{"repo_name": "handcrafted-persona-engine", "file_name": "/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCFilter.cs", "inference_info": {"prefix_code": "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCFilter : IAudioFilter, IDisposable\n{\n private const int ProcessingSampleRate = 16000;\n\n private const int OutputSampleRate = 32000;\n\n private const int FinalSampleRate = 24000;\n\n private const int MaxInputDuration = 30; // seconds\n\n private readonly SemaphoreSlim _initLock = new(1, 1);\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly IDisposable? _optionsChangeRegistration;\n\n private readonly IOptionsMonitor _optionsMonitor;\n\n private readonly IRVCVoiceProvider _rvcVoiceProvider;\n\n private RVCFilterOptions _currentOptions;\n\n private bool _disposed;\n\n private IF0Predictor? _f0Predictor;\n\n private OnnxRVC? _rvcModel;\n\n public RVCFilter(\n IOptionsMonitor optionsMonitor,\n IModelProvider modelProvider,\n IRVCVoiceProvider rvcVoiceProvider,\n ILogger logger)\n {\n _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));\n _modelProvider = modelProvider;\n _rvcVoiceProvider = rvcVoiceProvider;\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _currentOptions = optionsMonitor.CurrentValue;\n\n _ = InitializeAsync(_currentOptions);\n\n // Register for options changes\n _optionsChangeRegistration = _optionsMonitor.OnChange(OnOptionsChanged);\n }\n\n public void Process(AudioSegment audioSegment)\n {\n if ( _disposed )\n {\n throw new ObjectDisposedException(nameof(RVCFilter));\n }\n\n if ( _rvcModel == null || _f0Predictor == null ||\n audioSegment?.AudioData == null || audioSegment.AudioData.Length == 0 )\n {\n return;\n }\n\n // Get the latest options for processing\n var options = _currentOptions;\n var originalSampleRate = audioSegment.SampleRate;\n\n if ( !options.Enabled )\n {\n return;\n }\n\n // Start timing\n var stopwatch = Stopwatch.StartNew();\n\n // Step 1: Resample input to processing sample rate\n var resampleRatioToProcessing = (int)Math.Ceiling((double)ProcessingSampleRate / originalSampleRate);\n var resampledInputSize = audioSegment.AudioData.Length * resampleRatioToProcessing;\n\n var resampledInput = ArrayPool.Shared.Rent(resampledInputSize);\n try\n {\n var inputSampleCount = AudioConverter.ResampleFloat(\n audioSegment.AudioData,\n resampledInput,\n 1,\n (uint)originalSampleRate,\n ProcessingSampleRate);\n\n // Step 2: Process with RVC model\n var maxInputSamples = OutputSampleRate * MaxInputDuration;\n var outputBufferSize = maxInputSamples + 2 * options.HopSize;\n\n var processingBuffer = ArrayPool.Shared.Rent(outputBufferSize);\n try\n {\n var processedSampleCount = _rvcModel.ProcessAudio(\n resampledInput.AsMemory(0, inputSampleCount),\n processingBuffer,\n _f0Predictor,\n options.SpeakerId,\n options.F0UpKey);\n\n // Step 3: Resample to original sample rate\n var resampleRatioToOutput = (int)Math.Ceiling((double)originalSampleRate / OutputSampleRate);\n var finalOutputSize = processedSampleCount * resampleRatioToOutput;\n\n var resampledOutput = ArrayPool.Shared.Rent(finalOutputSize);\n try\n {\n var finalSampleCount = AudioConverter.ResampleFloat(\n processingBuffer.AsMemory(0, processedSampleCount),\n resampledOutput,\n 1,\n OutputSampleRate,\n (uint)originalSampleRate);\n\n // Need one allocation for the final output buffer since AudioSegment keeps this reference\n var finalBuffer = new float[finalSampleCount];\n Array.Copy(resampledOutput, finalBuffer, finalSampleCount);\n\n audioSegment.AudioData = finalBuffer.AsMemory();\n audioSegment.SampleRate = FinalSampleRate;\n }\n finally\n {\n ArrayPool.Shared.Return(resampledOutput);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(processingBuffer);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(resampledInput);\n }\n\n // Stop timing after processing is complete\n stopwatch.Stop();\n var processingTime = stopwatch.Elapsed.TotalSeconds;\n\n // Calculate final audio duration (based on the processed audio)\n var finalAudioDuration = audioSegment.AudioData.Length / (double)FinalSampleRate;\n\n // Calculate real-time factor\n var realTimeFactor = finalAudioDuration / processingTime;\n\n // Log the results using ILogger\n _logger.LogInformation(\"Generated {AudioDuration:F2}s audio in {ProcessingTime:F2}s (x{RealTimeFactor:F2} real-time)\",\n finalAudioDuration, processingTime, realTimeFactor);\n }\n\n public int Priority => 100;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n ", "suffix_code": "\n\n private async void OnOptionsChanged(RVCFilterOptions newOptions)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( ShouldReinitialize(newOptions) )\n {\n DisposeResources();\n await InitializeAsync(newOptions);\n }\n\n _currentOptions = newOptions;\n }\n\n private bool ShouldReinitialize(RVCFilterOptions newOptions)\n {\n return _currentOptions.DefaultVoice != newOptions.DefaultVoice ||\n _currentOptions.HopSize != newOptions.HopSize;\n }\n\n private async ValueTask InitializeAsync(RVCFilterOptions options)\n {\n await _initLock.WaitAsync();\n try\n {\n var crepeModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCCrepeTiny);\n var hubertModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCHubert);\n var rvcModel = await _rvcVoiceProvider.GetVoiceAsync(options.DefaultVoice);\n\n // _f0Predictor = new CrepeOnnx(crepeModel.Path);\n _f0Predictor = new CrepeOnnxSimd(crepeModel.Path);\n // _f0Predictor = new ACFMethod(512, 16000);\n\n _rvcModel = new OnnxRVC(\n rvcModel,\n options.HopSize,\n hubertModel.Path);\n }\n finally\n {\n _initLock.Release();\n }\n }\n\n private void DisposeResources()\n {\n _rvcModel?.Dispose();\n _rvcModel = null;\n\n _f0Predictor?.Dispose();\n _f0Predictor = null;\n }\n}", "middle_code": "protected virtual void Dispose(bool disposing)\n {\n if ( _disposed )\n {\n return;\n }\n if ( disposing )\n {\n _optionsChangeRegistration?.Dispose();\n DisposeResources();\n }\n _disposed = true;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OnnxAudioSynthesizer.cs", "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of audio synthesis using ONNX models\n/// \npublic class OnnxAudioSynthesizer : IAudioSynthesizer\n{\n private readonly ITtsCache _cache;\n\n private readonly SemaphoreSlim _inferenceThrottle;\n\n private readonly IModelProvider _ittsModelProvider;\n\n private readonly ILogger _logger;\n\n private readonly IOptionsMonitor _options;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private bool _disposed;\n\n private IReadOnlyDictionary? _phonemeToIdMap;\n\n private InferenceSession? _synthesisSession;\n\n public OnnxAudioSynthesizer(\n IModelProvider ittsModelProvider,\n IKokoroVoiceProvider voiceProvider,\n ITtsCache cache,\n IOptionsMonitor options,\n ILogger logger)\n {\n _ittsModelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _voiceProvider = voiceProvider ?? throw new ArgumentNullException(nameof(voiceProvider));\n _cache = cache ?? throw new ArgumentNullException(nameof(cache));\n _options = options ?? throw new ArgumentNullException(nameof(options));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n // Create throttle to limit concurrent inference operations\n _inferenceThrottle = new SemaphoreSlim(\n Math.Max(1, Environment.ProcessorCount / 2), // Use half of available cores for inference\n Environment.ProcessorCount);\n\n _logger.LogInformation(\"Initialized ONNX audio synthesizer\");\n }\n\n /// \n /// Synthesizes audio from phonemes\n /// \n public async Task SynthesizeAsync(\n string phonemes,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(phonemes) )\n {\n return new AudioData(Array.Empty(), Array.Empty());\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n // Initialize lazily on first use\n await EnsureInitializedAsync(cancellationToken);\n\n // Get current options (to ensure we have the latest values)\n var currentOptions = options ?? _options.CurrentValue;\n\n // Validate phoneme length\n if ( phonemes.Length > currentOptions.MaxPhonemeLength )\n {\n _logger.LogWarning(\"Truncating phonemes to maximum length {MaxLength}\", currentOptions.MaxPhonemeLength);\n phonemes = phonemes.Substring(0, currentOptions.MaxPhonemeLength);\n }\n\n // Convert phonemes to tokens\n var tokens = ConvertPhonemesToTokens(phonemes);\n if ( tokens.Count == 0 )\n {\n _logger.LogWarning(\"No valid tokens generated from phonemes\");\n\n return new AudioData(Array.Empty(), Array.Empty());\n }\n\n // Get voice data\n var voice = await _voiceProvider.GetVoiceAsync(currentOptions.DefaultVoice, cancellationToken);\n\n // Create audio with throttling for inference\n await _inferenceThrottle.WaitAsync(cancellationToken);\n\n try\n {\n // Measure performance\n var timer = Stopwatch.StartNew();\n\n // Perform inference\n var (audioData, phonemeTimings) = await RunInferenceAsync(tokens, voice, options, cancellationToken);\n\n // Log performance metrics\n timer.Stop();\n LogPerformanceMetrics(timer.Elapsed, audioData.Length, phonemes.Length, options);\n\n return new AudioData(audioData, phonemeTimings);\n }\n finally\n {\n _inferenceThrottle.Release();\n }\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"Audio synthesis was canceled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during audio synthesis\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _synthesisSession?.Dispose();\n _synthesisSession = null;\n\n _phonemeToIdMap = null;\n _inferenceThrottle.Dispose();\n\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Ensures the model and resources are initialized\n /// \n private async Task EnsureInitializedAsync(CancellationToken cancellationToken)\n {\n if ( _synthesisSession != null && _phonemeToIdMap != null )\n {\n return;\n }\n\n // Load model and resources\n await InitializeSessionAsync(cancellationToken);\n await LoadPhonemeMapAsync(cancellationToken);\n }\n\n /// \n /// Initializes the ONNX inference session\n /// \n private async Task InitializeSessionAsync(CancellationToken cancellationToken)\n {\n if ( _synthesisSession != null )\n {\n return;\n }\n\n _logger.LogInformation(\"Initializing synthesis model\");\n\n // Create optimized session options\n var sessionOptions = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Math.Max(1, Environment.ProcessorCount / 2),\n IntraOpNumThreads = Math.Max(1, Environment.ProcessorCount / 2),\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n try\n {\n sessionOptions.AppendExecutionProvider_CUDA();\n _logger.LogInformation(\"CUDA execution provider added successfully\");\n }\n catch (Exception ex)\n {\n _logger.LogWarning(\"CUDA execution provider not available: {Message}. Using CPU.\", ex.Message);\n }\n\n // Get model with retry mechanism\n var maxRetries = 3;\n Exception? lastException = null;\n\n for ( var attempt = 0; attempt < maxRetries; attempt++ )\n {\n try\n {\n var model = await _ittsModelProvider.GetModelAsync(ModelType.KokoroSynthesis, cancellationToken);\n var modelData = await model.GetDataAsync();\n\n _synthesisSession = new InferenceSession(modelData, sessionOptions);\n _logger.LogInformation(\"Synthesis model initialized successfully\");\n\n return;\n }\n catch (Exception ex)\n {\n lastException = ex;\n _logger.LogWarning(ex, \"Error initializing ONNX session (attempt {Attempt} of {MaxRetries}). Retrying...\",\n attempt + 1, maxRetries);\n\n if ( attempt < maxRetries - 1 )\n {\n // Exponential backoff\n await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)), cancellationToken);\n }\n }\n }\n\n // If we get here, all attempts failed\n throw new InvalidOperationException(\n $\"Failed to initialize ONNX session after {maxRetries} attempts\", lastException);\n }\n\n /// \n /// Loads the phoneme-to-ID mapping\n /// \n private async Task LoadPhonemeMapAsync(CancellationToken cancellationToken)\n {\n if ( _phonemeToIdMap != null )\n {\n return;\n }\n\n _logger.LogInformation(\"Loading phoneme mapping\");\n\n try\n {\n // Use cache for phoneme map to avoid repeated loading\n _phonemeToIdMap = await _cache.GetOrAddAsync(\"phoneme_map\", async ct =>\n {\n var model = await _ittsModelProvider.GetModelAsync(ModelType.KokoroPhonemeMappings, ct);\n var mapPath = model.Path;\n\n _logger.LogDebug(\"Loading phoneme mapping from {Path}\", mapPath);\n\n var lines = await File.ReadAllLinesAsync(mapPath, ct);\n\n // Initialize with capacity for better performance\n var mapping = new Dictionary(lines.Length);\n\n foreach ( var line in lines )\n {\n if ( string.IsNullOrWhiteSpace(line) || line.Length < 3 )\n {\n continue;\n }\n\n mapping[line[0]] = long.Parse(line[2..]);\n }\n\n _logger.LogInformation(\"Loaded {Count} phoneme mappings\", mapping.Count);\n\n return mapping;\n }, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n /* Ignored */\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading phoneme mapping\");\n\n throw;\n }\n }\n\n /// \n /// Converts phoneme characters to token IDs\n /// \n private List ConvertPhonemesToTokens(string phonemes)\n {\n // If no mapping loaded, can't convert\n if ( _phonemeToIdMap == null )\n {\n throw new InvalidOperationException(\"Phoneme map not initialized\");\n }\n\n // Pre-allocate with expected capacity\n var tokens = new List(phonemes.Length);\n\n foreach ( var phoneme in phonemes )\n {\n if ( _phonemeToIdMap.TryGetValue(phoneme, out var id) )\n {\n tokens.Add(id);\n }\n }\n\n return tokens;\n }\n\n /// \n /// Runs model inference to generate audio\n /// \n private async Task<(Memory AudioData, Memory PhonemeTimings)> RunInferenceAsync(\n List tokens,\n VoiceData voice,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default)\n {\n // Make sure session is initialized\n if ( _synthesisSession == null )\n {\n throw new InvalidOperationException(\"Synthesis session not initialized\");\n }\n\n // Get current options (to ensure we have the latest values)\n var currentOptions = options ?? _options.CurrentValue;\n\n // Create model inputs\n var modelInputs = CreateModelInputs(tokens, voice, currentOptions.DefaultSpeed);\n\n // Run inference\n using var results = _synthesisSession.Run(modelInputs);\n\n // Extract results\n var waveformTensor = results[0].AsTensor();\n var durationTensor = results[1].AsTensor();\n\n // Extract result data\n var waveformLength = waveformTensor.Dimensions.Length > 0 ? waveformTensor.Dimensions[0] : 0;\n\n var waveform = new float[waveformLength];\n var durations = new long[durationTensor.Length];\n\n // Copy data to results\n Buffer.BlockCopy(waveformTensor.ToArray(), 0, waveform, 0, waveformLength * sizeof(float));\n Buffer.BlockCopy(durationTensor.ToArray(), 0, durations, 0, durations.Length * sizeof(long));\n\n // Apply audio processing if needed\n if ( currentOptions.TrimSilence )\n {\n waveform = TrimSilence(waveform);\n }\n\n return (waveform, durations);\n }\n\n /// \n /// Creates input tensors for the synthesis model\n /// \n private List CreateModelInputs(List tokens, VoiceData voice, float speed)\n {\n // Add boundary tokens (BOS/EOS)\n var tokenArray = ArrayPool.Shared.Rent(tokens.Count + 2);\n\n try\n {\n // BOS token\n tokenArray[0] = 0;\n\n // Copy tokens\n tokens.CopyTo(tokenArray, 1);\n\n // EOS token\n tokenArray[tokens.Count + 1] = 0;\n\n // Create tensors\n var inputTokens = new DenseTensor(\n tokenArray.AsMemory(0, tokens.Count + 2),\n new[] { 1, tokens.Count + 2 });\n\n var styleInput = voice.GetEmbedding(inputTokens.Dimensions).ToArray();\n var voiceEmbedding = new DenseTensor(styleInput, new[] { 1, styleInput.Length });\n\n var speedTensor = new DenseTensor(\n new[] { speed },\n new[] { 1 });\n\n // Return named tensors\n return new List { NamedOnnxValue.CreateFromTensor(\"input_ids\", inputTokens), NamedOnnxValue.CreateFromTensor(\"style\", voiceEmbedding), NamedOnnxValue.CreateFromTensor(\"speed\", speedTensor) };\n }\n finally\n {\n // Always return the rented array\n ArrayPool.Shared.Return(tokenArray);\n }\n }\n\n /// \n /// Trims silence from the beginning and end of audio data\n /// \n private float[] TrimSilence(float[] audioData, float threshold = 0.01f, int minSamples = 512)\n {\n if ( audioData.Length <= minSamples * 2 )\n {\n return audioData;\n }\n\n // Find start (first sample above threshold)\n var startIndex = 0;\n for ( var i = 0; i < audioData.Length - minSamples; i++ )\n {\n if ( Math.Abs(audioData[i]) > threshold )\n {\n startIndex = Math.Max(0, i - minSamples);\n\n break;\n }\n }\n\n // Find end (last sample above threshold)\n var endIndex = audioData.Length - 1;\n for ( var i = audioData.Length - 1; i >= minSamples; i-- )\n {\n if ( Math.Abs(audioData[i]) > threshold )\n {\n endIndex = Math.Min(audioData.Length - 1, i + minSamples);\n\n break;\n }\n }\n\n // If no significant audio found, return original\n if ( startIndex >= endIndex )\n {\n return audioData;\n }\n\n // Create trimmed array\n var newLength = endIndex - startIndex + 1;\n var result = new float[newLength];\n Array.Copy(audioData, startIndex, result, 0, newLength);\n\n return result;\n }\n\n /// \n /// Logs performance metrics for inference\n /// \n private void LogPerformanceMetrics(TimeSpan elapsed, int audioLength, int phonemeCount, KokoroVoiceOptions? options = null)\n {\n // Get current options to ensure we have the latest sample rate\n var currentOptions = options ?? _options.CurrentValue;\n\n var audioDuration = audioLength / (float)currentOptions.SampleRate;\n var elapsedSeconds = elapsed.TotalSeconds;\n var speedup = elapsedSeconds > 0 ? audioDuration / elapsedSeconds : 0;\n\n _logger.LogInformation(\n \"Generated {AudioDuration:F2}s audio for {PhonemeCount} phonemes in {Elapsed:F2}s (x{Speedup:F2} real-time)\",\n audioDuration, phonemeCount, elapsedSeconds, speedup);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/TtsConfigEditor.cs", "using System.Diagnostics;\nusing System.Numerics;\nusing System.Threading.Channels;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets.Dialogs;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.RVC;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for TTS section configuration\n/// \npublic class TtsConfigEditor : ConfigSectionEditorBase\n{\n private readonly IAudioOutputAdapter _audioPlayer;\n\n private readonly IRVCVoiceProvider _rvcProvider;\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly ITtsEngine _ttsEngine;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private List _availableRVCs = new();\n\n private List _availableVoices = new();\n\n private TtsConfiguration _currentConfig;\n\n private RVCFilterOptions _currentRvcFilterOptions;\n\n private KokoroVoiceOptions _currentVoiceOptions;\n\n private string _defaultRVC;\n\n private string _defaultVoice;\n\n private string _espeakPath;\n\n private bool _isPlaying = false;\n\n private bool _loadingRvcs = false;\n\n private bool _loadingVoices = false;\n\n private int _maxPhonemeLength;\n\n private string _modelDir;\n\n private ActiveOperation? _playbackOperation = null;\n\n private bool _rvcEnabled;\n\n private int _rvcF0UpKey;\n\n private int _rvcHopSize;\n\n private int _sampleRate;\n\n private float _speechRate;\n\n private string _testText = \"This is a test of the text-to-speech system.\";\n\n private bool _trimSilence;\n\n private bool _useBritishEnglish;\n\n public TtsConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n ITtsEngine ttsEngine,\n IOutputAdapter audioPlayer,\n IKokoroVoiceProvider voiceProvider,\n IUiThemeManager themeManager, IRVCVoiceProvider rvcProvider)\n : base(configManager, stateManager)\n {\n _ttsEngine = ttsEngine;\n _audioPlayer = (IAudioOutputAdapter)audioPlayer;\n _voiceProvider = voiceProvider;\n _themeManager = themeManager;\n _rvcProvider = rvcProvider;\n\n LoadConfiguration();\n\n // _audioPlayerHost.OnPlaybackStarted += OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted += OnPlaybackCompleted;\n }\n\n public override string SectionKey => \"TTS\";\n\n public override string DisplayName => \"TTS Configuration\";\n\n public override void Initialize()\n {\n // Load available voices\n LoadAvailableVoicesAsync();\n LoadAvailableRVCAsync();\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Main layout with tabs for different sections\n if ( ImGui.BeginTabBar(\"TtsConfigTabs\") )\n {\n // Basic settings tab\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettings();\n\n ImGui.EndTabItem();\n }\n\n // Advanced settings tab\n if ( ImGui.BeginTabItem(\"Advanced Settings\") )\n {\n RenderAdvancedSettings();\n ImGui.EndTabItem();\n }\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n // Reset button at bottom\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all TTS settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n public override void Update(float deltaTime)\n {\n // Simplified update just for playback operation\n if ( _playbackOperation != null && _isPlaying )\n {\n _playbackOperation.Progress += deltaTime * 0.1f;\n if ( _playbackOperation.Progress > 0.99f )\n {\n _playbackOperation.Progress = 0.99f;\n }\n }\n }\n\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args);\n\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n }\n }\n\n public override void Dispose()\n {\n // Unsubscribe from audio player events\n // _audioPlayerHost.OnPlaybackStarted -= OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted -= OnPlaybackCompleted;\n\n // Cancel any active playback\n StopPlayback();\n\n base.Dispose();\n }\n\n #region Configuration Management\n\n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(\"TTS\");\n _currentVoiceOptions = _currentConfig.Voice;\n _currentRvcFilterOptions = _currentConfig.Rvc;\n\n // Update local fields from configuration\n _modelDir = _currentConfig.ModelDirectory;\n _espeakPath = _currentConfig.EspeakPath;\n _speechRate = _currentVoiceOptions.DefaultSpeed;\n _sampleRate = _currentVoiceOptions.SampleRate;\n _trimSilence = _currentVoiceOptions.TrimSilence;\n _useBritishEnglish = _currentVoiceOptions.UseBritishEnglish;\n _defaultVoice = _currentVoiceOptions.DefaultVoice;\n _maxPhonemeLength = _currentVoiceOptions.MaxPhonemeLength;\n\n // RVC\n _defaultRVC = _currentRvcFilterOptions.DefaultVoice;\n _rvcEnabled = _currentRvcFilterOptions.Enabled;\n _rvcHopSize = _currentRvcFilterOptions.HopSize;\n _rvcF0UpKey = _currentRvcFilterOptions.F0UpKey;\n }\n\n private async void LoadAvailableVoicesAsync()\n {\n try\n {\n _loadingVoices = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-voices\", \"Loading Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _voiceProvider.GetAvailableVoicesAsync();\n _availableVoices = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableVoices = [];\n }\n finally\n {\n _loadingVoices = false;\n }\n }\n\n private async void LoadAvailableRVCAsync()\n {\n try\n {\n _loadingRvcs = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-rvc\", \"Loading RVC Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _rvcProvider.GetAvailableVoicesAsync();\n _availableRVCs = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableRVCs = [];\n }\n finally\n {\n _loadingRvcs = false;\n }\n }\n\n private void UpdateConfiguration()\n {\n var updatedVoiceOptions = new KokoroVoiceOptions {\n DefaultVoice = _defaultVoice,\n DefaultSpeed = _speechRate,\n SampleRate = _sampleRate,\n TrimSilence = _trimSilence,\n UseBritishEnglish = _useBritishEnglish,\n MaxPhonemeLength = _maxPhonemeLength\n };\n\n var updatedRVCOptions = new RVCFilterOptions { DefaultVoice = _defaultRVC, Enabled = _rvcEnabled, HopSize = _rvcHopSize, F0UpKey = _rvcF0UpKey };\n\n var updatedConfig = new TtsConfiguration { ModelDirectory = _modelDir, EspeakPath = _espeakPath, Voice = updatedVoiceOptions, Rvc = updatedRVCOptions };\n\n _currentRvcFilterOptions = updatedRVCOptions;\n _currentVoiceOptions = updatedVoiceOptions;\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(updatedConfig, SectionKey);\n\n MarkAsChanged();\n }\n\n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved();\n }\n\n private void ResetToDefaults()\n {\n // Create default configuration\n var defaultVoiceOptions = new KokoroVoiceOptions();\n var defaultConfig = new TtsConfiguration();\n\n // Update local state\n _currentVoiceOptions = defaultVoiceOptions;\n _currentConfig = defaultConfig;\n\n // Update UI fields\n _modelDir = defaultConfig.ModelDirectory;\n _espeakPath = defaultConfig.EspeakPath;\n _speechRate = defaultVoiceOptions.DefaultSpeed;\n _sampleRate = defaultVoiceOptions.SampleRate;\n _trimSilence = defaultVoiceOptions.TrimSilence;\n _useBritishEnglish = defaultVoiceOptions.UseBritishEnglish;\n _defaultVoice = defaultVoiceOptions.DefaultVoice;\n _maxPhonemeLength = defaultVoiceOptions.MaxPhonemeLength;\n\n // Update configuration\n ConfigManager.UpdateConfiguration(defaultConfig, \"TTS\");\n MarkAsChanged();\n }\n\n #endregion\n\n #region Playback Controls\n\n private async void StartPlayback()\n {\n if ( _isPlaying || string.IsNullOrWhiteSpace(_testText) )\n {\n return;\n }\n\n try\n {\n // Create a new playback operation\n _playbackOperation = new ActiveOperation(\"tts-playback\", \"Playing TTS\");\n StateManager.RegisterActiveOperation(_playbackOperation);\n\n _isPlaying = true;\n\n var options = _currentVoiceOptions;\n\n var llmInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var ttsOutput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioEvents = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); // Tts Started/Tts Ended - Audio Started/Audio Ended\n\n await llmInput.Writer.WriteAsync(new LlmChunkEvent(Guid.Empty, Guid.Empty, DateTimeOffset.UtcNow, _testText), _playbackOperation.CancellationSource.Token);\n llmInput.Writer.Complete();\n\n _ = Task.Run(async () =>\n {\n await foreach(var ttsOut in ttsOutput.Reader.ReadAllAsync(_playbackOperation.CancellationSource.Token))\n {\n if ( ttsOut is TtsChunkEvent ttsChunk )\n {\n await audioInput.Writer.WriteAsync(ttsChunk, _playbackOperation.CancellationSource.Token);\n }\n }\n });\n\n _ = _ttsEngine.SynthesizeStreamingAsync(\n llmInput,\n ttsOutput,\n Guid.Empty,\n Guid.Empty,\n options,\n _playbackOperation.CancellationSource.Token\n );\n\n await _audioPlayer.SendAsync(audioInput, audioEvents, Guid.Empty, _playbackOperation.CancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"TTS playback cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during TTS playback: {ex.Message}\");\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n }\n\n private void StopPlayback()\n {\n if ( _playbackOperation != null )\n {\n _playbackOperation.CancellationSource.Cancel();\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n\n _isPlaying = false;\n }\n\n private void OnPlaybackStarted(object sender, EventArgs args)\n {\n _isPlaying = true;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 0.0f;\n }\n }\n\n private void OnPlaybackCompleted(object sender, EventArgs args)\n {\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 1.0f;\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n\n #endregion\n\n #region UI Rendering Methods\n\n private void RenderTestingSection()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Playground\");\n ImGui.Spacing();\n\n // Text input frame with light background\n ImGui.Text(\"Test Text:\");\n ImGui.SetNextItemWidth(availWidth);\n ImGui.InputTextMultiline(\"##TestText\", ref _testText, 1000, new Vector2(0, 80));\n\n ImGui.Spacing();\n ImGui.Spacing();\n\n // Controls section with better layout\n ImGui.BeginGroup();\n {\n // Left side: Example selector\n var controlWidth = Math.Min(180, availWidth * 0.4f);\n ImGui.SetNextItemWidth(controlWidth);\n\n if ( ImGui.BeginCombo(\"##exampleLbl\", \"Select Example\") )\n {\n string[] examples = { \"Hello, world!\", \"The quick brown fox jumps over the lazy dog.\", \"Welcome to the text-to-speech system.\", \"How are you doing today?\", \"Today's date is March 3rd, 2025.\" };\n\n foreach ( var example in examples )\n {\n var isSelected = _testText == example;\n if ( ImGui.Selectable(example, ref isSelected) )\n {\n _testText = example;\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.SameLine(0, 15);\n\n var clearDisabled = string.IsNullOrEmpty(_testText);\n if ( clearDisabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( ImGui.Button(\"Clear\", new Vector2(80, 0)) && !string.IsNullOrEmpty(_testText) )\n {\n _testText = \"\";\n }\n\n if ( clearDisabled )\n {\n ImGui.EndDisabled();\n }\n }\n\n ImGui.EndGroup();\n\n ImGui.SameLine(0, 10);\n\n // Playback controls in a styled frame\n {\n // Play/Stop button with color styling\n if ( _isPlaying )\n {\n if ( UiStyler.AnimatedButton(\"Stop\", new Vector2(80, 0), _isPlaying) )\n {\n StopPlayback();\n }\n\n ImGui.SameLine(0, 15);\n ImGui.ProgressBar(_playbackOperation?.Progress ?? 0, new Vector2(-1, 0), \"Playing\");\n }\n else\n {\n var disabled = string.IsNullOrWhiteSpace(_testText);\n if ( disabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( UiStyler.AnimatedButton(\"Play\", new Vector2(80, 0), _isPlaying) )\n {\n StartPlayback();\n }\n\n if ( disabled )\n {\n ImGui.EndDisabled();\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Enter some text to play\");\n }\n }\n }\n }\n }\n\n private void RenderBasicSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // === Voice Selection Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Voice Settings\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingVoices )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading voices...\";\n ImGui.InputText(\"##VoiceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n if ( ImGui.BeginCombo(\"##VoiceSelector\", string.IsNullOrEmpty(_defaultVoice) ? \"\" : _defaultRVC) )\n {\n if ( _availableRVCs.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No voices available\");\n }\n else\n {\n foreach ( var voice in _availableRVCs )\n {\n var isSelected = voice == _defaultRVC;\n if ( ImGui.Selectable(voice, isSelected) )\n {\n _defaultRVC = voice;\n UpdateConfiguration();\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh##RefreshRVC\", new Vector2(-1, 0)) )\n {\n LoadAvailableRVCAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available voices list\");\n }\n\n if ( ImGui.BeginTable(\"RVCProps\", 4, ImGuiTableFlags.SizingFixedFit) )\n {\n ImGui.TableSetupColumn(\"1\", 100f);\n ImGui.TableSetupColumn(\"2\", 200f);\n ImGui.TableSetupColumn(\"3\", 100f);\n ImGui.TableSetupColumn(\"4\", 200f);\n\n // Hop Size\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Hop Size\");\n ImGui.TableNextColumn();\n var fontSizeChanged = ImGui.InputInt(\"##HopSize\", ref _rvcHopSize, 8);\n if ( fontSizeChanged )\n {\n _rvcHopSize = Math.Clamp(_rvcHopSize, 8, 256);\n rvcConfigChanged = true;\n }\n\n // F0 Key\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Pitch\");\n ImGui.TableNextColumn();\n var pitchChanged = ImGui.InputInt(\"##Pitch\", ref _rvcF0UpKey, 1);\n if ( pitchChanged )\n {\n _rvcF0UpKey = Math.Clamp(_rvcF0UpKey, -20, 20);\n rvcConfigChanged = true;\n }\n\n ImGui.EndTable();\n }\n\n if ( !_rvcEnabled )\n {\n ImGui.EndDisabled();\n }\n\n if ( rvcConfigChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n private void RenderAdvancedSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Section header\n ImGui.Spacing();\n ImGui.SeparatorText(\"Advanced TTS Settings\");\n ImGui.Spacing();\n\n var sampleRateChanged = false;\n var phonemeChanged = false;\n\n // ImGui.BeginDisabled();\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Sample Rate:\");\n ImGui.SameLine(200);\n\n string[] sampleRates = [\"16000 Hz (Low quality)\", \"24000 Hz (Standard quality)\", \"32000 Hz (Good quality)\", \"44100 Hz (High quality)\", \"48000 Hz (Studio quality)\"];\n int[] rateValues = [16000, 24000, 32000, 44100, 48000];\n\n var currentIdx = Array.IndexOf(rateValues, _sampleRate);\n if ( currentIdx < 0 )\n {\n currentIdx = 1; // Default to 24000 Hz\n }\n\n ImGui.SetNextItemWidth(availWidth - 200);\n\n if ( ImGui.BeginCombo(\"##SampleRate\", sampleRates[currentIdx]) )\n {\n for ( var i = 0; i < sampleRates.Length; i++ )\n {\n var isSelected = i == currentIdx;\n if ( ImGui.Selectable(sampleRates[i], isSelected) )\n {\n _sampleRate = rateValues[i];\n sampleRateChanged = true;\n }\n\n // Show additional info on hover\n if ( ImGui.IsItemHovered() )\n {\n var tooltipText = i switch {\n 0 => \"Low quality, minimal resource usage\",\n 1 => \"Standard quality, recommended for most uses\",\n 2 => \"Good quality, balanced resource usage\",\n 3 => \"High quality, CD audio standard\",\n 4 => \"Studio quality, higher resource usage\",\n _ => \"\"\n };\n\n ImGui.SetTooltip(tooltipText);\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.EndDisabled();\n }\n\n ImGui.EndGroup();\n\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Max Phoneme Length:\");\n ImGui.SameLine(200);\n\n ImGui.SetNextItemWidth(120);\n phonemeChanged = ImGui.InputInt(\"##MaxPhonemeLength\", ref _maxPhonemeLength);\n ImGui.EndDisabled();\n\n // Clamp value to valid range\n if ( phonemeChanged )\n {\n var oldValue = _maxPhonemeLength;\n _maxPhonemeLength = Math.Clamp(_maxPhonemeLength, 1, 2048);\n\n if ( oldValue != _maxPhonemeLength )\n {\n ImGui.TextColored(new Vector4(1.0f, 0.7f, 0.3f, 1.0f),\n \"Value clamped to valid range (1-2048)\");\n }\n }\n\n // Helper text\n ImGui.Spacing();\n ImGui.TextWrapped(\"This is already setup correctly to work with Kokoro. Shouldn't have to change!\");\n\n // === Paths & Resources Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Paths & Resources\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n // Model directory\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Model Directory:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var modelDirChanged = ImGui.InputText(\"##ModelDir\", ref _modelDir, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##ModelDir\", new Vector2(-1, 0)) )\n {\n var fileDialog = new OpenFolderDialog(_modelDir);\n fileDialog.Show();\n if ( fileDialog.SelectedFolder != null )\n {\n _modelDir = fileDialog.SelectedFolder;\n modelDirChanged = true;\n }\n }\n\n // Espeak path\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Espeak Path:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var espeakPathChanged = ImGui.InputText(\"##EspeakPath\", ref _espeakPath, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##EspeakPath\", new Vector2(-1, 0)) )\n {\n // In a real app, this would open a file browser dialog\n Console.WriteLine(\"Open file browser for Espeak Path\");\n }\n\n // Apply changes if needed\n if ( modelDirChanged || espeakPathChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n ImGui.EndGroup();\n\n if ( sampleRateChanged || phonemeChanged )\n {\n UpdateConfiguration();\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/OnnxRVC.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class OnnxRVC : IDisposable\n{\n private readonly ArrayPool _arrayPool;\n\n private readonly int _hopSize;\n\n private readonly InferenceSession _model;\n\n private readonly ArrayPool _shortArrayPool;\n\n // Preallocated buffers and tensors\n private readonly DenseTensor _speakerIdTensor;\n\n private readonly ContentVec _vecModel;\n\n public OnnxRVC(string modelPath, int hopsize, string vecPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR\n };\n\n options.AppendExecutionProvider_CUDA();\n \n _model = new InferenceSession(modelPath, options);\n _hopSize = hopsize;\n _vecModel = new ContentVec(vecPath);\n\n // Preallocate the speaker ID tensor\n _speakerIdTensor = new DenseTensor(new[] { 1 });\n\n // Create array pools for temporary buffers\n _arrayPool = ArrayPool.Shared;\n _shortArrayPool = ArrayPool.Shared;\n }\n\n public void Dispose()\n {\n _model?.Dispose();\n _vecModel?.Dispose();\n }\n\n public int ProcessAudio(ReadOnlyMemory inputAudio, Memory outputAudio,\n IF0Predictor f0Predictor, int speakerId, int f0UpKey)\n {\n // Early exit if input is empty\n if ( inputAudio.Length == 0 )\n {\n return 0;\n }\n\n // Check if output buffer is large enough\n if ( outputAudio.Length < inputAudio.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(outputAudio));\n }\n\n // Set the speaker ID\n _speakerIdTensor[0] = speakerId;\n\n // Process the audio\n return ProcessInPlace(inputAudio, outputAudio, f0Predictor, _speakerIdTensor, f0UpKey);\n }\n\n private int ProcessInPlace(ReadOnlyMemory input, Memory output,\n IF0Predictor f0Predictor,\n DenseTensor speakerIdTensor, int f0UpKey)\n {\n const int f0Min = 50;\n const int f0Max = 1100;\n var f0MelMin = 1127 * Math.Log(1 + f0Min / 700.0);\n var f0MelMax = 1127 * Math.Log(1 + f0Max / 700.0);\n\n if ( input.Length / 16000.0 > 30.0 )\n {\n throw new Exception(\"Audio segment is too long (>30s)\");\n }\n\n // Calculate original scale for normalization (matching original implementation)\n var minValue = float.MaxValue;\n var maxValue = float.MinValue;\n var inputSpan = input.Span;\n for ( var i = 0; i < input.Length; i++ )\n {\n minValue = Math.Min(minValue, inputSpan[i]);\n maxValue = Math.Max(maxValue, inputSpan[i]);\n }\n\n var originalScale = maxValue - minValue;\n\n // Get the hubert features\n var hubert = _vecModel.Forward(input);\n\n // Repeat and transpose the features\n var hubertRepeated = RVCUtils.RepeatTensor(hubert, 2);\n hubertRepeated = RVCUtils.Transpose(hubertRepeated, 0, 2, 1);\n\n hubert = null; // Allow for garbage collection\n\n var hubertLength = hubertRepeated.Dimensions[1];\n var hubertLengthTensor = new DenseTensor(new[] { 1 }) { [0] = hubertLength };\n\n // Allocate buffers for F0 calculations\n var f0Buffer = _arrayPool.Rent(hubertLength);\n var f0Memory = new Memory(f0Buffer, 0, hubertLength);\n\n try\n {\n // Calculate F0 directly into buffer\n f0Predictor.ComputeF0(input, f0Memory, hubertLength);\n\n // Create pitch tensors\n var pitchBuffer = _arrayPool.Rent(hubertLength);\n var pitchTensor = new DenseTensor(new[] { 1, hubertLength });\n var pitchfTensor = new DenseTensor(new[] { 1, hubertLength });\n\n try\n {\n // Apply pitch shift and convert to mel scale\n for ( var i = 0; i < hubertLength; i++ )\n {\n // Apply pitch shift\n var shiftedF0 = f0Buffer[i] * (float)Math.Pow(2, f0UpKey / 12.0);\n pitchfTensor[0, i] = shiftedF0;\n\n // Convert to mel scale for pitch\n var f0Mel = 1127 * Math.Log(1 + shiftedF0 / 700.0);\n if ( f0Mel > 0 )\n {\n f0Mel = (f0Mel - f0MelMin) * 254 / (f0MelMax - f0MelMin) + 1;\n f0Mel = Math.Round(f0Mel);\n }\n\n if ( f0Mel <= 1 )\n {\n f0Mel = 1;\n }\n\n if ( f0Mel > 255 )\n {\n f0Mel = 255;\n }\n\n pitchTensor[0, i] = (long)f0Mel;\n }\n\n // Generate random noise tensor\n var rndTensor = new DenseTensor(new[] { 1, 192, hubertLength });\n var random = new Random();\n for ( var i = 0; i < 192 * hubertLength; i++ )\n {\n rndTensor[0, i / hubertLength, i % hubertLength] = (float)random.NextDouble();\n }\n\n // Run the model\n var outWav = Forward(hubertRepeated, hubertLengthTensor, pitchTensor,\n pitchfTensor, speakerIdTensor, rndTensor);\n\n // Apply padding to match original implementation\n // (adding padding at the end only, like in original Pad method)\n var paddedSize = outWav.Length + 2 * _hopSize;\n var paddedOutput = _shortArrayPool.Rent(paddedSize);\n try\n {\n // Copy original output to the beginning of padded output\n for ( var i = 0; i < outWav.Length; i++ )\n {\n paddedOutput[i] = outWav[i];\n }\n // Rest of array is already zeroed when rented from pool\n\n // Find min and max values for normalization\n var minOutValue = short.MaxValue;\n var maxOutValue = short.MinValue;\n for ( var i = 0; i < outWav.Length; i++ )\n {\n minOutValue = Math.Min(minOutValue, outWav[i]);\n maxOutValue = Math.Max(maxOutValue, outWav[i]);\n }\n\n // Copy the output to the buffer with normalization matching original\n var outputSpan = output.Span;\n if ( outputSpan.Length < paddedSize )\n {\n throw new InvalidOperationException($\"Output buffer too small. Needed {paddedSize}, but only had {outputSpan.Length}\");\n }\n\n var maxLen = Math.Min(paddedSize, outputSpan.Length);\n\n // Apply normalization that matches the original implementation\n float range = maxOutValue - minOutValue;\n if ( range > 0 )\n {\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = paddedOutput[i] * originalScale / range;\n }\n }\n else\n {\n // Handle edge case where all values are the same\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = 0;\n }\n }\n\n return outWav.Length;\n }\n finally\n {\n _shortArrayPool.Return(paddedOutput);\n }\n }\n finally\n {\n _arrayPool.Return(pitchBuffer);\n }\n }\n finally\n {\n _arrayPool.Return(f0Buffer);\n }\n }\n\n private short[] Forward(DenseTensor hubert, DenseTensor hubertLength,\n DenseTensor pitch, DenseTensor pitchf,\n DenseTensor speakerId, DenseTensor noise)\n {\n var inputs = new List {\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(0), hubert),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(1), hubertLength),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(2), pitch),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(3), pitchf),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(4), speakerId),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(5), noise)\n };\n\n var results = _model.Run(inputs);\n var output = results.First().AsTensor();\n\n return output.Select(x => (short)(x * 32767)).ToArray();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsEngine.cs", "using System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.LLM;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Main TTS engine implementation\n/// \npublic class TtsEngine : ITtsEngine\n{\n private readonly IList _audioFilters;\n\n private readonly ILogger _logger;\n\n private readonly IOptionsMonitor _options;\n\n private readonly IPhonemizer _phonemizer;\n\n private readonly IAudioSynthesizer _synthesizer;\n\n private readonly IList _textFilters;\n\n private readonly ITextProcessor _textProcessor;\n\n private readonly SemaphoreSlim _throttle;\n\n private bool _disposed;\n\n public TtsEngine(\n ITextProcessor textProcessor,\n IPhonemizer phonemizer,\n IAudioSynthesizer synthesizer,\n IOptionsMonitor options,\n IEnumerable audioFilters,\n IEnumerable textFilters,\n ILoggerFactory loggerFactory)\n {\n _textProcessor = textProcessor ?? throw new ArgumentNullException(nameof(textProcessor));\n _phonemizer = phonemizer ?? throw new ArgumentNullException(nameof(phonemizer));\n _synthesizer = synthesizer ?? throw new ArgumentNullException(nameof(synthesizer));\n _options = options;\n _audioFilters = audioFilters.OrderByDescending(x => x.Priority).ToList();\n _textFilters = textFilters.OrderByDescending(x => x.Priority).ToList();\n _logger = loggerFactory?.CreateLogger() ?? throw new ArgumentNullException(nameof(loggerFactory));\n\n _throttle = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount);\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _throttle.Dispose();\n _disposed = true;\n }\n\n public async Task SynthesizeStreamingAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default\n )\n {\n var textBuffer = new StringBuilder(4096);\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n\n try\n {\n await foreach ( var (_, _, _, textChunk) in inputReader.ReadAllAsync(cancellationToken).ConfigureAwait(false) )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n break;\n }\n\n if ( string.IsNullOrEmpty(textChunk) )\n {\n continue;\n }\n\n textBuffer.Append(textChunk);\n var currentText = textBuffer.ToString();\n\n var processedText = await _textProcessor.ProcessAsync(currentText, cancellationToken);\n var sentences = processedText.Sentences;\n\n if ( sentences.Count <= 1 )\n {\n continue;\n }\n\n // Process all sentences except the last one(which might be incomplete)\n for ( var i = 0; i < sentences.Count - 1; i++ )\n {\n var sentence = sentences[i].Trim();\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n continue;\n }\n\n await foreach ( var segment in ProcessSentenceAsync(sentence, options, cancellationToken) )\n {\n ApplyAudioFilters(segment);\n\n if ( firstChunk )\n {\n var firstChunkEvent = new TtsStreamStartEvent(sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, cancellationToken).ConfigureAwait(false);\n\n firstChunk = false;\n }\n\n var chunkEvent = new TtsChunkEvent(sessionId, turnId, DateTimeOffset.UtcNow, segment);\n await outputWriter.WriteAsync(chunkEvent, cancellationToken).ConfigureAwait(false);\n }\n }\n\n textBuffer.Clear();\n textBuffer.Append(sentences[^1]);\n }\n\n var remainingText = textBuffer.ToString().Trim();\n if ( !string.IsNullOrEmpty(remainingText) )\n {\n await foreach ( var segment in ProcessSentenceAsync(remainingText, options, cancellationToken) )\n {\n ApplyAudioFilters(segment);\n\n if ( firstChunk )\n {\n var firstChunkEvent = new TtsStreamStartEvent(sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, cancellationToken).ConfigureAwait(false);\n\n firstChunk = false;\n }\n \n var chunkEvent = new TtsChunkEvent(sessionId, turnId, DateTimeOffset.UtcNow, segment);\n await outputWriter.WriteAsync(chunkEvent, cancellationToken).ConfigureAwait(false);\n }\n }\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n\n await outputWriter.WriteAsync(new ErrorOutputEvent(sessionId, turnId, DateTimeOffset.UtcNow, ex), cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n if ( !firstChunk )\n {\n await outputWriter.WriteAsync(new TtsStreamEndEvent(sessionId, turnId, DateTimeOffset.UtcNow, completedReason), cancellationToken).ConfigureAwait(false);\n }\n }\n\n return completedReason;\n }\n\n /// \n /// Processes a single sentence for synthesis\n /// \n private async IAsyncEnumerable ProcessSentenceAsync(\n string sentence,\n KokoroVoiceOptions? options = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n yield break;\n }\n\n await _throttle.WaitAsync(cancellationToken);\n\n var currentOptions = options ?? _options.CurrentValue;\n\n try\n {\n // Apply text filters before processing\n var processedText = sentence;\n var textFilterResults = new List(_textFilters.Count);\n\n foreach ( var textFilter in _textFilters )\n {\n var filterResult = await textFilter.ProcessAsync(processedText, cancellationToken);\n processedText = filterResult.ProcessedText;\n\n textFilterResults.Add(filterResult);\n }\n\n // Get phonemes\n var phonemeResult = await _phonemizer.ToPhonemesAsync(processedText, cancellationToken);\n\n // Process each phoneme chunk\n foreach ( var phonemeChunk in SplitPhonemes(phonemeResult.Phonemes, 510) )\n {\n // Get audio\n var audioData = await _synthesizer.SynthesizeAsync(\n phonemeChunk,\n currentOptions,\n cancellationToken);\n\n // Apply timing\n ApplyTokenTimings(\n phonemeResult.Tokens,\n currentOptions,\n audioData.PhonemeTimings);\n\n // Return segment\n var segment = new AudioSegment(\n audioData.Samples,\n options?.SampleRate ?? _options.CurrentValue.SampleRate,\n phonemeResult.Tokens);\n\n for ( var index = 0; index < _textFilters.Count; index++ )\n {\n var textFilter = _textFilters[index];\n var textFilterResult = textFilterResults[index];\n await textFilter.PostProcessAsync(textFilterResult, segment, cancellationToken);\n }\n\n yield return segment;\n }\n }\n finally\n {\n _throttle.Release();\n }\n }\n\n /// \n /// Splits phonemes into manageable chunks\n /// \n private IEnumerable SplitPhonemes(string phonemes, int maxLength)\n {\n if ( string.IsNullOrEmpty(phonemes) )\n {\n yield return string.Empty;\n\n yield break;\n }\n\n if ( phonemes.Length <= maxLength )\n {\n yield return phonemes;\n\n yield break;\n }\n\n var currentIndex = 0;\n while ( currentIndex < phonemes.Length )\n {\n var remainingLength = phonemes.Length - currentIndex;\n var chunkSize = Math.Min(maxLength, remainingLength);\n\n // Find a good breakpoint (whitespace or punctuation)\n if ( chunkSize < remainingLength && chunkSize > 10 )\n {\n // Look backwards from the end to find a good breakpoint\n for ( var i = currentIndex + chunkSize - 1; i > currentIndex + 10; i-- )\n {\n if ( char.IsWhiteSpace(phonemes[i]) || IsPunctuation(phonemes[i]) )\n {\n chunkSize = i - currentIndex + 1;\n\n break;\n }\n }\n }\n\n yield return phonemes.Substring(currentIndex, chunkSize);\n currentIndex += chunkSize;\n }\n }\n\n private bool IsPunctuation(char c) { return \".,:;!?-—()[]{}\\\"'\".Contains(c); }\n\n private void ApplyAudioFilters(AudioSegment audioSegment)\n {\n foreach ( var audioFilter in _audioFilters )\n {\n audioFilter.Process(audioSegment);\n }\n }\n\n /// \n /// Applies timing information to tokens\n /// \n private void ApplyTokenTimings(\n IReadOnlyList tokens,\n KokoroVoiceOptions options,\n ReadOnlyMemory phonemeTimings)\n {\n // Skip if no timing information\n if ( tokens.Count == 0 || phonemeTimings.Length < 3 )\n {\n return;\n }\n\n var timingsSpan = phonemeTimings.Span;\n\n // Magic scaling factor for timing conversion\n const int TIME_DIVISOR = 80;\n\n // Start with boundary tokens (often token)\n var leftTime = options.TrimSilence ? 0 : 2 * Math.Max(0, timingsSpan[0] - 3);\n var rightTime = leftTime;\n\n // Process each token\n var timingIndex = 1;\n foreach ( var token in tokens )\n {\n // Skip tokens without phonemes\n if ( string.IsNullOrEmpty(token.Phonemes) )\n {\n // Handle whitespace timing specially\n if ( token.Whitespace == \" \" && timingIndex + 1 < timingsSpan.Length )\n {\n timingIndex++;\n leftTime = rightTime + timingsSpan[timingIndex];\n rightTime = leftTime + timingsSpan[timingIndex];\n timingIndex++;\n }\n\n continue;\n }\n\n // Calculate end index for this token's phonemes\n var endIndex = timingIndex + (token.Phonemes?.Length ?? 0);\n if ( endIndex >= phonemeTimings.Length )\n {\n continue;\n }\n\n // Start time for this token\n var startTime = (double)leftTime / TIME_DIVISOR;\n\n // Sum durations for all phonemes in this token\n var tokenDuration = 0L;\n for ( var i = timingIndex; i < endIndex && i < timingsSpan.Length; i++ )\n {\n tokenDuration += timingsSpan[i];\n }\n\n // Handle whitespace after token\n var spaceDuration = token.Whitespace == \" \" && endIndex < timingsSpan.Length\n ? timingsSpan[endIndex]\n : 0;\n\n // Calculate end time\n leftTime = rightTime + 2 * tokenDuration + spaceDuration;\n var endTime = (double)leftTime / TIME_DIVISOR;\n rightTime = leftTime + spaceDuration;\n\n // Add token with timing\n token.StartTs = startTime;\n token.EndTs = endTime;\n\n // Move to next token's timing\n timingIndex = endIndex + (token.Whitespace == \" \" ? 1 : 0);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/PcmResampler.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic class PcmResampler\n{\n // Constants for audio format\n private const int BYTES_PER_SAMPLE = 2;\n\n private const int MAX_FRAME_SIZE = 1920;\n\n private readonly float[] _filterCoefficients;\n\n private readonly int _filterDelay;\n\n // Filter configuration\n private readonly int _filterTaps;\n\n private readonly float[] _floatHistory;\n\n private readonly short[] _history;\n\n // Sample rate configuration\n\n // Pre-allocated working buffers\n private readonly short[] _inputSamples;\n\n private int _historyLength;\n\n // State tracking\n private float _position = 0.0f;\n\n public PcmResampler(int inputSampleRate = 48000, int outputSampleRate = 16000)\n {\n if ( inputSampleRate <= 0 || outputSampleRate <= 0 )\n {\n throw new ArgumentException(\"Sample rates must be positive values\");\n }\n\n InputSampleRate = inputSampleRate;\n OutputSampleRate = outputSampleRate;\n ResampleRatio = (float)InputSampleRate / OutputSampleRate;\n\n _filterTaps = DetermineOptimalFilterTaps(ResampleRatio);\n _filterDelay = _filterTaps / 2;\n\n var cutoffFrequency = Math.Min(0.45f * OutputSampleRate, 0.9f * OutputSampleRate / 2) / InputSampleRate;\n _filterCoefficients = GenerateLowPassFilter(_filterTaps, cutoffFrequency);\n\n _history = new short[_filterTaps + 10];\n _floatHistory = new float[_filterTaps + 10];\n _historyLength = 0;\n\n _inputSamples = new short[MAX_FRAME_SIZE];\n }\n\n public float ResampleRatio { get; }\n\n public int InputSampleRate { get; }\n\n public int OutputSampleRate { get; }\n\n private int DetermineOptimalFilterTaps(float ratio)\n {\n if ( Math.Abs(ratio - Math.Round(ratio)) < 0.01f )\n {\n return Math.Max(24, (int)(12 * ratio));\n }\n\n return Math.Max(36, (int)(18 * ratio));\n }\n\n private float[] GenerateLowPassFilter(int taps, float cutoff)\n {\n var coefficients = new float[taps];\n var center = taps / 2;\n\n var sum = 0.0;\n for ( var i = 0; i < taps; i++ )\n {\n if ( i == center )\n {\n coefficients[i] = (float)(2.0 * Math.PI * cutoff);\n }\n else\n {\n var x = 2.0 * Math.PI * cutoff * (i - center);\n coefficients[i] = (float)(Math.Sin(x) / x);\n }\n\n var window = 0.42 - 0.5 * Math.Cos(2.0 * Math.PI * i / (taps - 1))\n + 0.08 * Math.Cos(4.0 * Math.PI * i / (taps - 1));\n\n coefficients[i] *= (float)window;\n\n sum += coefficients[i];\n }\n\n for ( var i = 0; i < taps; i++ )\n {\n coefficients[i] /= (float)sum;\n }\n\n return coefficients;\n }\n\n public int Process(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length / BYTES_PER_SAMPLE;\n ConvertToShorts(input, _inputSamples, inputSampleCount);\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples * BYTES_PER_SAMPLE )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetSampleWithHistory(sampleIndex, _inputSamples, inputSampleCount);\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n if ( outputIndex < maxOutputSamples )\n {\n BinaryPrimitives.WriteInt16LittleEndian(\n output.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateHistory(_inputSamples, inputSampleCount);\n _position -= inputSampleCount;\n\n return outputIndex * BYTES_PER_SAMPLE;\n }\n\n public int Process(Stream input, Memory output)\n {\n var buffer = new byte[MAX_FRAME_SIZE * BYTES_PER_SAMPLE];\n var bytesRead = input.Read(buffer, 0, buffer.Length);\n\n return Process(buffer.AsSpan(0, bytesRead), output.Span);\n }\n\n public int ProcessInPlace(Span buffer)\n {\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length / BYTES_PER_SAMPLE;\n\n // Make a copy of the input for processing\n Span inputCopy = stackalloc short[inputSampleCount];\n for ( var i = 0; i < inputSampleCount; i++ )\n {\n inputCopy[i] = BinaryPrimitives.ReadInt16LittleEndian(buffer.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // Calculate positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n short sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _history[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n BinaryPrimitives.WriteInt16LittleEndian(\n buffer.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n // We need to keep the input history despite having processed in-place\n UpdateHistory(inputCopy.ToArray(), inputSampleCount);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount * BYTES_PER_SAMPLE;\n }\n\n public int ProcessFloat(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length;\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetFloatSampleWithHistory(sampleIndex, input);\n sum += sample * _filterCoefficients[tap];\n }\n\n if ( outputIndex < maxOutputSamples )\n {\n output[outputIndex] = sum;\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateFloatHistory(input);\n _position -= inputSampleCount;\n\n return outputIndex;\n }\n\n public int ProcessFloatInPlace(Span buffer)\n {\n // For in-place, we must work backward to avoid overwriting unprocessed input\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length;\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // First, store the full input for history and reference\n var inputCopy = new float[inputSampleCount];\n buffer.CopyTo(inputCopy);\n\n // Calculate sample positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n float sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _floatHistory[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0f;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n buffer[outputIndex] = sum;\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n UpdateFloatHistory(inputCopy);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount;\n }\n\n private short GetSampleWithHistory(int index, short[] inputSamples, int inputSampleCount)\n {\n if ( index >= 0 && index < inputSampleCount )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _history[_historyLength + index];\n }\n\n return 0;\n }\n\n private float GetFloatSampleWithHistory(int index, ReadOnlySpan inputSamples)\n {\n if ( index >= 0 && index < inputSamples.Length )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _floatHistory[_historyLength + index];\n }\n\n return 0f;\n }\n\n private void UpdateHistory(short[] currentFrame, int frameLength)\n {\n var samplesToKeep = Math.Min(frameLength, _history.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _history.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_history, _historyLength - unusedHistorySamples, _history, 0, unusedHistorySamples);\n }\n\n Array.Copy(currentFrame, frameLength - samplesToKeep, _history, unusedHistorySamples, samplesToKeep);\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _history.Length);\n }\n\n private void UpdateFloatHistory(ReadOnlySpan currentFrame)\n {\n var samplesToKeep = Math.Min(currentFrame.Length, _floatHistory.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _floatHistory.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_floatHistory, _historyLength - unusedHistorySamples, _floatHistory, 0, unusedHistorySamples);\n }\n\n for ( var i = 0; i < samplesToKeep; i++ )\n {\n _floatHistory[unusedHistorySamples + i] = currentFrame[currentFrame.Length - samplesToKeep + i];\n }\n\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _floatHistory.Length);\n }\n\n private void ConvertToShorts(ReadOnlySpan input, short[] output, int sampleCount)\n {\n for ( var i = 0; i < sampleCount; i++ )\n {\n output[i] = BinaryPrimitives.ReadInt16LittleEndian(input.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n }\n\n public void Reset()\n {\n _position = 0;\n _historyLength = 0;\n Array.Clear(_history, 0, _history.Length);\n Array.Clear(_floatHistory, 0, _floatHistory.Length);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/RealtimeTranscriptor.cs", "using System.Diagnostics;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.ASR.VAD;\nusing PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\ninternal class RealtimeTranscriptor : IRealtimeSpeechTranscriptor, IAsyncDisposable\n{\n private readonly object cacheLock = new();\n\n private readonly ILogger logger;\n\n private readonly RealtimeSpeechTranscriptorOptions options;\n\n private readonly RealtimeOptions realtimeOptions;\n\n private readonly ISpeechTranscriptorFactory? recognizingSpeechTranscriptorFactory;\n\n private readonly ISpeechTranscriptorFactory speechTranscriptorFactory;\n\n private readonly Dictionary transcriptorCache;\n\n private readonly IVadDetector vadDetector;\n\n private TimeSpan _lastDuration = TimeSpan.Zero;\n\n private TimeSpan _processedDuration = TimeSpan.Zero;\n\n private bool isDisposed;\n\n public RealtimeTranscriptor(\n ISpeechTranscriptorFactory speechTranscriptorFactory,\n IVadDetector vadDetector,\n ISpeechTranscriptorFactory? recognizingSpeechTranscriptorFactory,\n RealtimeSpeechTranscriptorOptions options,\n RealtimeOptions realtimeOptions,\n ILogger logger)\n {\n this.speechTranscriptorFactory = speechTranscriptorFactory;\n this.vadDetector = vadDetector;\n this.recognizingSpeechTranscriptorFactory = recognizingSpeechTranscriptorFactory;\n this.options = options;\n this.realtimeOptions = realtimeOptions;\n this.logger = logger;\n transcriptorCache = new Dictionary();\n\n logger.LogDebug(\"RealtimeTranscriptor initialized with options: {@Options}, realtime options: {@RealtimeOptions}\",\n options, realtimeOptions);\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( isDisposed )\n {\n return;\n }\n\n // lock (cacheLock)\n // {\n logger.LogInformation(\"Disposing {Count} cached transcriptors\", transcriptorCache.Count);\n foreach ( var transcriptor in transcriptorCache.Values )\n {\n await transcriptor.DisposeAsync();\n }\n\n transcriptorCache.Clear();\n // }\n\n isDisposed = true;\n GC.SuppressFinalize(this);\n }\n\n public async IAsyncEnumerable TranscribeAsync(\n IAwaitableAudioSource source,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n if ( isDisposed )\n {\n throw new ObjectDisposedException(nameof(RealtimeTranscriptor));\n }\n\n var stopwatch = Stopwatch.StartNew();\n var promptBuilder = new StringBuilder(options.Prompt);\n CultureInfo? detectedLanguage = null;\n\n await source.WaitForInitializationAsync(cancellationToken);\n var sessionId = Guid.NewGuid().ToString();\n\n logger.LogInformation(\"Starting transcription session {SessionId}\", sessionId);\n\n yield return new RealtimeSessionStarted(sessionId);\n\n try\n {\n while ( !source.IsFlushed )\n {\n var currentDuration = source.Duration;\n\n if ( currentDuration == _lastDuration )\n {\n await source.WaitForNewSamplesAsync(_lastDuration + realtimeOptions.ProcessingInterval, cancellationToken);\n\n continue;\n }\n\n logger.LogTrace(\"Processing new audio segment: Current={Current}ms, Last={Last}ms, Delta={Delta}ms\",\n currentDuration.TotalMilliseconds,\n _lastDuration.TotalMilliseconds,\n (currentDuration - _lastDuration).TotalMilliseconds);\n\n _lastDuration = currentDuration;\n var segmentStopwatch = Stopwatch.StartNew();\n var slicedSource = new SliceAudioSource(source, _processedDuration, currentDuration - _processedDuration);\n\n VadSegment? lastNonFinalSegment = null;\n VadSegment? recognizingSegment = null;\n\n await foreach ( var segment in vadDetector.DetectSegmentsAsync(slicedSource, cancellationToken) )\n {\n if ( segment.IsIncomplete )\n {\n recognizingSegment = segment;\n\n continue;\n }\n\n var segmentEnd = segment.StartTime + segment.Duration;\n lastNonFinalSegment = segment;\n\n logger.LogDebug(\"Processing VAD segment: Start={Start}ms, Duration={Duration}ms\",\n segment.StartTime.TotalMilliseconds,\n segment.Duration.TotalMilliseconds);\n\n var transcribeStopwatch = Stopwatch.StartNew();\n var transcribingEvents = TranscribeSegments(\n speechTranscriptorFactory,\n source,\n _processedDuration,\n segment.StartTime,\n segment.Duration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segmentData in transcribingEvents )\n {\n if ( options.AutodetectLanguageOnce )\n {\n detectedLanguage = segmentData.Language;\n }\n\n if ( realtimeOptions.ConcatenateSegmentsToPrompt )\n {\n promptBuilder.Append(segmentData.Text);\n }\n\n logger.LogDebug(\n \"Segment recognized: SessionId={SessionId}, Duration={Duration}ms, ProcessingTime={ProcessingTime}ms\",\n sessionId,\n segmentData.Duration.TotalMilliseconds,\n transcribeStopwatch.ElapsedMilliseconds);\n\n yield return new RealtimeSegmentRecognized(segmentData, sessionId);\n }\n }\n\n if ( options.IncludeSpeechRecogizingEvents && recognizingSegment != null )\n {\n logger.LogDebug(\"Processing recognizing segment: Duration={Duration}ms\",\n recognizingSegment.Duration.TotalMilliseconds);\n\n var transcribingEvents = TranscribeSegments(\n recognizingSpeechTranscriptorFactory ?? speechTranscriptorFactory,\n source,\n _processedDuration,\n recognizingSegment.StartTime,\n recognizingSegment.Duration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segment in transcribingEvents )\n {\n yield return new RealtimeSegmentRecognizing(segment, sessionId);\n }\n }\n\n HandleSegmentProcessing(source, ref _processedDuration, lastNonFinalSegment, recognizingSegment, _lastDuration);\n\n logger.LogTrace(\"Segment processing completed in {ElapsedTime}ms\",\n segmentStopwatch.ElapsedMilliseconds);\n }\n\n var finalStopwatch = Stopwatch.StartNew();\n var lastEvents = TranscribeSegments(\n speechTranscriptorFactory,\n source,\n _processedDuration,\n TimeSpan.Zero,\n source.Duration - _processedDuration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segmentData in lastEvents )\n {\n if ( realtimeOptions.ConcatenateSegmentsToPrompt )\n {\n promptBuilder.Append(segmentData.Text);\n }\n\n yield return new RealtimeSegmentRecognized(segmentData, sessionId);\n }\n\n logger.LogInformation(\n \"Transcription session completed: SessionId={SessionId}, TotalDuration={TotalDuration}ms, TotalProcessingTime={TotalTime}ms\",\n sessionId,\n source.Duration.TotalMilliseconds,\n stopwatch.ElapsedMilliseconds);\n\n yield return new RealtimeSessionStopped(sessionId);\n }\n finally\n {\n await CleanupSessionAsync(sessionId);\n }\n }\n\n private void HandleSegmentProcessing(\n IAudioSource source,\n ref TimeSpan processedDuration,\n VadSegment? lastNonFinalSegment,\n VadSegment? recognizingSegment,\n TimeSpan lastDuration)\n {\n if ( lastNonFinalSegment != null )\n {\n var skippingDuration = lastNonFinalSegment.StartTime + lastNonFinalSegment.Duration;\n processedDuration += skippingDuration;\n\n if ( source is IDiscardableAudioSource discardableSource )\n {\n var lastSegmentEndFrameIndex = (int)(skippingDuration.TotalMilliseconds * source.SampleRate / 1000d) - 1;\n discardableSource.DiscardFrames(lastSegmentEndFrameIndex);\n logger.LogTrace(\"Discarded frames up to index {FrameIndex}\", lastSegmentEndFrameIndex);\n }\n }\n else if ( recognizingSegment == null )\n {\n if ( lastDuration - processedDuration > realtimeOptions.SilenceDiscardInterval )\n {\n var silenceDurationToDiscard = TimeSpan.FromTicks(realtimeOptions.SilenceDiscardInterval.Ticks / 2);\n processedDuration += silenceDurationToDiscard;\n\n if ( source is IDiscardableAudioSource discardableSource )\n {\n var halfSilenceIndex = (int)(silenceDurationToDiscard.TotalMilliseconds * source.SampleRate / 1000d) - 1;\n discardableSource.DiscardFrames(halfSilenceIndex);\n logger.LogTrace(\"Discarded silence frames up to index {FrameIndex}\", halfSilenceIndex);\n }\n }\n }\n }\n\n private async IAsyncEnumerable TranscribeSegments(\n ISpeechTranscriptorFactory transcriptorFactory,\n IAudioSource source,\n TimeSpan processedDuration,\n TimeSpan startTime,\n TimeSpan duration,\n StringBuilder promptBuilder,\n CultureInfo? detectedLanguage,\n string sessionId,\n [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n if ( duration < realtimeOptions.MinTranscriptDuration )\n {\n yield break;\n }\n\n startTime += processedDuration;\n var paddedStart = startTime - realtimeOptions.PaddingDuration;\n\n if ( paddedStart < processedDuration )\n {\n paddedStart = processedDuration;\n }\n\n var paddedDuration = duration + realtimeOptions.PaddingDuration;\n\n using IAudioSource paddedSource = paddedDuration < realtimeOptions.MinDurationWithPadding\n ? GetSilenceAddedSource(source, paddedStart, paddedDuration)\n : new SliceAudioSource(source, paddedStart, paddedDuration);\n\n var languageAutodetect = options.LanguageAutoDetect;\n var language = options.Language;\n\n if ( languageAutodetect && options.AutodetectLanguageOnce && detectedLanguage != null )\n {\n languageAutodetect = false;\n language = detectedLanguage;\n }\n\n var currentOptions = options with { Prompt = realtimeOptions.ConcatenateSegmentsToPrompt ? promptBuilder.ToString() : options.Prompt, LanguageAutoDetect = languageAutodetect, Language = language };\n\n var transcriptor = GetOrCreateTranscriptor(transcriptorFactory, currentOptions, sessionId);\n\n await foreach ( var segment in transcriptor.TranscribeAsync(paddedSource, cancellationToken) )\n {\n segment.StartTime += processedDuration;\n\n yield return segment;\n }\n }\n\n private ISpeechTranscriptor GetOrCreateTranscriptor(\n ISpeechTranscriptorFactory factory,\n RealtimeSpeechTranscriptorOptions currentOptions,\n string sessionId)\n {\n var cacheKey = $\"{sessionId}_{factory.GetHashCode()}\";\n\n lock (cacheLock)\n {\n if ( !transcriptorCache.TryGetValue(cacheKey, out var transcriptor) )\n {\n transcriptor = factory.Create(currentOptions);\n transcriptorCache.Add(cacheKey, transcriptor);\n }\n\n return transcriptor;\n }\n }\n\n private async ValueTask CleanupSessionAsync(string sessionId)\n {\n // lock (cacheLock)\n // {\n var keysToRemove = transcriptorCache.Keys\n .Where(k => k.StartsWith($\"{sessionId}_\"))\n .ToList();\n\n foreach ( var key in keysToRemove )\n {\n if ( !transcriptorCache.TryGetValue(key, out var transcriptor) )\n {\n continue;\n }\n\n await transcriptor.DisposeAsync();\n transcriptorCache.Remove(key);\n }\n // }\n }\n\n private ConcatAudioSource GetSilenceAddedSource(IAudioSource source, TimeSpan paddedStart, TimeSpan paddedDuration)\n {\n var silenceDuration = new TimeSpan((realtimeOptions.MinDurationWithPadding.Ticks - paddedDuration.Ticks) / 2);\n var preSilence = new SilenceAudioSource(silenceDuration, source.SampleRate, source.Metadata, source.ChannelCount, source.BitsPerSample);\n var postSilence = new SilenceAudioSource(silenceDuration, source.SampleRate, source.Metadata, source.ChannelCount, source.BitsPerSample);\n\n return new ConcatAudioSource([preSilence, new SliceAudioSource(source, paddedStart, paddedDuration), postSilence], source.Metadata);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnx.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnx : IF0Predictor\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n private readonly float[] _inputBatchBuffer;\n\n // Preallocated buffers for zero-allocation processing\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Additional preallocated buffers for Viterbi decoding\n private readonly float[,] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[,] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[,] _transitionMatrix;\n\n private readonly float[,] _transOutBuffer;\n\n private readonly float[,] _valueBuffer;\n\n private readonly float[] _windowBuffer;\n\n public CrepeOnnx(string modelPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Preallocate buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _windowBuffer = new float[WINDOW_SIZE];\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Preallocate Viterbi algorithm buffers\n _logProbBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE, PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = CreateTransitionMatrix();\n _transOutBuffer = new float[PITCH_BINS, PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n\n // Initialize _logPInitBuffer with equal probabilities\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _logPInitBuffer[i] = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n }\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n var wavSpan = wav.Span;\n var outputSpan = f0Output.Span;\n\n if ( length > outputSpan.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Preallocate periodicity data buffer\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = new Span(pdBuffer, 0, length);\n\n // Process the audio to extract F0\n Crepe(wavSpan, outputSpan.Slice(0, length), pdSpan);\n\n // Apply post-processing\n for ( var i = 0; i < length; i++ )\n {\n if ( pdSpan[i] < 0.1 )\n {\n outputSpan[i] = 0;\n }\n }\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var total_frames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < total_frames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, total_frames - b);\n\n // Fill the batch input buffer\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame\n Normalize(frame);\n }\n\n private void Normalize(Span input)\n {\n // Mean center and scale\n float sum = 0;\n for ( var j = 0; j < input.Length; j++ )\n {\n sum += input[j];\n }\n\n var mean = sum / input.Length;\n float stdValue = 0;\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] - mean;\n stdValue += input[j] * input[j];\n }\n\n stdValue = stdValue / input.Length;\n stdValue = (float)Math.Sqrt(stdValue);\n\n if ( stdValue < 1e-10 )\n {\n stdValue = 1e-10f;\n }\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] / stdValue;\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor\n for ( var i = 0; i < batchSize; i++ )\n {\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[i * WINDOW_SIZE + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Remove frequencies outside of allowable range\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n for ( var t = 0; t < outputSize; t++ )\n {\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n if ( i < minidx || i >= maxidx )\n {\n probabilities[t * PITCH_BINS + i] = float.NegativeInfinity;\n }\n }\n }\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0, pd, outputSize, offset);\n }\n\n private void DecodeViterbi(float[] probabilities, Span f0, Span pd, int nSteps, int offset)\n {\n // Transfer probabilities to log_prob buffer and apply softmax\n for ( var i = 0; i < nSteps * PITCH_BINS; i++ )\n {\n _logProbBuffer[i / PITCH_BINS, i % PITCH_BINS] = probabilities[i];\n }\n\n Softmax(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n for ( var y = 0; y < nSteps; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _logProbBuffer[y, x] = (float)Math.Log(_logProbBuffer[y, x] + float.Epsilon);\n }\n }\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[0, i] = _logProbBuffer[0, i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm\n for ( var t = 1; t < nSteps; t++ )\n {\n // Calculate transition outputs\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _transOutBuffer[y, x] = _valueBuffer[t - 1, x] + _transitionMatrix[x, y]; // Transposed matrix\n }\n }\n\n for ( var j = 0; j < PITCH_BINS; j++ )\n {\n // Find argmax\n var maxI = 0;\n var maxProb = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb < _transOutBuffer[j, k] )\n {\n maxProb = _transOutBuffer[j, k];\n maxI = k;\n }\n }\n\n _ptrBuffer[t, j] = maxI;\n _valueBuffer[t, j] = _logProbBuffer[t, j] + _transOutBuffer[j, _ptrBuffer[t, j]];\n }\n }\n\n // Find the most likely final state\n var maxI2 = 0;\n var maxProb2 = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb2 < _valueBuffer[nSteps - 1, k] )\n {\n maxProb2 = _valueBuffer[nSteps - 1, k];\n maxI2 = k;\n }\n }\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI2;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[t + 1, _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values\n for ( var t = 0; t < nSteps; t++ )\n {\n var bins = _stateBuffer[t];\n var periodicity = Periodicity(probabilities, t, bins);\n var frequency = ConvertToFrequency(bins);\n\n if ( offset + t < f0.Length )\n {\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n }\n\n private void Softmax(float[,] data, int nSteps)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n sum += (float)Math.Exp(data[t, i]);\n }\n\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[t, i] = (float)Math.Exp(data[t, i]) / sum;\n }\n }\n }\n\n private float[,] CreateTransitionMatrix()\n {\n var transition = new float[PITCH_BINS, PITCH_BINS];\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n var v = 12 - Math.Abs(x - y);\n if ( v < 0 )\n {\n v = 0;\n }\n\n transition[y, x] = v;\n sum += v;\n }\n\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n transition[y, x] = transition[y, x] / sum;\n\n // Pre-apply log to the transition matrix for efficiency\n transition[y, x] = (float)Math.Log(transition[y, x] + float.Epsilon);\n }\n }\n\n return transition;\n }\n\n private float Periodicity(float[] probabilities, int t, int bins) { return probabilities[t * PITCH_BINS + bins]; }\n\n private float ConvertToFrequency(int bin)\n {\n float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n var frequency = 10 * (float)Math.Pow(2, cents / 1200);\n\n return frequency;\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n // Fill the window buffer\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n _medianBuffer[j] = original[k];\n }\n\n // Sort the window\n Array.Sort(_medianBuffer, 0, windowSize);\n\n // Set the median value\n data[i] = _medianBuffer[windowSize / 2];\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n float sum = 0;\n\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n sum += original[k];\n }\n\n // Set the mean value\n data[i] = sum / windowSize;\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadDetector.cs", "using System.Buffers;\nusing System.Runtime.CompilerServices;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroVadDetector : IVadDetector\n{\n private readonly int _minSilenceSamples;\n\n private readonly int _minSpeechSamples;\n\n private readonly SileroVadOnnxModel _model;\n\n private readonly float _negThreshold;\n\n private readonly float _threshold;\n\n public SileroVadDetector(VadDetectorOptions vadDetectorOptions, SileroVadOptions sileroVadOptions)\n {\n _model = new SileroVadOnnxModel(sileroVadOptions.ModelPath);\n _threshold = sileroVadOptions.Threshold;\n _negThreshold = _threshold - sileroVadOptions.ThresholdGap;\n _minSpeechSamples = (int)(16d * vadDetectorOptions.MinSpeechDuration.TotalMilliseconds);\n _minSilenceSamples = (int)(16d * vadDetectorOptions.MinSilenceDuration.TotalMilliseconds);\n }\n\n public async IAsyncEnumerable DetectSegmentsAsync(IAudioSource source, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n ValidateSource(source);\n\n foreach ( var segment in DetectSegments(await source.GetSamplesAsync(0, cancellationToken: cancellationToken)) )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n yield return segment;\n }\n }\n\n private IEnumerable DetectSegments(Memory samples)\n {\n var state = _model.CreateInferenceState();\n int? startingIndex = null;\n int? startingSilenceIndex = null;\n\n for ( var i = 0; i < samples.Length - SileroConstants.BatchSize; i += SileroConstants.BatchSize )\n {\n Memory slice;\n float[]? rentedMemory = null;\n try\n {\n if ( i == 0 )\n {\n // the first batch will have the empty context (which we need to copy at the beggining of the slice)\n rentedMemory = ArrayPool.Shared.Rent(SileroConstants.ContextSize + SileroConstants.BatchSize);\n Array.Clear(rentedMemory, 0, SileroConstants.ContextSize);\n samples.Span.Slice(0, SileroConstants.BatchSize).CopyTo(rentedMemory.AsSpan(SileroConstants.ContextSize));\n slice = rentedMemory.AsMemory(0, SileroConstants.BatchSize + SileroConstants.ContextSize);\n }\n else\n {\n slice = samples.Slice(i - SileroConstants.ContextSize, SileroConstants.BatchSize + SileroConstants.ContextSize);\n }\n\n var prob = _model.Call(slice, state);\n if ( !startingIndex.HasValue )\n {\n if ( prob > _threshold )\n {\n startingIndex = i;\n }\n\n continue;\n }\n\n // We are in speech\n if ( prob > _threshold )\n {\n startingSilenceIndex = null;\n\n continue;\n }\n\n if ( prob > _negThreshold )\n {\n // We are still in speech and the current batch is between the threshold and the negative threshold\n // We continue to the next batch\n continue;\n }\n\n if ( startingSilenceIndex == null )\n {\n startingSilenceIndex = i;\n\n continue;\n }\n\n var silenceLength = i - startingSilenceIndex.Value;\n\n if ( silenceLength > _minSilenceSamples )\n {\n // We have silence after speech exceeding the minimum silence duration\n var length = i - startingIndex.Value;\n if ( length >= _minSpeechSamples )\n {\n yield return new VadSegment { StartTime = TimeSpan.FromMilliseconds(startingIndex.Value * 1000d / SileroConstants.SampleRate), Duration = TimeSpan.FromMilliseconds(length * 1000d / SileroConstants.SampleRate) };\n }\n\n startingIndex = null;\n startingSilenceIndex = null;\n }\n }\n finally\n {\n if ( rentedMemory != null )\n {\n ArrayPool.Shared.Return(rentedMemory, ArrayPoolConfig.ClearOnReturn);\n }\n }\n }\n\n // The last segment if it was already started (might be incomplete for sources that are not yet finished)\n if ( startingIndex.HasValue )\n {\n var length = samples.Length - startingIndex.Value;\n if ( length >= _minSpeechSamples )\n {\n yield return new VadSegment { StartTime = TimeSpan.FromMilliseconds(startingIndex.Value * 1000d / SileroConstants.SampleRate), Duration = TimeSpan.FromMilliseconds(length * 1000d / SileroConstants.SampleRate), IsIncomplete = true };\n }\n }\n }\n\n private static void ValidateSource(IAudioSource source)\n {\n if ( source.ChannelCount != 1 )\n {\n throw new NotSupportedException(\"Only mono-channel audio is supported. Consider one channel aggregation on the audio source.\");\n }\n\n if ( source.SampleRate != 16000 )\n {\n throw new NotSupportedException(\"Only 16 kHz audio is supported. Consider resampling before calling this transcriptor.\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnxSimd.cs", "using System.Buffers;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\nusing System.Runtime.Intrinsics.X86;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnxSimd : IF0Predictor, IDisposable\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n // Preallocated buffers\n private readonly float[] _inputBatchBuffer;\n\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Flattened arrays for better cache locality and SIMD operations\n private readonly float[] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[] _tempBuffer; // Used for temporary calculations\n\n private readonly float[] _transitionMatrix;\n\n private readonly float[] _transOutBuffer;\n\n private readonly float[] _valueBuffer;\n\n // SIMD vector size based on hardware\n private readonly int _vectorSize;\n\n public CrepeOnnxSimd(string modelPath)\n {\n // Determine vector size based on hardware capabilities\n _vectorSize = Vector.Count;\n\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n // Use hardware specific optimizations if available\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Initialize preallocated buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Initialize flattened buffers for Viterbi algorithm\n _logProbBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE * PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = new float[PITCH_BINS * PITCH_BINS];\n _transOutBuffer = new float[PITCH_BINS * PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n _tempBuffer = new float[Math.Max(BATCH_SIZE, PITCH_BINS) * _vectorSize];\n\n // Initialize logPInitBuffer with equal probabilities\n var logInitProb = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n FillArray(_logPInitBuffer, logInitProb);\n\n // Initialize transition matrix\n InitializeTransitionMatrix(_transitionMatrix);\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n if ( length > f0Output.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Rent buffer from pool for periodicity data\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = pdBuffer.AsSpan(0, length);\n var wavSpan = wav.Span;\n var f0Span = f0Output.Span.Slice(0, length);\n\n // Process audio to extract F0\n Crepe(wavSpan, f0Span, pdSpan);\n\n // Apply post-processing with SIMD\n ApplyPeriodicityThreshold(f0Span, pdSpan, length);\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var totalFrames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < totalFrames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, totalFrames - b);\n\n // Fill the batch input buffer with SIMD\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing with SIMD\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection padding\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection padding\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame using SIMD\n NormalizeAvx(frame);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeSimd(Span input)\n {\n // 1. Calculate mean using SIMD\n float sum = 0;\n var vectorCount = input.Length / _vectorSize;\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var v = new Vector(input.Slice(i * _vectorSize, _vectorSize));\n sum += Vector.Sum(v);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n sum += input[i];\n }\n\n var mean = sum / input.Length;\n\n // 2. Subtract mean and calculate variance using SIMD\n float variance = 0;\n var meanVector = new Vector(mean);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var centered = v - meanVector;\n centered.CopyTo(slice);\n variance += Vector.Sum(centered * centered);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] -= mean;\n variance += input[i] * input[i];\n }\n\n // 3. Calculate stddev and normalize\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVector = new Vector(stddev);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var normalized = v / stddevVector;\n normalized.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] /= stddev;\n }\n }\n\n // Hardware-specific optimization for AVX2-capable systems\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeAvx(Span input)\n {\n if ( !Avx.IsSupported || input.Length < 8 )\n {\n NormalizeSimd(input);\n\n return;\n }\n\n unsafe\n {\n fixed (float* pInput = input)\n {\n // Calculate sum using AVX\n var sumVec = Vector256.Zero;\n var avxVectorCount = input.Length / 8;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n sumVec = Avx.Add(sumVec, v);\n }\n\n // Horizontal sum\n var sumArray = stackalloc float[8];\n Avx.Store(sumArray, sumVec);\n\n float sum = 0;\n for ( var i = 0; i < 8; i++ )\n {\n sum += sumArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n sum += pInput[i];\n }\n\n var mean = sum / input.Length;\n var meanVec = Vector256.Create(mean);\n\n // Subtract mean and compute variance\n var varianceVec = Vector256.Zero;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var centered = Avx.Subtract(v, meanVec);\n Avx.Store(pInput + i * 8, centered);\n varianceVec = Avx.Add(varianceVec, Avx.Multiply(centered, centered));\n }\n\n // Get variance\n var varArray = stackalloc float[8];\n Avx.Store(varArray, varianceVec);\n\n float variance = 0;\n for ( var i = 0; i < 8; i++ )\n {\n variance += varArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] -= mean;\n variance += pInput[i] * pInput[i];\n }\n\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVec = Vector256.Create(stddev);\n\n // Normalize\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var normalized = Avx.Divide(v, stddevVec);\n Avx.Store(pInput + i * 8, normalized);\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] /= stddev;\n }\n }\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor using SIMD where possible\n for ( var i = 0; i < batchSize; i++ )\n {\n var inputOffset = i * WINDOW_SIZE;\n var vectorCount = WINDOW_SIZE / _vectorSize;\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var vectorOffset = v * _vectorSize;\n var source = new Vector(_inputBatchBuffer.AsSpan(inputOffset + vectorOffset, _vectorSize));\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n _inputTensor[i, vectorOffset + j] = source[j];\n }\n }\n\n // Handle remainder\n for ( var j = vectorCount * _vectorSize; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[inputOffset + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Apply frequency range limitation using SIMD where possible\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n ApplyFrequencyRangeLimit(probabilities, outputSize, minidx, maxidx);\n\n // Make a safe copy of the spans since we can't capture them in parallel operations\n var f0Array = new float[f0.Length];\n var pdArray = new float[pd.Length];\n f0.CopyTo(f0Array);\n pd.CopyTo(pdArray);\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0Array, pdArray, outputSize, offset);\n\n // Copy results back\n for ( var i = 0; i < outputSize; i++ )\n {\n if ( offset + i < f0.Length )\n {\n f0[offset + i] = f0Array[offset + i];\n pd[offset + i] = pdArray[offset + i];\n }\n }\n }\n\n private void ApplyFrequencyRangeLimit(float[] probabilities, int outputSize, int minIdx, int maxIdx)\n {\n // Set values outside the frequency range to negative infinity\n Parallel.For(0, outputSize, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Handle first part (below minIdx)\n for ( var i = 0; i < minIdx; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n\n // Handle second part (above maxIdx)\n for ( var i = maxIdx; i < PITCH_BINS; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n });\n }\n\n private void DecodeViterbi(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n // Transfer probabilities to logProbBuffer and apply softmax\n Buffer.BlockCopy(probabilities, 0, _logProbBuffer, 0, nSteps * PITCH_BINS * sizeof(float));\n\n // Apply softmax with SIMD\n SoftmaxSimd(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n ApplyLogToProbs(_logProbBuffer, nSteps);\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[i] = _logProbBuffer[i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm (forward pass)\n for ( var t = 1; t < nSteps; t++ )\n {\n ViterbiForward(t, nSteps);\n }\n\n // Find the most likely final state\n var maxI = FindArgMax(_valueBuffer, (nSteps - 1) * PITCH_BINS, PITCH_BINS);\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[(t + 1) * PITCH_BINS + _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values and apply periodicity\n ConvertToF0(probabilities, f0, pd, nSteps, offset);\n }\n\n private void SoftmaxSimd(float[] data, int nSteps)\n {\n Parallel.For(0, nSteps, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Find max for numerical stability\n var max = float.NegativeInfinity;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n max = Math.Max(max, data[baseIdx + i]);\n }\n\n // Compute exp(x - max) and sum\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[baseIdx + i] = MathF.Exp(data[baseIdx + i] - max);\n sum += data[baseIdx + i];\n }\n\n // Normalize\n var invSum = 1.0f / sum;\n var vecCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var idx = baseIdx + v * _vectorSize;\n var values = new Vector(data.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n data[idx + j] = normalized[j];\n }\n }\n\n // Handle remainder\n for ( var i = baseIdx + vecCount * _vectorSize; i < baseIdx + PITCH_BINS; i++ )\n {\n data[i] *= invSum;\n }\n });\n }\n\n private void ApplyLogToProbs(float[] data, int nSteps)\n {\n var totalSize = nSteps * PITCH_BINS;\n var vecCount = totalSize / _vectorSize;\n var dataSpan = data.AsSpan(0, totalSize);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var slice = dataSpan.Slice(v * _vectorSize, _vectorSize);\n var values = new Vector(slice);\n var logValues = Vector.Log(values + new Vector(float.Epsilon));\n logValues.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vecCount * _vectorSize; i < totalSize; i++ )\n {\n data[i] = MathF.Log(data[i] + float.Epsilon);\n }\n }\n\n private void ViterbiForward(int t, int nSteps)\n {\n var baseIdxCurrent = t * PITCH_BINS;\n var baseIdxPrev = (t - 1) * PITCH_BINS;\n\n // Fixed number of threads to avoid thread contention\n var threadCount = Math.Min(Environment.ProcessorCount, PITCH_BINS);\n\n Parallel.For(0, threadCount, threadIdx =>\n {\n // Each thread processes a chunk of states\n var statesPerThread = (PITCH_BINS + threadCount - 1) / threadCount;\n var startState = threadIdx * statesPerThread;\n var endState = Math.Min(startState + statesPerThread, PITCH_BINS);\n\n for ( var j = startState; j < endState; j++ )\n {\n var maxI = 0;\n var maxVal = float.NegativeInfinity;\n\n // Find max transition - this could be further vectorized for specific hardware\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n var transVal = _valueBuffer[baseIdxPrev + k] + _transitionMatrix[j * PITCH_BINS + k];\n if ( transVal > maxVal )\n {\n maxVal = transVal;\n maxI = k;\n }\n }\n\n _ptrBuffer[baseIdxCurrent + j] = maxI;\n _valueBuffer[baseIdxCurrent + j] = _logProbBuffer[baseIdxCurrent + j] + maxVal;\n }\n });\n }\n\n private int FindArgMax(float[] data, int offset, int length)\n {\n var maxIdx = 0;\n var maxVal = float.NegativeInfinity;\n\n for ( var i = 0; i < length; i++ )\n {\n if ( data[offset + i] > maxVal )\n {\n maxVal = data[offset + i];\n maxIdx = i;\n }\n }\n\n return maxIdx;\n }\n\n private void ConvertToF0(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n if ( offset + t >= f0.Length )\n {\n break;\n }\n\n var bin = _stateBuffer[t];\n var periodicity = probabilities[t * PITCH_BINS + bin];\n var frequency = ConvertBinToFrequency(bin);\n\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n\n private void ApplyPeriodicityThreshold(Span f0, Span pd, int length)\n {\n const float threshold = 0.1f;\n var vecCount = length / _vectorSize;\n\n // Use SIMD for bulk processing\n for ( var v = 0; v < vecCount; v++ )\n {\n var offset = v * _vectorSize;\n var pdSlice = pd.Slice(offset, _vectorSize);\n var f0Slice = f0.Slice(offset, _vectorSize);\n\n var pdVec = new Vector(pdSlice);\n var thresholdVec = new Vector(threshold);\n var zeroVec = new Vector(0.0f);\n var f0Vec = new Vector(f0Slice);\n\n // Where pd < threshold, set f0 to 0\n var mask = Vector.LessThan(pdVec, thresholdVec);\n var result = Vector.ConditionalSelect(mask, zeroVec, f0Vec);\n\n result.CopyTo(f0Slice);\n }\n\n // Handle remainder with scalar code\n for ( var i = vecCount * _vectorSize; i < length; i++ )\n {\n if ( pd[i] < threshold )\n {\n f0[i] = 0;\n }\n }\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use thread-local window buffers for parallel processing\n Parallel.For(0, length, i =>\n {\n // Allocate a local median buffer for each thread\n var localMedianBuffer = new float[windowSize];\n\n // Get window values\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - radius;\n k = Math.Clamp(k, 0, length - 1);\n localMedianBuffer[j] = original[k];\n }\n\n // Simple sort for small window\n Array.Sort(localMedianBuffer, 0, windowSize);\n result[i] = localMedianBuffer[radius];\n });\n\n // Copy results back to the span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n // Copy to array for processing\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use arrays instead of spans for parallel processing\n Parallel.For(0, length, i =>\n {\n float sum = 0;\n for ( var j = -radius; j <= radius; j++ )\n {\n var k = Math.Clamp(i + j, 0, length - 1);\n sum += original[k];\n }\n\n result[i] = sum / windowSize;\n });\n\n // Copy back to span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void InitializeTransitionMatrix(float[] transitionMatrix)\n {\n Parallel.For(0, PITCH_BINS, y =>\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n float v = 12 - Math.Abs(x - y);\n v = Math.Max(v, 0);\n transitionMatrix[y * PITCH_BINS + x] = v;\n sum += v;\n }\n\n // Normalize and pre-apply log\n var invSum = 1.0f / sum;\n var vectorCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n var epsilonVec = new Vector(float.Epsilon);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var idx = y * PITCH_BINS + v * _vectorSize;\n var values = new Vector(transitionMatrix.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n var logValues = Vector.Log(normalized + epsilonVec);\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n transitionMatrix[idx + j] = logValues[j];\n }\n }\n\n // Handle remainder\n for ( var x = vectorCount * _vectorSize; x < PITCH_BINS; x++ )\n {\n var idx = y * PITCH_BINS + x;\n transitionMatrix[idx] = transitionMatrix[idx] * invSum;\n transitionMatrix[idx] = MathF.Log(transitionMatrix[idx] + float.Epsilon);\n }\n });\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private float ConvertBinToFrequency(int bin)\n {\n const float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n\n return 10 * MathF.Pow(2, cents / 1200);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void FillArray(Span array, float value)\n {\n var vectorCount = array.Length / _vectorSize;\n var valueVec = new Vector(value);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n valueVec.CopyTo(array.Slice(v * _vectorSize, _vectorSize));\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < array.Length; i++ )\n {\n array[i] = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioConverter.cs", "using System.Buffers.Binary;\nusing System.Runtime.CompilerServices;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Provides functionality for converting audio between different formats.\n/// \npublic static class AudioConverter\n{\n /// \n /// Calculates the required size for a buffer to hold the converted audio.\n /// \n /// The source audio buffer.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The size in bytes needed for the target buffer.\n public static int CalculateTargetBufferSize(\n ReadOnlyMemory sourceBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var framesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // If resampling is needed, adjust the frame count\n if ( sourceFormat.SampleRate != targetFormat.SampleRate )\n {\n framesCount = CalculateResampledFrameCount(framesCount, sourceFormat.SampleRate, targetFormat.SampleRate);\n }\n\n // Calculate the expected size of the target buffer\n return framesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Calculates the number of frames after resampling.\n /// \n /// Number of frames in the source buffer.\n /// Sample rate of the source audio.\n /// Target sample rate.\n /// The number of frames after resampling.\n public static int CalculateResampledFrameCount(\n int sourceFrameCount,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n return (int)Math.Ceiling(sourceFrameCount * ((double)targetSampleRate / sourceSampleRate));\n }\n\n /// \n /// Converts audio data between different formats.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the converted data to.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The number of bytes written to the target buffer.\n /// Thrown if the target buffer is too small.\n public static int Convert(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var sourceFramesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // Check if resampling is needed\n var needsResampling = sourceFormat.SampleRate != targetFormat.SampleRate;\n\n // Calculate the expected number of frames in the target buffer\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceFormat.SampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate the expected size of the target buffer\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Fast path for same format conversion with no resampling\n if ( !needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n sourceBuffer.CopyTo(targetBuffer);\n\n return sourceBuffer.Length;\n }\n\n // If only resampling is needed (same format otherwise)\n if ( needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n return ResampleDirect(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // For mono-to-stereo int16 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 32 && targetFormat.BitsPerSample == 16 )\n {\n ConvertMonoFloat32ToStereoInt16Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For stereo-to-mono conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 2 && targetFormat.Channels == 1 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertStereoInt16ToMonoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For mono-int16 to stereo-float32 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertMonoInt16ToStereoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // General case: convert through intermediate float format\n return ConvertGeneral(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount,\n needsResampling);\n }\n\n /// \n /// Specialized fast path to convert 48kHz stereo float32 audio to 16kHz mono int16 audio.\n /// This optimized method combines resampling, channel conversion, and bit depth conversion in one pass.\n /// \n /// The 48kHz stereo float32 audio buffer.\n /// The target buffer to receive the 16kHz mono int16 data.\n /// The number of bytes written to the target buffer.\n public static int ConvertStereoFloat32_48kTo_MonoInt16_16k(\n ReadOnlyMemory stereoFloat32Buffer,\n Memory targetBuffer)\n {\n var sourceFormat = new AudioFormat(2, 32, 48000);\n var targetFormat = new AudioFormat(1, 16, 16000);\n\n // Calculate number of source and target frames\n var sourceFramesCount = stereoFloat32Buffer.Length / sourceFormat.BytesPerFrame;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, 48000, 16000);\n\n // Calculate expected target size and verify buffer is large enough\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Process the conversion directly\n ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n stereoFloat32Buffer.Span,\n targetBuffer.Span,\n sourceFramesCount,\n targetFramesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Direct conversion implementation for 48kHz stereo float32 to 16kHz mono int16.\n /// Combines downsampling (48kHz to 16kHz - 3:1 ratio), stereo to mono mixing, and float32 to int16 conversion.\n /// \n private static void ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n ReadOnlySpan source,\n Span target,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // The resampling ratio is exactly 3:1 (48000/16000)\n const int resampleRatio = 3;\n\n // For optimal quality, we'll use a simple low-pass filter when downsampling\n // by averaging 3 consecutive frames before picking every 3rd one\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source frame index (center of 3-frame window)\n var sourceFrameBase = targetFrame * resampleRatio;\n\n // Initialize accumulator for filtered sample\n var monoSampleAccumulator = 0f;\n var sampleCount = 0;\n\n // Apply a simple averaging filter over a window of frames\n for ( var offset = -1; offset <= 1; offset++ )\n {\n var sourceFrameIndex = sourceFrameBase + offset;\n\n // Skip samples outside buffer boundary\n if ( sourceFrameIndex < 0 || sourceFrameIndex >= sourceFramesCount )\n {\n continue;\n }\n\n // Read left and right float32 samples and average them to mono\n var sourceByteIndex = sourceFrameIndex * 8; // 8 bytes per stereo float32 frame\n var leftSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex, 4));\n var rightSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex + 4, 4));\n\n // Average stereo to mono\n var monoSample = (leftSample + rightSample) * 0.5f;\n\n // Accumulate filtered sample\n monoSampleAccumulator += monoSample;\n sampleCount++;\n }\n\n // Average samples if we have any\n var filteredSample = sampleCount > 0 ? monoSampleAccumulator / sampleCount : 0f;\n\n // Convert float32 to int16 (with scaling and clamping)\n var int16Sample = ClampToInt16(filteredSample * 32767f);\n\n // Write to target buffer\n var targetByteIndex = targetFrame * 2; // 2 bytes per mono int16 frame\n BinaryPrimitives.WriteInt16LittleEndian(target.Slice(targetByteIndex, 2), int16Sample);\n }\n }\n\n /// \n /// Resamples audio using a higher quality filter.\n /// Uses a sinc filter for better frequency response.\n /// \n private static void ResampleWithFilter(float[] source, float[] target, uint sourceRate, uint targetRate)\n {\n // For 48kHz to 16kHz, we have a 3:1 ratio\n var ratio = (double)sourceRate / targetRate;\n\n // Use a simple windowed-sinc filter with 8 taps for anti-aliasing\n var filterSize = 8;\n\n for ( var targetIndex = 0; targetIndex < target.Length; targetIndex++ )\n {\n // Calculate the corresponding position in the source\n var sourcePos = targetIndex * ratio;\n var sourceCenterIndex = (int)sourcePos;\n\n // Apply the filter\n var sum = 0f;\n var totalWeight = 0f;\n\n for ( var tap = -filterSize / 2; tap < filterSize / 2; tap++ )\n {\n var sourceIndex = sourceCenterIndex + tap;\n\n // Skip samples outside buffer boundary\n if ( sourceIndex < 0 || sourceIndex >= source.Length )\n {\n continue;\n }\n\n // Calculate the sinc weight\n var x = sourcePos - sourceIndex;\n var weight = x == 0 ? 1.0f : (float)(Math.Sin(Math.PI * x) / (Math.PI * x));\n\n // Apply a Hann window to reduce ringing\n weight *= 0.5f * (1 + (float)Math.Cos(2 * Math.PI * (tap + filterSize / 2) / filterSize));\n\n sum += source[sourceIndex] * weight;\n totalWeight += weight;\n }\n\n // Normalize the output\n target[targetIndex] = totalWeight > 0 ? sum / totalWeight : 0f;\n }\n }\n\n /// \n /// Resamples audio data to a different sample rate.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the resampled data to.\n /// The format of the source audio.\n /// The target sample rate.\n /// The number of bytes written to the target buffer.\n public static int Resample(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n uint targetSampleRate)\n {\n // Create target format with the new sample rate but same other parameters\n var targetFormat = new AudioFormat(\n sourceFormat.Channels,\n sourceFormat.BitsPerSample,\n targetSampleRate);\n\n return Convert(sourceBuffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Resamples floating-point audio samples directly.\n /// \n /// The source float samples.\n /// The target buffer to write the resampled samples to.\n /// Number of channels in the audio.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ResampleFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort channels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n // Fast path for same sample rate\n if ( sourceSampleRate == targetSampleRate )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceSamples.Length / channels;\n }\n\n var sourceFramesCount = sourceSamples.Length / channels;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate);\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * channels )\n {\n throw new ArgumentException(\"Target buffer is too small for the resampled audio.\");\n }\n\n // Perform the resampling\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n channels,\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Converts float samples to a different format (channels, sample rate) and outputs as byte array.\n /// \n /// The source float samples.\n /// The target buffer to write the converted data to.\n /// Number of channels in the source.\n /// Source sample rate.\n /// The desired output format.\n /// The number of bytes written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetBuffer,\n ushort sourceChannels,\n uint sourceSampleRate,\n AudioFormat targetFormat)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetFormat.SampleRate;\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate expected target buffer size\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Handle resampling if needed\n ReadOnlyMemory resampledSamples;\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceChannels];\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n }\n else\n {\n resampledSamples = sourceSamples;\n }\n\n // Handle channel conversion if needed\n ReadOnlyMemory convertedSamples;\n if ( sourceChannels != targetFormat.Channels )\n {\n var convertedBuffer = new float[targetFramesCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceChannels,\n targetFormat.Channels,\n targetFramesCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return expectedTargetSize;\n }\n\n /// \n /// Converts audio format with direct access to float samples.\n /// \n /// The source float samples.\n /// The target buffer to write the converted samples to.\n /// Number of channels in the source.\n /// Number of channels for the output.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort sourceChannels,\n ushort targetChannels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetSampleRate;\n var needsChannelConversion = sourceChannels != targetChannels;\n\n // If no conversion needed, just copy\n if ( !needsResampling && !needsChannelConversion )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceFramesCount;\n }\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate)\n : sourceFramesCount;\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * targetChannels )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Optimize the common path where only channel conversion or only resampling is needed\n if ( needsResampling && !needsChannelConversion )\n {\n // Only resample\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels, // same as targetChannels in this case\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n if ( !needsResampling && needsChannelConversion )\n {\n // Only convert channels\n ConvertChannels(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n sourceFramesCount);\n\n return sourceFramesCount;\n }\n\n // If we need both resampling and channel conversion\n // First resample, then convert channels\n var resampledBuffer = needsResampling ? new float[targetFramesCount * sourceChannels] : null;\n\n if ( needsResampling )\n {\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // Then convert channels\n ConvertChannels(\n needsResampling ? resampledBuffer.AsSpan() : sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Direct resampling of audio data without format conversion.\n /// \n private static int ResampleDirect(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Convert to float for processing\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Resample the float samples\n var resampledBuffer = new float[targetFramesCount * targetFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n // Serialize back to the target format\n SampleSerializer.Serialize(resampledBuffer, targetBuffer, targetFormat.BitsPerSample);\n\n return targetFramesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Resamples floating-point audio samples.\n /// \n private static void ResampleFloatBuffer(\n ReadOnlySpan sourceBuffer,\n Span targetBuffer,\n ushort channels,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Calculate the step size for linear interpolation\n var step = (double)(sourceFramesCount - 1) / (targetFramesCount - 1);\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source position (as a floating point value)\n var sourcePos = targetFrame * step;\n\n // Get indices of the two source frames to interpolate between\n var sourceFrameLow = (int)sourcePos;\n var sourceFrameHigh = Math.Min(sourceFrameLow + 1, sourceFramesCount - 1);\n\n // Calculate interpolation factor\n var fraction = (float)(sourcePos - sourceFrameLow);\n\n // Interpolate each channel\n for ( var channel = 0; channel < channels; channel++ )\n {\n var sourceLowIndex = sourceFrameLow * channels + channel;\n var sourceHighIndex = sourceFrameHigh * channels + channel;\n var targetIndex = targetFrame * channels + channel;\n\n // Linear interpolation\n targetBuffer[targetIndex] = Lerp(\n sourceBuffer[sourceLowIndex],\n sourceBuffer[sourceHighIndex],\n fraction);\n }\n }\n }\n\n /// \n /// Linear interpolation between two values.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static float Lerp(float a, float b, float t) { return a + (b - a) * t; }\n\n /// \n /// Converts mono float32 audio to stereo int16 PCM format.\n /// \n /// The mono float32 audio buffer.\n /// The target buffer to receive the stereo int16 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoFloat32ToStereoInt16(\n ReadOnlyMemory monoFloat32Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(32, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(16, sampleRate);\n\n return Convert(monoFloat32Buffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Converts mono int16 audio to stereo float32 PCM format.\n /// \n /// The mono int16 audio buffer.\n /// The target buffer to receive the stereo float32 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoInt16ToStereoFloat32(\n ReadOnlyMemory monoInt16Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(16, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(32, sampleRate);\n\n // Use fast path for this specific conversion\n var framesCount = monoInt16Buffer.Length / sourceFormat.BytesPerFrame;\n var expectedTargetSize = framesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n ConvertMonoInt16ToStereoFloat32Direct(monoInt16Buffer, targetBuffer, framesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Optimized direct conversion from mono float32 to stereo int16.\n /// \n private static void ConvertMonoFloat32ToStereoInt16Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 4 bytes per float32\n var targetIndex = frame * 4; // 2 bytes per int16 * 2 channels\n\n // Read float32 value\n var floatValue = BinaryPrimitives.ReadSingleLittleEndian(sourceSpan.Slice(sourceIndex, 4));\n\n // Convert to int16 (with clamping)\n var int16Value = ClampToInt16(floatValue * 32767f);\n\n // Write the same value to both left and right channels\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex, 2), int16Value);\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex + 2, 2), int16Value);\n }\n }\n\n /// \n /// Optimized direct conversion from stereo int16 to mono float32.\n /// \n private static void ConvertStereoInt16ToMonoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 2 bytes per int16 * 2 channels\n var targetIndex = frame * 4; // 4 bytes per float32\n\n // Read int16 values for left and right channels\n var leftValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n var rightValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex + 2, 2));\n\n // Convert to float32 and average the channels\n var floatValue = (leftValue + rightValue) * 0.5f / 32768f;\n\n // Write to target buffer\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n }\n }\n\n /// \n /// Optimized direct conversion from mono int16 to stereo float32.\n /// \n private static void ConvertMonoInt16ToStereoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2; // 2 bytes per int16\n var targetIndex = frame * 8; // 4 bytes per float32 * 2 channels\n\n // Read int16 value\n var int16Value = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n\n // Convert to float32\n var floatValue = int16Value / 32768f;\n\n // Write the same float value to both left and right channels\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex + 4, 4), floatValue);\n }\n }\n\n /// \n /// General case conversion using intermediate float format.\n /// \n private static int ConvertGeneral(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount,\n bool needsResampling)\n {\n // Deserialize to float samples - this will give us interleaved float samples\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Perform resampling if needed\n Memory resampledSamples;\n int actualFrameCount;\n\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n actualFrameCount = targetFramesCount;\n }\n else\n {\n resampledSamples = floatSamples;\n actualFrameCount = sourceFramesCount;\n }\n\n // Convert channel configuration if needed\n Memory convertedSamples;\n\n if ( sourceFormat.Channels != targetFormat.Channels )\n {\n var convertedBuffer = new float[actualFrameCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceFormat.Channels,\n targetFormat.Channels,\n actualFrameCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n // No channel conversion needed\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return actualFrameCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Converts between different channel configurations.\n /// \n private static void ConvertChannels(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n // If source and target have the same number of channels, just copy\n if ( sourceChannels == targetChannels )\n {\n source.CopyTo(target);\n\n return;\n }\n\n // Handle specific conversions with optimized implementations\n if ( sourceChannels == 1 && targetChannels == 2 )\n {\n // Mono to stereo conversion\n ConvertMonoToStereo(source, target, framesCount);\n }\n else if ( sourceChannels == 2 && targetChannels == 1 )\n {\n // Stereo to mono conversion\n ConvertStereoToMono(source, target, framesCount);\n }\n else\n {\n // More general conversion implementation\n ConvertChannelsGeneral(source, target, sourceChannels, targetChannels, framesCount);\n }\n }\n\n /// \n /// Converts mono audio to stereo by duplicating each sample.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertMonoToStereo(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceSample = source[frame];\n var targetIndex = frame * 2;\n\n target[targetIndex] = sourceSample; // Left channel\n target[targetIndex + 1] = sourceSample; // Right channel\n }\n }\n\n /// \n /// Converts stereo audio to mono by averaging the channels.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertStereoToMono(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2;\n var leftSample = source[sourceIndex];\n var rightSample = source[sourceIndex + 1];\n\n target[frame] = (leftSample + rightSample) * 0.5f; // Average the channels\n }\n }\n\n /// \n /// General method for converting between different channel configurations.\n /// \n private static void ConvertChannelsGeneral(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n ConvertChannelsChunk(source, target, sourceChannels, targetChannels, 0, framesCount);\n }\n\n /// \n /// Converts a chunk of frames between different channel configurations.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertChannelsChunk(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int startFrame,\n int endFrame)\n {\n for ( var frame = startFrame; frame < endFrame; frame++ )\n {\n var sourceFrameOffset = frame * sourceChannels;\n var targetFrameOffset = frame * targetChannels;\n\n // Find the minimum of source and target channels\n var minChannels = Math.Min(sourceChannels, targetChannels);\n\n // Copy the available channels\n for ( var channel = 0; channel < minChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + channel];\n }\n\n // If target has more channels than source, duplicate the last channel\n for ( var channel = minChannels; channel < targetChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + (minChannels - 1)];\n }\n }\n }\n\n /// \n /// Clamps a float value to the range of a 16-bit integer.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static short ClampToInt16(float value)\n {\n if ( value > 32767f )\n {\n return 32767;\n }\n\n if ( value < -32768f )\n {\n return -32768;\n }\n\n return (short)value;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MicrophoneInputNAudioSource.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing NAudio.Wave;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents a source that captures audio from a microphone,\n/// configured dynamically via IOptionsMonitor.\n/// \npublic sealed class MicrophoneInputNAudioSource : AwaitableWaveFileSource, IMicrophone\n{\n private readonly Lock _lock = new();\n\n private readonly ILogger _logger;\n\n private readonly IDisposable? _optionsChangeListener;\n\n private MicrophoneConfiguration _currentOptions;\n\n private bool _isDisposed = false;\n\n private CancellationTokenSource? _recordingCts;\n\n private bool _wasRecordingBeforeReconfigure = false;\n\n private WaveInEvent? _waveIn;\n\n public MicrophoneInputNAudioSource(\n ILogger logger,\n IOptionsMonitor optionsMonitor,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : base(new Dictionary(),\n true,\n false,\n DefaultInitialSize,\n DefaultInitialSize,\n aggregationStrategy)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _currentOptions = optionsMonitor.CurrentValue;\n\n _logger.LogInformation(\"Initializing MicrophoneInputNAudioSource with options: {@Options}\", _currentOptions);\n\n InitializeMicrophone(_currentOptions);\n\n _optionsChangeListener = optionsMonitor.OnChange(HandleOptionsChange);\n }\n\n public void StartRecording()\n {\n lock (_lock)\n {\n ObjectDisposedException.ThrowIf(_isDisposed, typeof(MicrophoneInputNAudioSource));\n\n if ( _recordingCts is { IsCancellationRequested: false } )\n {\n _logger.LogWarning(\"StartRecording called, but recording is already active.\");\n\n return;\n }\n\n StartRecordingInternal();\n }\n }\n\n public void StopRecording()\n {\n lock (_lock)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n if ( _recordingCts == null || _recordingCts.IsCancellationRequested )\n {\n return;\n }\n\n StopInternal();\n }\n }\n\n public IEnumerable GetAvailableDevices() { return GetAvailableDevicesInternal(_logger); }\n\n public new void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private static IEnumerable GetAvailableDevicesInternal(ILogger? logger = null)\n {\n var deviceNames = new List();\n try\n {\n var deviceCount = WaveInEvent.DeviceCount;\n logger?.LogDebug(\"Enumerating {DeviceCount} audio input devices.\", deviceCount);\n for ( var n = 0; n < deviceCount; n++ )\n {\n try\n {\n var caps = WaveInEvent.GetCapabilities(n);\n deviceNames.Add(caps.ProductName ?? $\"Unnamed Device {n}\");\n logger?.LogTrace(\"Found Device {DeviceNumber}: {ProductName}\", n, caps.ProductName);\n }\n catch (Exception capEx)\n {\n logger?.LogError(capEx, \"Error getting capabilities for WaveInEvent device number {DeviceNumber}.\", n);\n deviceNames.Add($\"⚠️ {n}\");\n }\n }\n }\n catch (Exception ex)\n {\n logger?.LogError(ex, \"Error enumerating WaveInEvent devices.\");\n\n return [];\n }\n\n return deviceNames;\n }\n\n private void HandleOptionsChange(MicrophoneConfiguration newOptions)\n {\n lock (_lock)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n if ( newOptions.DeviceName == _currentOptions.DeviceName )\n {\n return;\n }\n\n _logger.LogInformation(\"Audio input configuration changed. Reconfiguring microphone. New options: {@Options}\", newOptions);\n _currentOptions = newOptions;\n\n _wasRecordingBeforeReconfigure = _recordingCts is { IsCancellationRequested: false };\n\n StopInternal();\n\n InitializeMicrophone(newOptions);\n\n if ( !_wasRecordingBeforeReconfigure )\n {\n return;\n }\n\n _logger.LogInformation(\"Restarting recording after reconfiguration.\");\n StartRecordingInternal();\n }\n }\n\n private void InitializeMicrophone(MicrophoneConfiguration options)\n {\n lock (_lock)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n DisposeMicrophoneInstance();\n\n var deviceNumber = FindDeviceNumberByName(options.DeviceName);\n if ( deviceNumber == -1 )\n {\n _logger.LogWarning(\"Could not find audio input device named '{DeviceName}'. Falling back to default device (0).\", options.DeviceName);\n deviceNumber = 0;\n }\n\n try\n {\n _waveIn = new WaveInEvent { DeviceNumber = deviceNumber, WaveFormat = new WaveFormat(16000, 16, 1), BufferMilliseconds = 100 };\n\n if ( !IsInitialized )\n {\n Initialize(new AudioSourceHeader { BitsPerSample = 16, Channels = 1, SampleRate = 16000 });\n }\n\n _waveIn.DataAvailable += WaveIn_DataAvailable;\n _waveIn.RecordingStopped += WaveInRecordingStopped;\n\n _logger.LogInformation(\"Microphone initialized with DeviceNumber: {DeviceNumber}, WaveFormat: {WaveFormat}\",\n _waveIn.DeviceNumber, _waveIn.WaveFormat);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to initialize WaveInEvent with DeviceNumber {DeviceNumber} and options {@Options}\", deviceNumber, options);\n _waveIn = null;\n }\n }\n }\n\n private int FindDeviceNumberByName(string? deviceName)\n {\n if ( string.IsNullOrWhiteSpace(deviceName) )\n {\n _logger.LogDebug(\"Device name is null or whitespace, returning default device number 0.\");\n\n return 0;\n }\n\n try\n {\n var devices = GetAvailableDevicesInternal();\n var index = 0;\n foreach ( var name in devices )\n {\n _logger.LogTrace(\"Checking device {DeviceNumber}: {ProductName}\", index, name);\n if ( deviceName.Trim().Equals(name?.Trim(), StringComparison.OrdinalIgnoreCase) )\n {\n _logger.LogDebug(\"Found device '{DeviceName}' at DeviceNumber {DeviceNumber}\", deviceName, index);\n\n return index;\n }\n\n index++;\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error searching for device name '{DeviceName}'.\", deviceName);\n }\n\n _logger.LogWarning(\"Audio input device named '{DeviceName}' not found among available devices.\", deviceName);\n\n return -1;\n }\n\n private void StartRecordingInternal()\n {\n if ( _waveIn == null )\n {\n _logger.LogError(\"Cannot start recording, microphone is not initialized (likely due to previous error).\");\n\n return;\n }\n\n try\n {\n _recordingCts = new CancellationTokenSource();\n _waveIn.StartRecording();\n _logger.LogInformation(\"Microphone recording started.\");\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to start microphone recording.\");\n _recordingCts?.Dispose();\n _recordingCts = null;\n\n throw;\n }\n }\n\n private void StopInternal()\n {\n if ( _waveIn == null || _recordingCts == null || _recordingCts.IsCancellationRequested )\n {\n return;\n }\n\n _logger.LogInformation(\"Stopping microphone recording...\");\n try\n {\n _recordingCts.Cancel();\n _waveIn?.StopRecording();\n\n _logger.LogInformation(\"Microphone recording stopped.\");\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during microphone StopRecording.\");\n }\n finally\n {\n _recordingCts?.Dispose();\n _recordingCts = null;\n }\n }\n\n private void WaveIn_DataAvailable(object? sender, WaveInEventArgs e)\n {\n if ( _recordingCts is not { IsCancellationRequested: false } )\n {\n return;\n }\n\n var sourceSpan = e.Buffer.AsMemory(0, e.BytesRecorded);\n WriteData(sourceSpan);\n }\n\n private void WaveInRecordingStopped(object? sender, StoppedEventArgs e)\n {\n _logger.LogDebug(\"MicrophoneIn_RecordingStopped event received.\");\n if ( e.Exception != null )\n {\n _logger.LogError(e.Exception, \"An error occurred during microphone recording.\");\n // Decide how to handle this - maybe set an error state?\n // For now, just log it. Reconfiguration might fix it later.\n }\n\n _logger.LogDebug(\"Microphone stream flushed after stopping.\");\n }\n\n private void DisposeMicrophoneInstance()\n {\n if ( _waveIn == null )\n {\n return;\n }\n\n _logger.LogDebug(\"Disposing existing WaveInEvent instance.\");\n _waveIn.DataAvailable -= WaveIn_DataAvailable;\n _waveIn.RecordingStopped -= WaveInRecordingStopped;\n\n if ( _recordingCts is { IsCancellationRequested: false } )\n {\n _logger.LogWarning(\"Disposing microphone instance while it was potentially still marked as recording. Stopping first.\");\n StopInternal();\n }\n\n _waveIn.Dispose();\n _waveIn = null;\n }\n\n protected override void Dispose(bool disposing)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n if ( disposing )\n {\n _logger.LogInformation(\"Disposing MicrophoneInputNAudioSource...\");\n lock (_lock)\n {\n _isDisposed = true;\n _optionsChangeListener?.Dispose();\n\n StopInternal();\n DisposeMicrophoneInstance();\n\n Flush();\n\n _recordingCts?.Dispose();\n _recordingCts = null;\n }\n\n _logger.LogInformation(\"MicrophoneInputNAudioSource disposed.\");\n }\n\n base.Dispose(disposing);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Adapters/Audio/Output/PortaudioOutputAdapter.cs", "using System.Runtime.InteropServices;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Audio.Player;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nusing PortAudioSharp;\n\nusing Stream = PortAudioSharp.Stream;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Output;\n\npublic class PortaudioOutputAdapter(ILogger logger, IAudioProgressNotifier progressNotifier) : IAudioOutputAdapter\n{\n private const int DefaultSampleRate = 24000;\n\n private const int DefaultFrameBufferSize = 1024;\n\n private readonly float[] _frameBuffer = new float[DefaultFrameBufferSize];\n\n private Stream? _audioStream;\n\n private AudioBuffer? _currentBuffer;\n\n private ChannelReader? _currentReader;\n\n private Guid _currentTurnId;\n\n private long _framesOfChunkPlayed;\n\n private TaskCompletionSource? _playbackCompletion;\n\n private CancellationTokenSource? _playbackCts;\n\n private volatile bool _producerCompleted;\n\n private Channel? _progressChannel;\n\n private Guid _sessionId;\n\n public ValueTask DisposeAsync()\n {\n try\n {\n _audioStream = null;\n }\n catch\n {\n /* ignored */\n }\n\n return ValueTask.CompletedTask;\n }\n\n public Guid AdapterId { get; } = Guid.NewGuid();\n\n public ValueTask InitializeAsync(Guid sessionId, CancellationToken cancellationToken)\n {\n _sessionId = sessionId;\n\n try\n {\n PortAudio.Initialize();\n var deviceIndex = PortAudio.DefaultOutputDevice;\n if ( deviceIndex == PortAudio.NoDevice )\n {\n throw new AudioDeviceNotFoundException(\"No default PortAudio output device found.\");\n }\n\n var deviceInfo = PortAudio.GetDeviceInfo(deviceIndex);\n logger.LogDebug(\"Using PortAudio output device: {DeviceName} (Index: {DeviceIndex})\", deviceInfo.name, deviceIndex);\n\n var parameters = new StreamParameters {\n device = deviceIndex,\n channelCount = 1,\n sampleFormat = SampleFormat.Float32,\n suggestedLatency = deviceInfo.defaultLowOutputLatency,\n hostApiSpecificStreamInfo = IntPtr.Zero\n };\n\n _audioStream = new Stream(\n null,\n parameters,\n DefaultSampleRate,\n DefaultFrameBufferSize,\n StreamFlags.ClipOff,\n AudioCallback,\n IntPtr.Zero);\n }\n catch (Exception ex)\n {\n logger.LogError(ex, \"Failed to initialize PortAudio or create stream.\");\n\n try\n {\n PortAudio.Terminate();\n }\n catch\n {\n // ignored\n }\n\n throw new AudioPlayerInitializationException(\"Failed to initialize PortAudio audio system.\", ex);\n }\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StartAsync(CancellationToken cancellationToken)\n {\n // Don't start it here, SendAsync will handle it.\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StopAsync(CancellationToken cancellationToken)\n {\n // Don't stop it here, SendAsync's cleanup or cancellation will handle it.\n // If a hard stop independent of SendAsync is needed, cancellation of SendAsync's token is the way.\n\n return ValueTask.CompletedTask;\n }\n\n public async Task SendAsync(ChannelReader inputReader, ChannelWriter outputWriter, Guid turnId, CancellationToken cancellationToken = default)\n {\n if ( _audioStream == null )\n {\n throw new InvalidOperationException(\"Audio stream is not initialized.\");\n }\n\n _currentTurnId = turnId;\n _currentReader = inputReader;\n\n _progressChannel = Channel.CreateBounded(new BoundedChannelOptions(10) { SingleReader = true, SingleWriter = true });\n\n _playbackCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _playbackCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);\n\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n var localPlaybackCts = _playbackCts;\n var localCompletion = _playbackCompletion;\n using var eventLoopCts = new CancellationTokenSource();\n var progressPumpTask = ProgressEventsLoop(eventLoopCts.Token);\n\n try\n {\n _audioStream.Start();\n\n while ( await inputReader.WaitToReadAsync(localPlaybackCts.Token).ConfigureAwait(false) )\n {\n if ( !firstChunk )\n {\n continue;\n }\n\n var firstChunkEvent = new AudioPlaybackStartedEvent(_sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, localPlaybackCts.Token).ConfigureAwait(false);\n\n firstChunk = false;\n }\n\n _producerCompleted = true;\n\n await localCompletion.Task.ConfigureAwait(false);\n await progressPumpTask.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n\n eventLoopCts.CancelAfter(250);\n\n await localCompletion.Task.ConfigureAwait(false);\n await progressPumpTask.ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n\n await outputWriter.WriteAsync(new ErrorOutputEvent(_sessionId, turnId, DateTimeOffset.UtcNow, ex), CancellationToken.None).ConfigureAwait(false);\n }\n finally\n {\n CleanupPlayback();\n\n if ( !firstChunk )\n {\n await outputWriter.WriteAsync(new AudioPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, completedReason), CancellationToken.None).ConfigureAwait(false);\n }\n }\n }\n\n private async ValueTask ProgressEventsLoop(CancellationToken ct = default)\n {\n var eventsReader = _progressChannel!.Reader;\n\n await foreach ( var progressEvent in eventsReader.ReadAllAsync(ct).ConfigureAwait(false) )\n {\n if ( ct.IsCancellationRequested )\n {\n break;\n }\n\n switch ( progressEvent )\n {\n case AudioChunkPlaybackStartedEvent startedArgs:\n progressNotifier.RaiseChunkStarted(this, startedArgs);\n\n break;\n case AudioChunkPlaybackEndedEvent endedArgs:\n progressNotifier.RaiseChunkEnded(this, endedArgs);\n\n break;\n case AudioPlaybackProgressEvent progressArgs:\n progressNotifier.RaiseProgress(this, progressArgs);\n\n break;\n }\n }\n }\n\n private void CleanupPlayback()\n {\n _audioStream?.Stop();\n\n _currentTurnId = Guid.Empty;\n _currentReader = null;\n\n _progressChannel?.Writer.TryComplete();\n _producerCompleted = false;\n _framesOfChunkPlayed = 0;\n _currentBuffer = null;\n\n _playbackCts?.Cancel();\n _playbackCts?.Dispose();\n _playbackCts = null;\n\n Array.Clear(_frameBuffer, 0, DefaultFrameBufferSize);\n }\n\n private StreamCallbackResult AudioCallback(IntPtr input, IntPtr output, uint framecount, ref StreamCallbackTimeInfo timeinfo, StreamCallbackFlags statusflags, IntPtr userdataptr)\n {\n var framesRequested = (int)framecount;\n var framesWritten = 0;\n\n var turnId = _currentTurnId;\n var reader = _currentReader;\n var completionSource = _playbackCompletion;\n var currentPlaybackCts = _playbackCts;\n var ct = currentPlaybackCts?.Token ?? CancellationToken.None;\n var progressWriter = _progressChannel!.Writer;\n\n if ( reader == null )\n {\n completionSource?.TrySetResult(false);\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n while ( framesWritten < framesRequested )\n {\n if ( ct.IsCancellationRequested )\n {\n FillSilence();\n completionSource?.TrySetResult(false);\n\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n if ( _currentBuffer == null )\n {\n if ( reader.TryRead(out var chunk) )\n {\n _currentBuffer = new AudioBuffer(chunk.Chunk.AudioData, chunk.Chunk);\n progressWriter.TryWrite(new AudioChunkPlaybackStartedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, chunk.Chunk));\n }\n else\n {\n if ( _producerCompleted )\n {\n FillSilence();\n completionSource?.TrySetResult(true);\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n FillSilence();\n }\n }\n\n if ( _currentBuffer == null )\n {\n return StreamCallbackResult.Continue;\n }\n\n var framesToCopy = Math.Min(framesRequested - framesWritten, _currentBuffer.Remaining);\n var sourceSpan = _currentBuffer.Data.Span.Slice(_currentBuffer.Position, framesToCopy);\n var destinationSpan = _frameBuffer.AsSpan(framesWritten, framesToCopy);\n sourceSpan.CopyTo(destinationSpan);\n _currentBuffer.Advance(framesToCopy);\n framesWritten += framesToCopy;\n\n if ( _currentBuffer.IsFinished )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n _framesOfChunkPlayed = 0;\n _currentBuffer = null;\n }\n }\n\n Marshal.Copy(_frameBuffer, 0, output, framesRequested);\n\n _framesOfChunkPlayed += framesRequested;\n var currentTime = TimeSpan.FromSeconds((double)_framesOfChunkPlayed / DefaultSampleRate);\n progressWriter.TryWrite(new AudioPlaybackProgressEvent(_sessionId, turnId, DateTimeOffset.UtcNow, currentTime));\n\n if ( _currentBuffer == null && _producerCompleted )\n {\n completionSource?.TrySetResult(true);\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n if ( ct.IsCancellationRequested )\n {\n completionSource?.TrySetResult(false);\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n return StreamCallbackResult.Continue;\n\n void FillSilence()\n {\n if ( framesWritten < framesRequested )\n {\n Array.Clear(_frameBuffer, framesWritten, framesRequested - framesWritten);\n }\n\n Marshal.Copy(_frameBuffer, 0, output, framesRequested);\n }\n }\n\n private sealed class AudioBuffer(Memory data, AudioSegment segment)\n {\n public Memory Data { get; } = data;\n\n public AudioSegment Segment { get; } = segment;\n\n public int Position { get; private set; } = 0;\n\n public int Remaining => Data.Length - Position;\n\n public bool IsFinished => Position >= Data.Length;\n\n public void Advance(int count) { Position += count; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/RouletteWheel.cs", "using System.Drawing;\nusing System.Numerics;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic partial class RouletteWheel : IRenderComponent\n{\n private const int MAX_VERTICES = 64;\n\n private const int MAX_INDICES = MAX_VERTICES * 6 / 4;\n\n private const float OUTER_RADIUS_FACTOR = 0.8f;\n\n private const float INNER_RADIUS_FACTOR = 0.64f; // OUTER_RADIUS_FACTOR * 0.8f\n\n private const float CENTER_RADIUS_FACTOR = 0.128f; // INNER_RADIUS_FACTOR * 0.2f\n\n private static readonly short[] _indexData = GenerateIndexArray();\n\n private readonly Lock _applyingConfig = new();\n\n private readonly IOptionsMonitor _config;\n\n private readonly FontProvider _fontProvider;\n\n private readonly Dictionary _segmentFontSizes = new();\n\n private readonly float _textSizeAdaptationFactor = 1.0f;\n\n private readonly VertexPositionTexture[] _vertexData = new VertexPositionTexture[MAX_VERTICES];\n\n private GL _gl;\n\n private BufferObject _indexBuffer;\n\n private float _minRotations;\n\n private int _numSections = 0;\n\n private Action? _onSpinCompleteCallback;\n\n private Vector2 _position = Vector2.Zero;\n\n private bool _radialTextOrientation = true;\n\n private string[] _sectionLabels;\n\n private Shader _shader;\n\n private float _spinDuration;\n\n private float _spinStartTime = 0f;\n\n private float _startSegment = 0f;\n\n private float _targetSegment = 0f;\n\n private FSColor _textColor = new(255, 255, 255, 255);\n\n private TextRenderer _textRenderer;\n\n private float _textScale = 1.0f;\n\n private int _textStrokeWidth = 2;\n\n private float _time = 0f;\n\n private bool _useAdaptiveTextSize = true;\n\n private VertexArrayObject _vao;\n\n private BufferObject _vertexBuffer;\n\n private int _vertexIndex = 0;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n private float _wheelSize = 1;\n\n public RouletteWheel(IOptionsMonitor config, FontProvider fontProvider)\n {\n _config = config;\n _fontProvider = fontProvider;\n }\n\n public bool IsSpinning { get; private set; } = false;\n\n public float Progress { get; private set; } = 1f;\n\n public int NumberOfSections\n {\n get => _numSections;\n private set\n {\n _numSections = Math.Clamp(value, 2, 24);\n _targetSegment = Math.Min(_targetSegment, _numSections - 1);\n _startSegment = Math.Min(_startSegment, _numSections - 1);\n ResizeSectionLabels();\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n }\n\n public bool UseSpout => true;\n\n public string SpoutTarget => \"RouletteWheel\";\n\n public int Priority => 0;\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _textRenderer = new TextRenderer(gl);\n\n // Initialize buffers\n _vertexBuffer = new BufferObject(gl, MAX_VERTICES, BufferTargetARB.ArrayBuffer, true);\n _indexBuffer = new BufferObject(gl, _indexData.Length, BufferTargetARB.ElementArrayBuffer, false);\n _indexBuffer.SetData(_indexData, 0, _indexData.Length);\n\n // Initialize shader\n var vertSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"wheel_shader.vert\"));\n var fragSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"wheel_shader.frag\"));\n _shader = new Shader(_gl, vertSrc, fragSrc);\n\n // Setup VAO\n unsafe\n {\n _vao = new VertexArrayObject(gl, sizeof(VertexPositionTexture));\n _vao.Bind();\n }\n\n var location = _shader.GetAttribLocation(\"a_position\");\n _vao.VertexAttribPointer(location, 3, VertexAttribPointerType.Float, false, 0);\n\n location = _shader.GetAttribLocation(\"a_texCoords0\");\n _vao.VertexAttribPointer(location, 2, VertexAttribPointerType.Float, false, 12);\n\n ResizeSectionLabels();\n\n ApplyConfiguration(_config.CurrentValue);\n\n _config.OnChange(ApplyConfiguration);\n\n // Prevent wheel from spinning on creation\n _spinStartTime = -_spinDuration;\n }\n\n public void Update(float deltaTime)\n {\n _time += deltaTime;\n\n if ( IsSpinning )\n {\n var progress = Math.Min((_time - _spinStartTime) / _spinDuration, 1.0f);\n Progress = progress;\n }\n\n if ( IsSpinning && _time - _spinStartTime >= _spinDuration )\n {\n IsSpinning = false;\n _onSpinCompleteCallback?.Invoke((int)_targetSegment);\n _onSpinCompleteCallback = null;\n }\n\n UpdateVisibilityAnimation();\n }\n\n public void Render(float deltaTime)\n {\n lock (_applyingConfig)\n {\n // Skip rendering if wheel is disabled and not animating\n if ( !IsEnabled && CurrentAnimationState == AnimationState.Idle )\n {\n return;\n }\n\n var originalWheelSize = _wheelSize;\n _wheelSize *= _animationCurrentScale;\n\n Begin();\n DrawWheel();\n End();\n\n // Only render labels if wheel is sufficiently visible\n if ( _animationCurrentScale > 0.25f )\n {\n RenderSectionLabels();\n }\n\n _wheelSize = originalWheelSize;\n }\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n\n return;\n\n _vao.Dispose();\n _vertexBuffer.Dispose();\n _indexBuffer.Dispose();\n _shader.Dispose();\n _textRenderer.Dispose();\n }\n\n public string GetLabel(int index) { return _sectionLabels[index]; }\n\n public string[] GetLabels() { return _sectionLabels.ToArray(); }\n\n public void Spin(int targetSection, Action? onSpinComplete = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return;\n }\n\n _targetSegment = Math.Clamp(targetSection, 0, _numSections - 1);\n _startSegment = GetCurrentWheelPosition();\n _spinStartTime = _time;\n IsSpinning = true;\n _onSpinCompleteCallback = onSpinComplete;\n Progress = 0;\n }\n\n public int SpinRandom(Action? onSpinComplete = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return -1;\n }\n\n var target = Random.Shared.Next(_numSections);\n Spin(target, onSpinComplete);\n\n return target;\n }\n\n public Task SpinAsync(int? targetSection = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return Task.FromResult(-1);\n }\n\n var tcs = new TaskCompletionSource();\n var target = targetSection ?? Random.Shared.Next(_numSections);\n\n Spin(target, result => tcs.SetResult(result));\n\n return tcs.Task;\n }\n\n public void SetSectionLabels(string[] labels)\n {\n if ( labels.Length == 0 )\n {\n return;\n }\n\n if ( labels.Length != _numSections )\n {\n NumberOfSections = labels.Length;\n }\n\n for ( var i = 0; i < _numSections; i++ )\n {\n _sectionLabels[i] = labels[i];\n }\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n public void ConfigureTextStyle(\n bool radialText = true,\n Color? textColor = null,\n float scale = 1.0f,\n int strokeWidth = 2,\n bool useAdaptiveSize = true)\n {\n var color = textColor ?? Color.White;\n\n _textColor = new FSColor(color.R, color.G, color.B, color.A);\n _textScale = scale;\n _textStrokeWidth = strokeWidth;\n _radialTextOrientation = radialText;\n _useAdaptiveTextSize = useAdaptiveSize;\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n private static short[] GenerateIndexArray()\n {\n var result = new short[MAX_INDICES];\n for ( int i = 0,\n vi = 0; i < MAX_INDICES; i += 6, vi += 4 )\n {\n result[i] = (short)vi;\n result[i + 1] = (short)(vi + 1);\n result[i + 2] = (short)(vi + 2);\n result[i + 3] = (short)(vi + 1);\n result[i + 4] = (short)(vi + 3);\n result[i + 5] = (short)(vi + 2);\n }\n\n return result;\n }\n\n private void Begin()\n {\n _gl.Disable(EnableCap.DepthTest);\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n\n _shader.Use();\n UpdateShaderParameters();\n\n var projectionMatrix = Matrix4x4.CreateOrthographicOffCenter(0, _viewportWidth, _viewportHeight, 0, -1, 1);\n _shader.SetUniform(\"MatrixTransform\", projectionMatrix);\n\n _vao.Bind();\n _vertexBuffer.Bind();\n _indexBuffer.Bind();\n }\n\n private void End() { FlushBuffer(); }\n\n private unsafe void FlushBuffer()\n {\n if ( _vertexIndex == 0 )\n {\n return;\n }\n\n _vertexBuffer.SetData(_vertexData, 0, _vertexIndex);\n _gl.DrawElements(PrimitiveType.Triangles, (uint)(_vertexIndex * 6 / 4), DrawElementsType.UnsignedShort, null);\n _vertexIndex = 0;\n }\n\n private void DrawWheel()\n {\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var centerX = _position.X;\n var centerY = _position.Y;\n var cosR = (float)Math.Cos(Rotation);\n var sinR = (float)Math.Sin(Rotation);\n var left = centerX - radius;\n var right = centerX + radius;\n var top = centerY - radius;\n var bottom = centerY + radius;\n\n // Top-left vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(left, top, 0), centerX, centerY, cosR, sinR),\n new Vector2(0, 0));\n\n // Top-right vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(right, top, 0), centerX, centerY, cosR, sinR),\n new Vector2(1, 0));\n\n // Bottom-left vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(left, bottom, 0), centerX, centerY, cosR, sinR),\n new Vector2(0, 1));\n\n // Bottom-right vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(right, bottom, 0), centerX, centerY, cosR, sinR),\n new Vector2(1, 1));\n }\n\n private void RenderSectionLabels()\n {\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var innerRadius = radius * INNER_RADIUS_FACTOR;\n var centerRadius = radius * CENTER_RADIUS_FACTOR;\n var centerX = _position.X != 0 ? _position.X : _viewportWidth / 2.0f;\n var centerY = _position.Y != 0 ? _position.Y : _viewportHeight / 2.0f;\n var availableRadialSpace = innerRadius - centerRadius;\n var textRadius = centerRadius + availableRadialSpace * 0.5f;\n var currentRotation = GetCurrentWheelRotation();\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n\n if ( _useAdaptiveTextSize && _segmentFontSizes.Count != _numSections )\n {\n CalculateAllSegmentFontSizes();\n }\n\n _textRenderer.Begin();\n\n var fontSystem = _fontProvider.GetFontSystem(_config.CurrentValue.Font);\n\n // Reusable Vector2 for text position to avoid allocation in the loop\n var position = new Vector2();\n\n for ( var i = 0; i < _numSections; i++ )\n {\n if ( string.IsNullOrEmpty(_sectionLabels[i]) )\n {\n continue;\n }\n\n var fontSize = _useAdaptiveTextSize ? _segmentFontSizes[i] : _config.CurrentValue.FontSize;\n var segmentFont = fontSystem.GetFont(fontSize);\n\n var rotatedStartAngle = -currentRotation;\n var rotatedEndAngle = segmentAngle - currentRotation;\n var segmentCenter = (rotatedStartAngle + rotatedEndAngle) / 2.0f + (_numSections - 1 - i) * segmentAngle;\n\n // Position text\n var textX = centerX + textRadius * MathF.Cos(segmentCenter);\n var textY = centerY + textRadius * MathF.Sin(segmentCenter);\n var textSize = segmentFont.MeasureString(_sectionLabels[i]);\n\n // Update position instead of creating a new Vector2\n position.X = textX;\n position.Y = textY;\n\n // Calculate text rotation\n var textRotation = _radialTextOrientation\n ? MathF.Atan2(textY - centerY, textX - centerX)\n : 0.0f;\n\n // Draw text\n segmentFont.DrawText(\n _textRenderer,\n _sectionLabels[i],\n position,\n _textColor,\n textRotation,\n scale: new Vector2(_textScale),\n effect: FontSystemEffect.Stroked,\n effectAmount: _textStrokeWidth,\n origin: textSize / 2);\n }\n\n _textRenderer.End();\n }\n\n private Vector3 RotatePoint(Vector3 point, float centerX, float centerY, float cosR, float sinR)\n {\n var x = point.X - centerX;\n var y = point.Y - centerY;\n\n var newX = x * cosR - y * sinR + centerX;\n var newY = x * sinR + y * cosR + centerY;\n\n return new Vector3(newX, newY, point.Z);\n }\n\n private float GetCurrentWheelPosition()\n {\n if ( !IsSpinning )\n {\n return _targetSegment;\n }\n\n if ( Progress >= 1.0f )\n {\n IsSpinning = false;\n\n return _targetSegment;\n }\n\n var easedProgress = EaseOutQuint(Progress);\n\n var segmentDiff = (_targetSegment - _startSegment + _numSections) % _numSections;\n if ( segmentDiff > _numSections / 2.0f )\n {\n segmentDiff -= _numSections;\n }\n\n return (_startSegment + segmentDiff * easedProgress + _numSections) % _numSections;\n }\n\n private float GetCurrentWheelRotation()\n {\n var baseRotation = -Rotation;\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n\n var targetAngle = baseRotation + -(_targetSegment + 0.5f) * segmentAngle + MathF.PI * 1.5f;\n\n if ( !IsSpinning )\n {\n return targetAngle;\n }\n\n var startAngle = baseRotation + -(_startSegment + 0.5f) * segmentAngle + MathF.PI * 1.5f;\n var easedProgress = EaseOutQuint(Progress);\n\n var adjustedExtraAngle = targetAngle - startAngle;\n if ( adjustedExtraAngle > 0.0 )\n {\n adjustedExtraAngle -= 2.0f * MathF.PI;\n }\n\n var spinningAngle = startAngle + (adjustedExtraAngle - _minRotations * 2.0f * MathF.PI) * easedProgress;\n\n return spinningAngle;\n }\n\n private void UpdateShaderParameters()\n {\n _shader.SetUniform(\"u_targetSegment\", _targetSegment);\n _shader.SetUniform(\"u_startSegment\", _startSegment);\n _shader.SetUniform(\"u_spinDuration\", _spinDuration);\n _shader.SetUniform(\"u_minRotations\", _minRotations);\n _shader.SetUniform(\"u_spinStartTime\", _spinStartTime);\n _shader.SetUniform(\"u_time\", _time);\n _shader.SetUniform(\"u_numSlices\", (float)_numSections);\n\n float size = Math.Min(_viewportWidth, _viewportHeight);\n _shader.SetUniform(\"u_resolution\", size, size);\n }\n\n private int CalculateOptimalTextSizeForSegment(string label, int segmentIndex)\n {\n if ( string.IsNullOrEmpty(label) )\n {\n return 24;\n }\n\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var innerRadius = radius * INNER_RADIUS_FACTOR;\n var centerRadius = radius * CENTER_RADIUS_FACTOR;\n var availableRadialSpace = innerRadius - centerRadius;\n var textRadius = centerRadius + availableRadialSpace * 0.5f;\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n var maxWidth = 2.0f * textRadius * MathF.Sin(segmentAngle / 2.0f);\n\n var fontSystem = _fontProvider.GetFontSystem(_config.CurrentValue.Font);\n\n // Binary search for optimal font size\n var minFontSize = 1;\n var maxFontSize = 72;\n var optimalFontSize = _config.CurrentValue.FontSize;\n\n while ( minFontSize <= maxFontSize )\n {\n var currentFontSize = (minFontSize + maxFontSize) / 2;\n\n var testFont = fontSystem.GetFont(currentFontSize);\n var textSize = testFont.MeasureString(label);\n var scaledWidth = textSize.X * _textScale * _textSizeAdaptationFactor;\n\n if ( scaledWidth <= maxWidth * INNER_RADIUS_FACTOR )\n {\n optimalFontSize = currentFontSize;\n minFontSize = currentFontSize + 1;\n }\n else\n {\n maxFontSize = currentFontSize - 1;\n }\n }\n\n return optimalFontSize;\n }\n\n private void CalculateAllSegmentFontSizes()\n {\n if ( !_useAdaptiveTextSize )\n {\n return;\n }\n\n _segmentFontSizes.Clear();\n\n for ( var i = 0; i < _numSections; i++ )\n {\n _segmentFontSizes[i] = string.IsNullOrEmpty(_sectionLabels[i])\n ? 24\n : CalculateOptimalTextSizeForSegment(_sectionLabels[i], i);\n }\n }\n\n private void ResizeSectionLabels()\n {\n var newLabels = new string[_numSections];\n for ( var i = 0; i < _numSections; i++ )\n {\n newLabels[i] = i < _sectionLabels?.Length ? _sectionLabels[i] : $\"Section {i + 1}\";\n }\n\n _sectionLabels = newLabels;\n }\n\n private static float EaseOutQuint(float t) { return 1.0f - MathF.Pow(1.0f - t, 5); }\n\n private void ApplyConfiguration(RouletteWheelOptions options)\n {\n lock (_applyingConfig)\n {\n // Apply text configuration\n _radialTextOrientation = options.RadialTextOrientation;\n _textScale = options.TextScale;\n _textStrokeWidth = options.TextStroke;\n _useAdaptiveTextSize = options.AdaptiveText;\n\n if ( !string.IsNullOrEmpty(options.TextColor) )\n {\n var color = ColorTranslator.FromHtml(options.TextColor);\n _textColor = new FSColor(color.R, color.G, color.B, color.A);\n }\n\n // Apply section labels\n if ( options.SectionLabels?.Length > 0 )\n {\n SetSectionLabels(options.SectionLabels);\n }\n\n // Apply spin parameters\n _spinDuration = Math.Max(options.SpinDuration, 0.1f);\n _minRotations = Math.Max(options.MinRotations, 1.0f);\n\n // Apply wheel size\n _wheelSize = Math.Clamp(options.WheelSizePercentage, 0.1f, 1.0f);\n\n // Apply positioning\n if ( !string.IsNullOrEmpty(options.PositionMode) )\n {\n switch ( options.PositionMode )\n {\n case \"Absolute\":\n _positionMode = PositionMode.Absolute;\n SetAbsolutePosition(options.AbsolutePositionX, options.AbsolutePositionY);\n\n break;\n case \"Percentage\":\n _positionMode = PositionMode.Percentage;\n PositionByPercentage(options.PositionXPercentage, options.PositionYPercentage);\n\n break;\n case \"Anchored\":\n _positionMode = PositionMode.Anchored;\n if ( Enum.TryParse(options.ViewportAnchor, out ViewportAnchor anchor) )\n {\n PositionAt(anchor, new Vector2(options.AnchorOffsetX, options.AnchorOffsetY));\n }\n else\n {\n PositionAt(ViewportAnchor.Center);\n }\n\n break;\n }\n }\n\n // Apply rotation\n Rotation = options.RotationDegrees * MathF.PI / 180;\n\n // Handle viewport size changes\n var viewportChanged = _viewportWidth != options.Width || _viewportHeight != options.Height;\n if ( viewportChanged )\n {\n _viewportWidth = options.Width;\n _viewportHeight = options.Height;\n\n // Update text renderer viewport\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n\n // Update position based on mode\n switch ( _positionMode )\n {\n case PositionMode.Anchored:\n UpdatePositionFromAnchor();\n\n break;\n case PositionMode.Percentage:\n UpdatePositionFromPercentage();\n\n break;\n }\n }\n\n // Apply enabled state (if changed)\n if ( options.Enabled != IsEnabled )\n {\n if ( options.Enabled )\n {\n Enable();\n }\n else\n {\n Disable();\n }\n }\n\n // Recalculate font sizes if needed (after all other changes)\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/EspeakFallbackPhonemizer.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Espeak-based fallback phonemizer matching the Python reference implementation\n/// \npublic class EspeakFallbackPhonemizer : IFallbackPhonemizer\n{\n // Dictionary of espeak to model phoneme mappings, sorted by key length descending (matching Python E2M)\n private static readonly IReadOnlyDictionary E2M = new Dictionary {\n { \"ʔˌn\\u0329\", \"tn\" },\n { \"ʔn\\u0329\", \"tn\" },\n { \"ʔn\", \"tn\" },\n { \"ʔ\", \"t\" },\n { \"a^ɪ\", \"I\" },\n { \"a^ʊ\", \"W\" },\n { \"d^ʒ\", \"ʤ\" },\n { \"e^ɪ\", \"A\" },\n { \"e\", \"A\" },\n { \"t^ʃ\", \"ʧ\" },\n { \"ɔ^ɪ\", \"Y\" },\n { \"ə^l\", \"ᵊl\" },\n { \"ʲo\", \"jo\" },\n { \"ʲə\", \"jə\" },\n { \"ʲ\", \"\" },\n { \"ɚ\", \"əɹ\" },\n { \"r\", \"ɹ\" },\n { \"x\", \"k\" },\n { \"ç\", \"k\" },\n { \"ɐ\", \"ə\" },\n { \"ɬ\", \"l\" },\n { \"\\u0303\", \"\" }\n }.OrderByDescending(kv => kv.Key.Length).ToDictionary(kv => kv.Key, kv => kv.Value);\n\n // Add a cache to avoid repeated processing\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly ILogger _logger;\n\n private readonly SemaphoreSlim _processLock = new(1, 1);\n\n private readonly int _processReadTimeoutMs = 2000;\n\n private readonly int _processStartTimeoutMs = 5000;\n\n private readonly IOptionsMonitor _ttsConfig;\n\n private readonly IDisposable? _ttsConfigChangeToken;\n\n private readonly IOptionsMonitor _voiceOptions;\n\n private readonly IDisposable? _voiceOptionsChangeToken;\n\n private bool _disposed;\n\n private volatile string _espeakPath;\n\n // Process state\n private Process? _espeakProcess;\n\n private volatile bool _needProcessReset;\n\n private volatile bool _useBritishEnglish;\n\n public EspeakFallbackPhonemizer(\n IOptionsMonitor ttsConfig,\n IOptionsMonitor voiceOptions,\n ILogger logger)\n {\n _ttsConfig = ttsConfig ?? throw new ArgumentNullException(nameof(ttsConfig));\n _voiceOptions = voiceOptions ?? throw new ArgumentNullException(nameof(voiceOptions));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n _espeakPath = _ttsConfig.CurrentValue.EspeakPath ?? throw new ArgumentNullException(nameof(ttsConfig.CurrentValue.EspeakPath));\n _useBritishEnglish = _voiceOptions.CurrentValue.UseBritishEnglish;\n\n _voiceOptionsChangeToken = _voiceOptions.OnChange(options =>\n {\n _useBritishEnglish = options.UseBritishEnglish;\n _logger.LogDebug(\"Voice options updated: UseBritishEnglish={UseBritishEnglish}\", _useBritishEnglish);\n _needProcessReset = true;\n\n // Clear cache when voice options change\n _cache.Clear();\n });\n\n _ttsConfigChangeToken = _ttsConfig.OnChange(config =>\n {\n if ( string.IsNullOrEmpty(config.EspeakPath) || _espeakPath == config.EspeakPath )\n {\n return;\n }\n\n _espeakPath = config.EspeakPath;\n _logger.LogDebug(\"TTS configuration updated: EspeakPath={EspeakPath}\", _espeakPath);\n _needProcessReset = true;\n\n // Clear cache when espeak path changes\n _cache.Clear();\n });\n }\n\n /// \n /// Gets phonemes for a word using espeak-ng command-line tool\n /// \n public async Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(\n string word,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(word) )\n {\n return (null, null);\n }\n\n // Check cache first\n if ( _cache.TryGetValue(word, out var cachedResult) )\n {\n return cachedResult;\n }\n\n var cancelled = false;\n\n try\n {\n await _processLock.WaitAsync(cancellationToken);\n\n // Check cache again in case another thread added the result while we were waiting\n if ( _cache.TryGetValue(word, out cachedResult) )\n {\n return cachedResult;\n }\n\n var cleanWord = SanitizeInput(word);\n\n // Ensure the process is running\n var process = await EnsureProcessIsInitializedAsync(cancellationToken);\n\n // Write the word to the process stdin\n await process.StandardInput.WriteLineAsync(cleanWord);\n await process.StandardInput.FlushAsync();\n\n // Read the output with a timeout\n var readTask = process.StandardOutput.ReadLineAsync();\n\n if ( await Task.WhenAny(readTask, Task.Delay(_processReadTimeoutMs, cancellationToken)) != readTask )\n {\n _logger.LogWarning(\"Timeout reading output from espeak-ng for word {Word}\", word);\n _needProcessReset = true;\n\n return (null, null);\n }\n\n var output = await readTask;\n\n if ( string.IsNullOrEmpty(output) )\n {\n _logger.LogDebug(\"Empty output from espeak-ng for word {Word}\", word);\n _needProcessReset = true;\n\n return (null, null);\n }\n\n var phonemes = NormalizeEspeakOutput(output.Trim(), _useBritishEnglish);\n\n var result = (phonemes, 2);\n\n // Add to cache\n _cache[word] = result;\n\n return result;\n }\n catch (OperationCanceledException)\n {\n cancelled = true;\n\n return (null, null);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting phonemes from espeak-ng for word {Word}\", word);\n _needProcessReset = true;\n\n return (null, null);\n }\n finally\n {\n if ( !cancelled )\n {\n _processLock.Release();\n }\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voiceOptionsChangeToken?.Dispose();\n _ttsConfigChangeToken?.Dispose();\n\n if ( _espeakProcess != null )\n {\n try\n {\n if ( !_espeakProcess.HasExited )\n {\n _espeakProcess.Kill();\n }\n\n _espeakProcess.Dispose();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing espeak-ng process\");\n }\n }\n\n _processLock.Dispose();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Ensures the espeak process is initialized and running\n /// \n private async Task EnsureProcessIsInitializedAsync(CancellationToken cancellationToken)\n {\n // If process needs to be reset or doesn't exist or has exited, create a new one\n if ( _needProcessReset || _espeakProcess == null || _espeakProcess.HasExited )\n {\n // Dispose of the old process if it exists\n if ( _espeakProcess != null )\n {\n try\n {\n if ( !_espeakProcess.HasExited )\n {\n _espeakProcess.Kill();\n }\n\n _espeakProcess.Dispose();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing espeak-ng process\");\n }\n\n _espeakProcess = null;\n }\n\n // Create a new process\n var language = _useBritishEnglish ? \"en-gb\" : \"en-us\";\n var startInfo = new ProcessStartInfo {\n FileName = _espeakPath,\n Arguments = $\"--ipa=1 -v {language} -q --tie=^\",\n RedirectStandardOutput = true,\n RedirectStandardInput = true,\n StandardOutputEncoding = Encoding.UTF8,\n StandardInputEncoding = Encoding.UTF8,\n UseShellExecute = false,\n CreateNoWindow = true\n };\n\n var process = new Process { StartInfo = startInfo };\n\n // Start the process with a timeout\n var startTask = Task.Run(() =>\n {\n process.Start();\n\n return true;\n });\n\n if ( await Task.WhenAny(startTask, Task.Delay(_processStartTimeoutMs, cancellationToken)) != startTask )\n {\n try\n {\n if ( !process.HasExited )\n {\n process.Kill();\n }\n\n process.Dispose();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing espeak-ng process after start timeout\");\n }\n\n throw new TimeoutException(\"Timeout starting espeak-ng process\");\n }\n\n if ( !startTask.Result )\n {\n throw new InvalidOperationException(\"Failed to start espeak-ng process\");\n }\n\n _espeakProcess = process;\n _needProcessReset = false;\n _logger.LogDebug(\"Started new espeak-ng process\");\n }\n\n return _espeakProcess;\n }\n\n /// \n /// Sanitizes input for espeak command line\n /// \n private string SanitizeInput(string input)\n {\n // Remove characters that could cause command line issues\n return input.Replace(\"\\\"\", \"\")\n .Replace(\"\\\\\", \"\")\n .Replace(\";\", \"\")\n .Replace(\"&\", \"\")\n .Replace(\"|\", \"\")\n .Replace(\">\", \"\")\n .Replace(\"<\", \"\")\n .Replace(\"`\", \"\");\n }\n\n /// \n /// Normalizes espeak output to match the Python implementation\n /// \n private string NormalizeEspeakOutput(string output, bool useBritishEnglish)\n {\n // Apply all replacements from E2M dictionary\n var result = output;\n\n // Apply all the E2M replacements in order of key length (longest first)\n foreach ( var kvp in E2M )\n {\n result = result.Replace(kvp.Key, kvp.Value);\n }\n\n // Apply the regex substitution similar to the Python version\n // This converts characters with combining subscript (U+0329) to have a schwa prefix\n result = Regex.Replace(result, @\"(\\S)\\u0329\", \"ᵊ$1\");\n result = result.Replace(\"\\u0329\", \"\");\n\n // Apply language-specific replacements as in the Python implementation\n if ( useBritishEnglish )\n {\n result = result.Replace(\"e^ə\", \"ɛː\");\n result = result.Replace(\"iə\", \"ɪə\");\n result = result.Replace(\"ə^ʊ\", \"Q\");\n }\n else // American English\n {\n result = result.Replace(\"o^ʊ\", \"O\");\n result = result.Replace(\"ɜːɹ\", \"ɜɹ\");\n result = result.Replace(\"ɜː\", \"ɜɹ\");\n result = result.Replace(\"ɪə\", \"iə\");\n result = result.Replace(\"ː\", \"\");\n }\n\n // Common replacement for both language variants\n result = result.Replace(\"o\", \"ɔ\"); // for espeak < 1.52\n\n // Final clean-up - remove tie character and spaces\n return result.Replace(\"^\", \"\").Replace(\" \", \"\");\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCVoiceProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCVoiceProvider : IRVCVoiceProvider\n{\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly ConcurrentDictionary _voicePaths = new();\n\n private bool _disposed;\n\n public RVCVoiceProvider(\n IModelProvider ittsModelProvider,\n ILogger logger)\n {\n _modelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n /// \n public async Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(voiceId) )\n {\n throw new ArgumentException(\"Voice ID cannot be null or empty\", nameof(voiceId));\n }\n\n return await GetVoicePathAsync(voiceId, cancellationToken);\n }\n\n /// \n public async Task> GetAvailableVoicesAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n // Get voice directory\n var model = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCVoices, cancellationToken);\n var voicesDir = model.Path;\n\n if ( !Directory.Exists(voicesDir) )\n {\n _logger.LogWarning(\"Voices directory not found: {Path}\", voicesDir);\n\n return Array.Empty();\n }\n\n // Get all .bin files\n var voiceFiles = Directory.GetFiles(voicesDir, \"*.onnx\");\n\n // Extract voice IDs from filenames\n var voiceIds = new List(voiceFiles.Length);\n\n foreach ( var file in voiceFiles )\n {\n var voiceId = Path.GetFileNameWithoutExtension(file);\n voiceIds.Add(voiceId);\n\n // Cache the path for faster lookup\n _voicePaths[voiceId] = file;\n }\n\n _logger.LogInformation(\"Found {Count} available RVC voices\", voiceIds.Count);\n\n return voiceIds;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available voices\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voicePaths.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n private async Task GetVoicePathAsync(string voiceId, CancellationToken cancellationToken)\n {\n if ( _voicePaths.TryGetValue(voiceId, out var cachedPath) )\n {\n return cachedPath;\n }\n\n var model = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCVoices, cancellationToken);\n var voicesDir = model.Path;\n\n var voicePath = Path.Combine(voicesDir, $\"{voiceId}.onnx\");\n\n if ( !File.Exists(voicePath) )\n {\n _logger.LogWarning(\"Voice file not found: {Path}\", voicePath);\n\n throw new FileNotFoundException($\"Voice file not found for {voiceId}\", voicePath);\n }\n\n _voicePaths[voiceId] = voicePath;\n\n return voicePath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MicrophoneInputPortAudioSource.cs", "using System.Runtime.InteropServices;\nusing System.Text;\n\nusing Microsoft.Extensions.Logging;\n\nusing PortAudioSharp;\n\nusing Stream = PortAudioSharp.Stream;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents a source that captures audio from a microphone.\n/// \npublic sealed class MicrophoneInputPortAudioSource : AwaitableWaveFileSource, IMicrophone\n{\n private readonly int _bitsPerSample;\n\n private readonly int _channels;\n\n private readonly CancellationTokenSource _cts;\n\n private readonly int _deviceNumber;\n\n private readonly uint _framesPerBuffer;\n\n private readonly ILogger _logger;\n\n private readonly int _sampleRate;\n\n private Stream? _audioStream;\n\n private bool _isRecording;\n\n private Dictionary _metadata;\n\n public MicrophoneInputPortAudioSource(\n ILogger logger,\n int deviceNumber = -1,\n int sampleRate = 16000,\n int bitsPerSample = 16,\n int channels = 1,\n uint framesPerBuffer = 0,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : this(new Dictionary(), logger, deviceNumber, sampleRate, bitsPerSample,\n channels, framesPerBuffer, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy) { }\n\n private MicrophoneInputPortAudioSource(\n Dictionary metadata,\n ILogger logger,\n int deviceNumber = -1,\n int sampleRate = 16000,\n int bitsPerSample = 16,\n int channels = 1,\n uint framesPerBuffer = 0,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : base(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy)\n {\n PortAudio.Initialize();\n\n _logger = logger;\n _deviceNumber = deviceNumber == -1 ? PortAudio.DefaultInputDevice : deviceNumber;\n _sampleRate = sampleRate;\n _bitsPerSample = bitsPerSample;\n _channels = channels;\n _framesPerBuffer = framesPerBuffer;\n _cts = new CancellationTokenSource();\n _metadata = metadata;\n\n if ( _deviceNumber == PortAudio.NoDevice )\n {\n var sb = new StringBuilder();\n\n for ( var i = 0; i != PortAudio.DeviceCount; ++i )\n {\n var deviceInfo = PortAudio.GetDeviceInfo(i);\n\n sb.AppendLine($\"[*] Device {i}\");\n sb.AppendLine($\" Name: {deviceInfo.name}\");\n sb.AppendLine($\" Max input channels: {deviceInfo.maxInputChannels}\");\n sb.AppendLine($\" Default sample rate: {deviceInfo.defaultSampleRate}\");\n }\n\n logger.LogWarning(\"Devices available: {Devices}\", sb);\n\n throw new InvalidOperationException(\"No default input device available\");\n }\n\n Initialize(new AudioSourceHeader { BitsPerSample = (ushort)bitsPerSample, Channels = (ushort)channels, SampleRate = (uint)sampleRate });\n\n try\n {\n InitializeAudioStream();\n }\n catch\n {\n PortAudio.Terminate();\n\n throw;\n }\n }\n\n public void StartRecording()\n {\n if ( _isRecording )\n {\n return;\n }\n\n _isRecording = true;\n _audioStream?.Start();\n }\n\n public void StopRecording()\n {\n if ( !_isRecording )\n {\n return;\n }\n\n _isRecording = false;\n _audioStream?.Stop();\n Flush();\n }\n\n public IEnumerable GetAvailableDevices()\n {\n throw new NotImplementedException();\n }\n\n private void InitializeAudioStream()\n {\n var deviceInfo = PortAudio.GetDeviceInfo(_deviceNumber);\n _logger.LogInformation(\"Using input device: {DeviceName}\", deviceInfo.name);\n\n var inputParams = new StreamParameters {\n device = _deviceNumber,\n channelCount = _channels,\n sampleFormat = SampleFormat.Float32,\n suggestedLatency = deviceInfo.defaultLowInputLatency,\n hostApiSpecificStreamInfo = IntPtr.Zero\n };\n\n _audioStream = new Stream(\n inputParams,\n null,\n _sampleRate,\n _framesPerBuffer,\n StreamFlags.ClipOff,\n ProcessAudioCallback,\n IntPtr.Zero);\n }\n\n private StreamCallbackResult ProcessAudioCallback(\n IntPtr input,\n IntPtr output,\n uint frameCount,\n ref StreamCallbackTimeInfo timeInfo,\n StreamCallbackFlags statusFlags,\n IntPtr userData)\n {\n if ( _cts.Token.IsCancellationRequested )\n {\n return StreamCallbackResult.Complete;\n }\n\n try\n {\n var samples = new float[frameCount];\n Marshal.Copy(input, samples, 0, (int)frameCount);\n\n var byteArray = SampleSerializer.Serialize(samples, Header.BitsPerSample);\n\n WriteData(byteArray);\n\n return StreamCallbackResult.Continue;\n }\n catch\n {\n return StreamCallbackResult.Abort;\n }\n }\n\n protected override void Dispose(bool disposing)\n {\n if ( disposing )\n {\n _cts.Cancel();\n StopRecording();\n _audioStream?.Dispose();\n _audioStream = null;\n PortAudio.Terminate();\n }\n\n base.Dispose(disposing);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ServiceCollectionExtensions.cs", "#pragma warning disable SKEXP0001\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\n\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing Microsoft.Extensions.Options;\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.SemanticKernel;\n\nusing PersonaEngine.Lib.ASR.Transcriber;\nusing PersonaEngine.Lib.ASR.VAD;\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Input;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Output;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Metrics;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Session;\nusing PersonaEngine.Lib.Live2D;\nusing PersonaEngine.Lib.Live2D.Behaviour;\nusing PersonaEngine.Lib.Live2D.Behaviour.Emotion;\nusing PersonaEngine.Lib.Live2D.Behaviour.LipSync;\nusing PersonaEngine.Lib.LLM;\nusing PersonaEngine.Lib.Logging;\nusing PersonaEngine.Lib.TTS.Audio;\nusing PersonaEngine.Lib.TTS.Profanity;\nusing PersonaEngine.Lib.TTS.RVC;\nusing PersonaEngine.Lib.TTS.Synthesis;\nusing PersonaEngine.Lib.UI;\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.GUI;\nusing PersonaEngine.Lib.UI.RouletteWheel;\nusing PersonaEngine.Lib.UI.Text.Subtitles;\nusing PersonaEngine.Lib.Vision;\n\nusing Polly;\nusing Polly.Retry;\nusing Polly.Timeout;\n\nnamespace PersonaEngine.Lib;\n\npublic static class ServiceCollectionExtensions\n{\n public static IServiceCollection AddApp(this IServiceCollection services, IConfiguration configuration, Action? configureKernel = null)\n {\n services.Configure(configuration.GetSection(\"Config\"));\n\n services.AddConversation(configuration, configureKernel);\n services.AddUI(configuration);\n services.AddLive2D(configuration);\n services.AddSystemAudioPlayer();\n services.AddPolly(configuration);\n\n services.AddSingleton();\n\n OrtEnv.Instance().EnvLogLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR;\n\n return services;\n }\n\n public static IServiceCollection AddConversation(this IServiceCollection services, IConfiguration configuration, Action? configureKernel = null)\n {\n services.AddASRSystem(configuration);\n services.AddTTSSystem(configuration);\n services.AddRVC(configuration);\n#pragma warning disable SKEXP0010\n services.AddLLM(configuration, configureKernel);\n#pragma warning restore SKEXP0010\n services.AddChatEngineSystem(configuration);\n\n services.AddConversationPipeline(configuration);\n\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddConversationPipeline(this IServiceCollection services, IConfiguration configuration)\n {\n services.AddSingleton();\n\n services.AddSingleton();\n\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddASRSystem(this IServiceCollection services, IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Asr\"));\n services.Configure(configuration.GetSection(\"Config:Microphone\"));\n\n services.AddSingleton(sp =>\n {\n var asrOptions = sp.GetRequiredService>().Value;\n\n var siletroOptions = new SileroVadOptions(ModelUtils.GetModelPath(ModelType.Silero)) { Threshold = asrOptions.VadThreshold, ThresholdGap = asrOptions.VadThresholdGap };\n\n var vadOptions = new VadDetectorOptions { MinSpeechDuration = TimeSpan.FromMilliseconds(asrOptions.VadMinSpeechDuration), MinSilenceDuration = TimeSpan.FromMilliseconds(asrOptions.VadMinSilenceDuration) };\n\n return new SileroVadDetector(vadOptions, siletroOptions);\n });\n\n services.AddSingleton(sp =>\n {\n var asrOptions = sp.GetRequiredService>().Value;\n\n var realtimeSpeechTranscriptorOptions = new RealtimeSpeechTranscriptorOptions {\n AutodetectLanguageOnce = false, // Flag to detect the language only once or for each segment\n IncludeSpeechRecogizingEvents = true, // Flag to include speech recognizing events (RealtimeSegmentRecognizing)\n RetrieveTokenDetails = false, // Flag to retrieve token details\n LanguageAutoDetect = false, // Flag to auto-detect the language\n Language = new CultureInfo(\"en-US\"), // Language to use for transcription\n Prompt = asrOptions.TtsPrompt,\n Template = asrOptions.TtsMode\n };\n\n var realTimeOptions = new RealtimeOptions();\n\n return new RealtimeTranscriptor(\n new WhisperSpeechTranscriptorFactory(ModelUtils.GetModelPath(ModelType.WhisperGgmlTurbov3)),\n sp.GetRequiredService(),\n new WhisperSpeechTranscriptorFactory(ModelUtils.GetModelPath(ModelType.WhisperGgmlTiny)),\n realtimeSpeechTranscriptorOptions,\n realTimeOptions,\n sp.GetRequiredService>());\n });\n\n services.AddSingleton();\n services.AddSingleton(sp => sp.GetRequiredService());\n\n return services;\n }\n\n public static IServiceCollection AddSystemAudioPlayer(this IServiceCollection services)\n {\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddChatEngineSystem(this IServiceCollection services, IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Conversation\"));\n services.Configure(configuration.GetSection(\"Config:ConversationContext\"));\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n [Experimental(\"SKEXP0010\")]\n public static IServiceCollection AddLLM(this IServiceCollection services, IConfiguration configuration, Action? configureKernel = null)\n {\n services.Configure(configuration.GetSection(\"Config:Llm\"));\n\n services.AddSingleton(sp =>\n {\n var llmOptions = sp.GetRequiredService>().Value;\n var kernelBuilder = Kernel.CreateBuilder();\n\n kernelBuilder.AddOpenAIChatCompletion(llmOptions.TextModel, new Uri(llmOptions.TextEndpoint), llmOptions.TextApiKey, serviceId: \"text\");\n kernelBuilder.AddOpenAIChatCompletion(llmOptions.VisionEndpoint, new Uri(llmOptions.VisionEndpoint), llmOptions.VisionApiKey, serviceId: \"vision\");\n\n configureKernel?.Invoke(kernelBuilder);\n\n return kernelBuilder.Build();\n });\n\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddTTSSystem(\n this IServiceCollection services,\n IConfiguration configuration)\n {\n // Add configuration\n services.Configure(configuration.GetSection(\"Config:Tts\"));\n services.Configure(configuration.GetSection(\"Config:Tts:Voice\"));\n\n // Add core TTS components\n services.AddSingleton();\n\n // Add text processing components\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton(provider =>\n {\n var logger = provider.GetRequiredService>();\n var modelProvider = provider.GetRequiredService();\n var basePath = modelProvider.GetModelAsync(TTS.Synthesis.ModelType.OpenNLPDir).GetAwaiter().GetResult().Path;\n var modelPath = Path.Combine(basePath, \"EnglishSD.nbin\");\n\n return new OpenNlpSentenceDetector(modelPath, logger);\n });\n\n // Add phoneme processing components\n services.AddSingleton(provider =>\n {\n var posTagger = provider.GetRequiredService();\n var lexicon = provider.GetRequiredService();\n var fallback = provider.GetRequiredService();\n\n return new PhonemizerG2P(posTagger, lexicon, fallback);\n });\n\n services.AddSingleton(provider =>\n {\n var logger = provider.GetRequiredService>();\n var modelProvider = provider.GetRequiredService();\n\n var basePath = modelProvider.GetModelAsync(TTS.Synthesis.ModelType.OpenNLPDir).GetAwaiter().GetResult().Path;\n var modelPath = Path.Combine(basePath, \"EnglishPOS.nbin\");\n\n return new OpenNlpPosTagger(modelPath, logger);\n });\n\n services.AddSingleton();\n services.AddSingleton();\n\n services.AddSingleton();\n services.AddSingleton(provider =>\n {\n var config = provider.GetRequiredService>().Value;\n var logger = provider.GetRequiredService>();\n\n return new FileModelProvider(config.ModelDirectory, logger);\n });\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddUI(\n this IServiceCollection services,\n IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Subtitle\"));\n services.Configure(configuration.GetSection(\"Config:RouletteWheel\"));\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton(x => x.GetRequiredService());\n services.AddConfigEditor();\n\n services.AddSingleton();\n services.AddSingleton(x => x.GetRequiredService());\n\n return services;\n }\n\n public static IServiceCollection AddLive2D(\n this IServiceCollection services,\n IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Live2D\"));\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddEmotionProcessing(configuration);\n\n return services;\n }\n\n public static IServiceCollection AddConfigEditor(this IServiceCollection services)\n {\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n services.AddSingleton();\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddRVC(this IServiceCollection services, IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Tts:Rvc\"));\n\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddEmotionProcessing(this IServiceCollection services, IConfiguration configuration)\n {\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddPolly(this IServiceCollection services, IConfiguration configuration)\n {\n services.AddResiliencePipeline(\"semantickernel-chat\", pipelineBuilder =>\n {\n pipelineBuilder\n .AddTimeout(TimeSpan.FromSeconds(60))\n .AddRetry(new RetryStrategyOptions {\n Name = \"ChatServiceRetry\",\n ShouldHandle = new PredicateBuilder().Handle(ex => ex is HttpRequestException ||\n ex is TimeoutRejectedException ||\n (ex is KernelException ke && ke.Message.Contains(\"transient\", StringComparison.OrdinalIgnoreCase))),\n Delay = TimeSpan.FromSeconds(2),\n BackoffType = DelayBackoffType.Exponential,\n MaxDelay = TimeSpan.FromSeconds(30),\n MaxRetryAttempts = 3,\n UseJitter = true,\n OnRetry = args =>\n {\n var sessionId = args.Context.Properties.TryGetValue(ResilienceKeys.SessionId, out var x) ? x : Guid.Empty;\n var logger = args.Context.Properties.TryGetValue(ResilienceKeys.Logger, out var y) ? y : NullLogger.Instance;\n logger.LogWarning(\"Request failed/stopped for session {SessionId}. Retrying in {Timespan}. Attempt {RetryAttempt}...\",\n sessionId, args.Duration, args.AttemptNumber);\n\n return ValueTask.CompletedTask;\n }\n });\n });\n\n return services;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleRenderer.cs", "// SubtitleRenderer.cs\n\nusing System.Collections.Concurrent;\nusing System.Drawing;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.Synthesis;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Main class responsible for rendering subtitles using the revised system.\n/// Integrates with audio events, processes segments, manages the timeline, and draws text.\n/// \npublic class SubtitleRenderer : IRenderComponent\n{\n private readonly IAudioProgressNotifier _audioNotifier;\n\n private readonly SubtitleOptions _config;\n\n private readonly FontProvider _fontProvider;\n\n private readonly FSColor _highlightColor;\n\n private readonly FSColor _normalColor;\n\n private readonly ConcurrentQueue _pendingSegments = new();\n\n private TimeSpan _currentPlaybackTime = TimeSpan.Zero;\n\n private GL? _gl;\n\n private bool _isDisposed = false;\n\n private List _linesToRender = new();\n\n private Task _processingTask = Task.CompletedTask;\n\n private SubtitleProcessor _subtitleProcessor;\n\n private SubtitleTimeline _subtitleTimeline;\n\n private TextMeasurer _textMeasurer;\n\n private TextRenderer _textRenderer;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n private IWordAnimator _wordAnimator;\n\n public SubtitleRenderer(\n IOptions configOptions,\n IAudioProgressNotifier audioNotifier,\n FontProvider fontProvider)\n {\n _config = configOptions.Value;\n _audioNotifier = audioNotifier;\n _fontProvider = fontProvider;\n\n var normalColorSys = ColorTranslator.FromHtml(_config.Color);\n _normalColor = new FSColor(normalColorSys.R, normalColorSys.G, normalColorSys.B, normalColorSys.A);\n var hColorSys = ColorTranslator.FromHtml(_config.HighlightColor);\n _highlightColor = new FSColor(hColorSys.R, hColorSys.G, hColorSys.B, hColorSys.A);\n\n SubscribeToAudioNotifier();\n }\n\n public void Dispose()\n {\n if ( _isDisposed )\n {\n return;\n }\n\n _isDisposed = true;\n\n UnsubscribeFromAudioNotifier();\n \n _pendingSegments.Clear();\n\n _linesToRender.Clear();\n\n GC.SuppressFinalize(this);\n }\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _viewportWidth = view.Size.X;\n _viewportHeight = view.Size.Y;\n\n var fontSystem = _fontProvider.GetFontSystem(_config.Font);\n var font = fontSystem.GetFont(_config.FontSize);\n\n _textMeasurer = new TextMeasurer(font, _config.SideMargin, _viewportWidth, _viewportHeight);\n _subtitleProcessor = new SubtitleProcessor(_textMeasurer, _config.AnimationDuration);\n _wordAnimator = new PopAnimator();\n\n _subtitleTimeline = new SubtitleTimeline(\n _config.MaxVisibleLines,\n _config.BottomMargin,\n _textMeasurer.LineHeight + 0.5f,\n _config.InterSegmentSpacing,\n _textMeasurer,\n _wordAnimator,\n _highlightColor,\n _normalColor\n );\n\n _textRenderer = new TextRenderer(_gl);\n\n Resize();\n }\n \n public bool UseSpout { get; } = true;\n\n public string SpoutTarget { get; } = \"Live2D\";\n\n public int Priority { get; } = -100;\n\n public void Update(float deltaTime)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n var currentTime = (float)_currentPlaybackTime.TotalSeconds;\n\n _subtitleTimeline.Update(currentTime);\n\n _linesToRender = _subtitleTimeline.GetVisibleLinesAndPosition(currentTime, _viewportWidth, _viewportHeight);\n }\n\n public void Render(float deltaTime)\n {\n if ( _isDisposed || _gl == null )\n {\n return;\n }\n\n _textRenderer.Begin();\n\n foreach ( var line in _linesToRender )\n {\n foreach ( var word in line.Words )\n {\n if ( word.AnimationProgress > 0 || word.IsActive((float)_currentPlaybackTime.TotalSeconds) )\n {\n _textMeasurer.Font.DrawText(\n _textRenderer,\n word.Text,\n word.Position,\n word.CurrentColor,\n scale: word.CurrentScale,\n origin: word.Size / 2.0f,\n effect: FontSystemEffect.Stroked,\n effectAmount: _config.StrokeThickness\n );\n }\n }\n }\n\n _textRenderer.End();\n }\n\n public void Resize()\n {\n _viewportWidth = _config.Width;\n _viewportHeight = _config.Height;\n\n _textMeasurer.UpdateViewport(_viewportWidth, _viewportHeight);\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n }\n\n private void SubscribeToAudioNotifier()\n {\n _audioNotifier.ChunkPlaybackStarted += OnChunkPlaybackStarted;\n _audioNotifier.ChunkPlaybackEnded += OnChunkPlaybackEnded;\n _audioNotifier.PlaybackProgress += OnPlaybackProgress;\n }\n\n private void UnsubscribeFromAudioNotifier()\n {\n _audioNotifier.ChunkPlaybackStarted -= OnChunkPlaybackStarted;\n _audioNotifier.ChunkPlaybackEnded -= OnChunkPlaybackEnded;\n _audioNotifier.PlaybackProgress -= OnPlaybackProgress;\n }\n \n private void OnChunkPlaybackStarted(object? sender, AudioChunkPlaybackStartedEvent e)\n {\n _pendingSegments.Enqueue(e.Chunk);\n\n if ( _processingTask.IsCompleted )\n {\n _processingTask = Task.Run(ProcessPendingSegmentsAsync);\n }\n }\n\n private void OnChunkPlaybackEnded(object? sender, AudioChunkPlaybackEndedEvent e) { _subtitleTimeline.RemoveSegment(e.Chunk); }\n\n private void OnPlaybackProgress(object? sender, AudioPlaybackProgressEvent e) { _currentPlaybackTime = e.CurrentPlaybackTime; }\n\n private void ProcessPendingSegmentsAsync()\n {\n while ( _pendingSegments.TryDequeue(out var audioSegment) )\n {\n try\n {\n var segmentStartTime = (float)0f;\n\n var processedSegment = _subtitleProcessor.ProcessSegment(audioSegment, segmentStartTime);\n\n _subtitleTimeline.AddSegment(processedSegment);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error processing subtitle segment: {ex.Message}\");\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Session/ConversationSession.cs", "using System.Diagnostics;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\n\nusing OpenAI.Chat;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Context;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Input;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Metrics;\nusing PersonaEngine.Lib.LLM;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nusing Stateless;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Session;\n\npublic partial class ConversationSession : IConversationSession\n{\n private static readonly ParticipantInfo ASSISTANT_PARTICIPANT = new(\"ARIA_ASSISTANT_BOT\", \"Aria\", ChatMessageRole.Assistant);\n\n public ConversationSession(ILogger logger, IChatEngine chatEngine, ITtsEngine ttsEngine, IEnumerable inputAdapters, IOutputAdapter outputAdapter, ConversationMetrics metrics, Guid sessionId, ConversationOptions options, ConversationContext context, IBargeInStrategy bargeInStrategy)\n {\n _logger = logger;\n _chatEngine = chatEngine;\n _ttsEngine = ttsEngine;\n\n _inputAdapters.AddRange(inputAdapters);\n _outputAdapter = outputAdapter;\n _metrics = metrics;\n SessionId = sessionId;\n _options = options;\n _context = context;\n _bargeInStrategy = bargeInStrategy;\n\n _inputChannel = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false });\n _inputChannelWriter = _inputChannel.Writer;\n\n _outputChannel = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false });\n _outputChannelWriter = _outputChannel.Writer;\n\n _stateMachine = new StateMachine(ConversationState.Initial);\n ConfigureStateMachine();\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _isDisposed )\n {\n return;\n }\n\n _logger.LogDebug(\"{SessionId} | Disposing session.\", SessionId);\n\n if ( !_sessionCts.IsCancellationRequested )\n {\n await _sessionCts.CancelAsync();\n }\n\n if ( _sessionLoopTask is { IsCompleted: false } )\n {\n try\n {\n await _sessionLoopTask.WaitAsync(TimeSpan.FromSeconds(5));\n }\n catch (TimeoutException)\n {\n _logger.LogWarning(\"{SessionId} | Timeout waiting for session loop task during dispose.\", SessionId);\n }\n catch (Exception ex) when (ex is not OperationCanceledException)\n {\n _logger.LogError(ex, \"{SessionId} | Error waiting for session loop task during dispose.\", SessionId);\n }\n }\n\n await CleanupSessionAsync();\n\n _currentTurnCts?.Dispose();\n _sessionCts.Dispose();\n\n _inputChannelWriter.TryComplete();\n _outputChannelWriter.TryComplete();\n\n _isDisposed = true;\n\n GC.SuppressFinalize(this);\n _logger.LogInformation(\"{SessionId} | Session disposed.\", SessionId);\n }\n\n public IConversationContext Context => _context;\n\n public Guid SessionId { get; }\n\n public async ValueTask RunAsync(CancellationToken cancellationToken)\n {\n ObjectDisposedException.ThrowIf(_isDisposed, this);\n\n if ( _sessionLoopTask is { IsCompleted: false } )\n {\n _logger.LogWarning(\"{SessionId} | RunAsync called while session is already running.\", SessionId);\n await _sessionLoopTask;\n\n return;\n }\n\n using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_sessionCts.Token, cancellationToken);\n var linkedToken = linkedCts.Token;\n\n var inputLoopTask = ProcessInputEventsAsync(linkedToken);\n var outputLoopTask = ProcessOutputEventsAsync(linkedToken);\n\n _sessionLoopTask = Task.WhenAll(inputLoopTask, outputLoopTask);\n\n try\n {\n await _stateMachine.FireAsync(ConversationTrigger.InitializeRequested);\n await _sessionLoopTask;\n\n _logger.LogInformation(\"{SessionId} | Session run completed. Final State: {State}\", SessionId, _stateMachine.State);\n }\n catch (OperationCanceledException) when (linkedToken.IsCancellationRequested)\n {\n _logger.LogInformation(\"{SessionId} | RunAsync cancelled externally or by StopAsync.\", SessionId);\n\n await EnsureStateMachineStoppedAsync();\n }\n catch (Exception ex)\n {\n _logger.LogCritical(ex, \"{SessionId} | Unhandled exception during RunAsync setup or state machine trigger.\", SessionId);\n await FireErrorAsync(ex);\n }\n finally\n {\n _logger.LogDebug(\"{SessionId} | RunAsync finished execution.\", SessionId);\n await CleanupSessionAsync();\n\n _inputChannelWriter.TryComplete();\n _outputChannelWriter.TryComplete();\n _sessionLoopTask = null;\n }\n }\n\n public async ValueTask StopAsync()\n {\n _logger.LogDebug(\"{SessionId} | StopAsync called. Current State: {State}\", SessionId, _stateMachine.State);\n\n if ( !_sessionCts.IsCancellationRequested )\n {\n await _sessionCts.CancelAsync();\n }\n }\n\n #region Event Processing Loops\n\n private async Task ProcessInputEventsAsync(CancellationToken cancellationToken)\n {\n _logger.LogDebug(\"{SessionId} | Starting input event processing loop.\", SessionId);\n\n try\n {\n await foreach ( var inputEvent in _inputChannel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false) )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n break;\n }\n\n try\n {\n if ( inputEvent is SttSegmentRecognizing && !_sttStartTime.HasValue )\n {\n _sttStartTime = inputEvent.Timestamp;\n }\n\n if ( inputEvent is SttSegmentRecognized sttRecognized && _sttStartTime.HasValue )\n {\n var sttDuration = (sttRecognized.Timestamp - _sttStartTime.Value).TotalMilliseconds;\n _metrics.RecordSttSegmentDuration(sttDuration, SessionId, sttRecognized.ParticipantId);\n _sttStartTime = null;\n }\n\n var (trigger, eventArgs) = MapInputEventToTrigger(inputEvent);\n\n if ( trigger.HasValue )\n {\n _logger.LogTrace(\"{SessionId} | Input Loop: Firing trigger {Trigger} for event {EventType}\", SessionId, trigger.Value, inputEvent.GetType().Name);\n\n await _stateMachine.FireAsync(trigger.Value, eventArgs);\n }\n else\n {\n _logger.LogWarning(\"{SessionId} | Input Loop: Received unhandled input event type: {EventType}\", SessionId, inputEvent.GetType().Name);\n }\n }\n catch (InvalidOperationException ex)\n {\n _logger.LogWarning(ex, \"{SessionId} | Input Loop: State machine transition denied in state {State}. Trigger: {Trigger}, Event: {@Event}\",\n SessionId, _stateMachine.State, MapInputEventToTrigger(inputEvent).Trigger, inputEvent);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Input Loop: Error processing input event: {EventType}. Firing ErrorOccurred trigger.\", SessionId, inputEvent.GetType().Name);\n // await FireErrorWithoutStoppingAsync(ex);\n if ( _stateMachine.State is ConversationState.Error or ConversationState.Ended )\n {\n break;\n }\n }\n }\n }\n catch (OperationCanceledException)\n {\n _logger.LogDebug(\"{SessionId} | Input event processing loop cancelled.\", SessionId);\n }\n catch (ChannelClosedException)\n {\n _logger.LogInformation(\"{SessionId} | Input channel closed, ending event processing loop.\", SessionId);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Unhandled exception in input event processing loop.\", SessionId);\n await FireErrorAsync(ex);\n }\n finally\n {\n _logger.LogInformation(\"{SessionId} | Input event processing loop finished. Final State: {State}\", SessionId, _stateMachine.State);\n _inputChannelWriter.TryComplete();\n }\n }\n\n private async Task ProcessOutputEventsAsync(CancellationToken cancellationToken)\n {\n _logger.LogDebug(\"{SessionId} | Starting output event processing loop.\", SessionId);\n\n try\n {\n await foreach ( var outputEvent in _outputChannel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false) )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n break;\n }\n\n try\n {\n switch ( outputEvent )\n {\n case LlmStreamStartEvent:\n _llmStopwatch = Stopwatch.StartNew();\n\n break;\n case LlmStreamEndEvent ev:\n if ( _llmStopwatch != null )\n {\n _llmStopwatch.Stop();\n _llmFinishReason = ev.FinishReason;\n _metrics.RecordLlmDuration(_llmStopwatch.Elapsed.TotalMilliseconds, SessionId, ev.TurnId ?? Guid.Empty, _llmFinishReason);\n _llmStopwatch = null;\n }\n\n break;\n case TtsStreamStartEvent:\n _ttsStopwatch ??= Stopwatch.StartNew();\n\n break;\n case TtsStreamEndEvent ev:\n if ( _ttsStopwatch != null )\n {\n _ttsStopwatch.Stop();\n _ttsFinishReason = ev.FinishReason;\n _metrics.RecordTtsDuration(_ttsStopwatch.Elapsed.TotalMilliseconds, SessionId, ev.TurnId ?? Guid.Empty, _ttsFinishReason);\n _ttsStopwatch = null;\n }\n\n break;\n case AudioPlaybackStartedEvent ev:\n if ( _firstAudioLatencyStopwatch != null && ev.TurnId.HasValue )\n {\n _firstAudioLatencyStopwatch.Stop();\n _currentTurnFirstAudioLatencyMs = _firstAudioLatencyStopwatch.Elapsed.TotalMilliseconds;\n _metrics.RecordFirstAudioLatency(_firstAudioLatencyStopwatch.Elapsed.TotalMilliseconds, SessionId, ev.TurnId.Value);\n _firstAudioLatencyStopwatch = null;\n }\n\n _audioPlaybackStopwatch = Stopwatch.StartNew();\n\n break;\n case AudioPlaybackEndedEvent ev:\n if ( _audioPlaybackStopwatch != null )\n {\n var apt = _audioPlaybackStopwatch;\n apt.Stop();\n _audioFinishReason = ev.FinishReason;\n _metrics.RecordAudioPlaybackDuration(apt.Elapsed.TotalMilliseconds, SessionId, ev.TurnId ?? Guid.Empty, _audioFinishReason);\n _audioPlaybackStopwatch = null;\n\n if ( _turnStopwatch != null && ev.TurnId.HasValue )\n {\n apt = _turnStopwatch;\n apt.Stop();\n\n var overallReason = _audioFinishReason;\n if ( _ttsFinishReason == CompletionReason.Error || _llmFinishReason == CompletionReason.Error )\n {\n overallReason = CompletionReason.Error;\n }\n else if ( _ttsFinishReason == CompletionReason.Cancelled || _llmFinishReason == CompletionReason.Cancelled )\n {\n overallReason = CompletionReason.Cancelled;\n }\n\n _metrics.RecordTurnDuration(apt.Elapsed.TotalMilliseconds, SessionId, ev.TurnId.Value, overallReason);\n }\n }\n\n break;\n case ErrorOutputEvent ev:\n _metrics.IncrementErrors(SessionId, ev.TurnId, ev.Exception);\n\n break;\n }\n\n var (trigger, eventArgs) = MapOutputEventToTrigger(outputEvent);\n\n if ( trigger.HasValue )\n {\n _logger.LogTrace(\"{SessionId} | Output Loop: Firing trigger {Trigger} for event {EventType}\", SessionId, trigger.Value, outputEvent.GetType().Name);\n\n await _stateMachine.FireAsync(trigger.Value, eventArgs);\n }\n }\n catch (InvalidOperationException ex)\n {\n _logger.LogWarning(ex, \"{SessionId} | Output Loop: State machine transition denied in state {State}. Trigger: {Trigger}, Event: {@Event}\",\n SessionId, _stateMachine.State, MapOutputEventToTrigger(outputEvent).Trigger, outputEvent);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Output Loop: Error processing output event: {EventType}. Firing ErrorOccurred trigger.\", SessionId, outputEvent.GetType().Name);\n if ( _stateMachine.State is ConversationState.Error or ConversationState.Ended )\n {\n break;\n }\n }\n }\n }\n catch (OperationCanceledException)\n {\n _logger.LogDebug(\"{SessionId} | Output event processing loop cancelled.\", SessionId);\n }\n catch (ChannelClosedException)\n {\n _logger.LogDebug(\"{SessionId} | Output channel closed, ending output event processing loop.\", SessionId);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Unhandled exception in output event processing loop.\", SessionId);\n await FireErrorAsync(ex);\n }\n finally\n {\n _logger.LogInformation(\"{SessionId} | Output event processing loop finished. Final State: {State}\", SessionId, _stateMachine.State);\n _inputChannelWriter.TryComplete();\n }\n }\n\n private (ConversationTrigger? Trigger, object? EventArgs) MapInputEventToTrigger(IInputEvent inputEvent)\n {\n return inputEvent switch {\n SttSegmentRecognizing ev => (ConversationTrigger.InputDetected, ev),\n SttSegmentRecognized ev => (ConversationTrigger.InputFinalized, ev),\n _ => (null, null)\n };\n }\n\n private (ConversationTrigger? Trigger, object? EventArgs) MapOutputEventToTrigger(IOutputEvent outputEvent)\n {\n return outputEvent switch {\n LlmStreamStartEvent ev => (ConversationTrigger.LlmStreamStarted, ev),\n LlmChunkEvent ev => (ConversationTrigger.LlmStreamChunkReceived, ev),\n LlmStreamEndEvent ev => (ConversationTrigger.LlmStreamEnded, ev),\n TtsStreamStartEvent ev => (ConversationTrigger.TtsStreamStarted, ev),\n TtsChunkEvent ev => (ConversationTrigger.TtsStreamChunkReceived, ev),\n TtsStreamEndEvent ev => (ConversationTrigger.TtsStreamEnded, ev),\n AudioPlaybackStartedEvent ev => (ConversationTrigger.AudioStreamStarted, ev),\n AudioPlaybackEndedEvent ev => (ConversationTrigger.AudioStreamEnded, ev),\n ErrorOutputEvent ev => (ConversationTrigger.ErrorOccurred, ev.Exception),\n _ => (null, null)\n };\n }\n\n #endregion\n\n #region Fields\n\n private readonly IBargeInStrategy _bargeInStrategy;\n\n private Task? _llmTask;\n\n private Task? _ttsTask;\n\n private Task? _audioTask;\n\n private readonly ILogger _logger;\n\n private readonly ConversationOptions _options;\n\n private readonly IChatEngine _chatEngine;\n\n private readonly ITtsEngine _ttsEngine;\n\n private readonly List _inputAdapters = new();\n\n private readonly IOutputAdapter _outputAdapter;\n\n private readonly CancellationTokenSource _sessionCts = new();\n\n private CancellationTokenSource? _currentTurnCts;\n\n private Task? _sessionLoopTask;\n\n private Guid? _currentTurnId;\n\n private readonly Channel _inputChannel;\n\n private readonly ChannelWriter _inputChannelWriter;\n\n private readonly Channel _outputChannel;\n\n private readonly ChannelWriter _outputChannelWriter;\n\n private Channel? _currentLlmChannel;\n\n private Channel? _currentTtsChannel;\n\n private bool _isDisposed = false;\n\n private readonly ConversationContext _context;\n\n private CompletionReason _llmFinishReason = CompletionReason.Completed;\n\n private CompletionReason _ttsFinishReason = CompletionReason.Completed;\n\n private CompletionReason _audioFinishReason = CompletionReason.Completed;\n\n private Stopwatch? _turnStopwatch;\n\n private Stopwatch? _llmStopwatch;\n\n private Stopwatch? _ttsStopwatch;\n\n private Stopwatch? _audioPlaybackStopwatch;\n\n private DateTimeOffset? _sttStartTime;\n\n private readonly ConversationMetrics _metrics;\n\n private Stopwatch? _firstAudioLatencyStopwatch;\n\n private double? _currentTurnFirstAudioLatencyMs;\n\n private Stopwatch? _firstLlmTokenLatencyStopwatch;\n\n private double? _currentTurnFirstLlmTokenLatencyMs;\n\n private Stopwatch? _firstTtsChunkLatencyStopwatch;\n\n private double? _currentTurnFirstTtsChunkLatencyMs;\n\n #endregion\n\n # region State Actions\n\n private async Task InitializeSessionAsync()\n {\n _logger.LogDebug(\"{SessionId} | Action: InitializeSessionAsync\", SessionId);\n\n try\n {\n _context.TryAddParticipant(ASSISTANT_PARTICIPANT);\n\n var initInputTasks = _inputAdapters.Select(async adapter =>\n {\n await adapter.InitializeAsync(SessionId, _inputChannelWriter, _sessionCts.Token);\n await adapter.StartAsync(_sessionCts.Token);\n _context.TryAddParticipant(adapter.Participant);\n\n _logger.LogDebug(\"{SessionId} | Input Adapter {AdapterId} initialized and started.\", SessionId, adapter.AdapterId);\n }).ToList();\n\n var initOutputTasks = Task.Run(async () =>\n {\n await _outputAdapter.InitializeAsync(SessionId, _sessionCts.Token);\n await _outputAdapter.StartAsync(_sessionCts.Token);\n _logger.LogDebug(\"{SessionId} | Output Adapter {AdapterId} initialized and started.\", SessionId, _outputAdapter.AdapterId);\n });\n\n await Task.WhenAll(initInputTasks.Concat([initOutputTasks]));\n\n await _stateMachine.FireAsync(ConversationTrigger.InitializeComplete);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error during InitializeSessionAsync.\", SessionId);\n await _stateMachine.FireAsync(ConversationTrigger.ErrorOccurred, ex);\n }\n }\n\n private async Task PrepareLlmRequestAsync(IInputEvent inputEvent)\n {\n if ( inputEvent is not SttSegmentRecognized finalizedEvent )\n {\n _logger.LogWarning(\"{SessionId} | PrepareLlmRequestAsync received unexpected event type: {EventType}\", SessionId, inputEvent.GetType().Name);\n await FireErrorAsync(new ArgumentException(\"Invalid event type for InputFinalized trigger.\", nameof(inputEvent)), false);\n\n return;\n }\n\n _logger.LogDebug(\"{SessionId} | Action: PrepareLlmRequestAsync for input: \\\"{InputText}\\\"\", SessionId, finalizedEvent.FinalTranscript);\n\n // In-case race condition (channel events not consumed fast enough)\n await CancelCurrentTurnProcessingAsync();\n\n _currentTurnCts = CancellationTokenSource.CreateLinkedTokenSource(_sessionCts.Token);\n _currentTurnId = Guid.NewGuid();\n\n _turnStopwatch = Stopwatch.StartNew();\n _firstAudioLatencyStopwatch = Stopwatch.StartNew(); // For first audio playback\n _firstLlmTokenLatencyStopwatch = Stopwatch.StartNew(); // For first LLM token\n _firstTtsChunkLatencyStopwatch = Stopwatch.StartNew(); // For first TTS chunk (if applicable)\n\n _metrics.IncrementTurnsStarted(SessionId);\n\n _llmFinishReason = CompletionReason.Completed;\n _ttsFinishReason = CompletionReason.Completed;\n _audioFinishReason = CompletionReason.Completed;\n\n try\n {\n _context.StartTurn(_currentTurnId.Value, [finalizedEvent.ParticipantId, ASSISTANT_PARTICIPANT.Id]);\n _context.AppendToTurn(finalizedEvent.ParticipantId, finalizedEvent.FinalTranscript);\n\n var userName = _context.Participants.TryGetValue(finalizedEvent.ParticipantId, out var pInfo) ? pInfo.Name : finalizedEvent.ParticipantId;\n _logger.LogInformation(\"{SessionId} | {TurnId} | 📝 | [{Speaker}]{Text}\", SessionId, _currentTurnId, userName, _context.GetPendingMessageText(finalizedEvent.ParticipantId));\n\n _context.CompleteTurnPart(finalizedEvent.ParticipantId);\n\n await _stateMachine.FireAsync(ConversationTrigger.LlmRequestSent);\n\n if ( _outputAdapter is IAudioOutputAdapter )\n {\n await _stateMachine.FireAsync(ConversationTrigger.TtsRequestSent);\n }\n else\n {\n _firstTtsChunkLatencyStopwatch?.Stop();\n _firstTtsChunkLatencyStopwatch = null;\n _currentTurnFirstTtsChunkLatencyMs = null;\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error during PrepareLlmRequestAsync for Turn {TurnId}.\", SessionId, _currentTurnId ?? Guid.Empty);\n await FireErrorAsync(ex);\n }\n }\n\n private async Task CancelCurrentTurnProcessingAsync()\n {\n if ( _currentTurnCts == null )\n {\n _logger.LogDebug(\"{SessionId} | No active turn processing to cancel.\", SessionId);\n\n return;\n }\n\n var turnIdBeingCancelled = _currentTurnId;\n _logger.LogDebug(\"{SessionId} | Requesting cancellation for Turn {TurnId}'s processing pipeline.\", SessionId, turnIdBeingCancelled);\n\n if ( _currentTurnCts is { IsCancellationRequested: false } )\n {\n try\n {\n await _currentTurnCts.CancelAsync();\n _logger.LogTrace(\"{SessionId} | Turn {TurnId} CancellationToken cancelled.\", SessionId, turnIdBeingCancelled);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error cancelling CancellationTokenSource for Turn {TurnId}.\", SessionId, turnIdBeingCancelled);\n }\n }\n\n if ( turnIdBeingCancelled.HasValue )\n {\n await WaitForTaskCancellationAsync(_llmTask, \"LLM response generation\", turnIdBeingCancelled.Value);\n await WaitForTaskCancellationAsync(_ttsTask, \"TTS generation\", turnIdBeingCancelled.Value);\n await WaitForTaskCancellationAsync(_audioTask, \"Audio processing\", turnIdBeingCancelled.Value);\n }\n\n _currentTurnCts?.Dispose();\n _currentTurnCts = null;\n _currentTurnId = null;\n _llmTask = null;\n _ttsTask = null;\n _audioTask = null;\n\n _context.AbortTurn();\n\n _currentLlmChannel?.Writer.TryComplete(new OperationCanceledException());\n _currentTtsChannel?.Writer.TryComplete(new OperationCanceledException());\n\n _turnStopwatch?.Stop();\n _llmStopwatch?.Stop();\n _ttsStopwatch?.Stop();\n _audioPlaybackStopwatch?.Stop();\n _firstAudioLatencyStopwatch?.Stop();\n _firstLlmTokenLatencyStopwatch?.Stop();\n _firstTtsChunkLatencyStopwatch?.Stop();\n\n _turnStopwatch = null;\n _llmStopwatch = null;\n _ttsStopwatch = null;\n _audioPlaybackStopwatch = null;\n _firstAudioLatencyStopwatch = null;\n _firstLlmTokenLatencyStopwatch = null;\n _firstTtsChunkLatencyStopwatch = null;\n _currentTurnFirstAudioLatencyMs = null;\n _sttStartTime = null;\n\n _currentLlmChannel = null;\n _currentTtsChannel = null;\n }\n\n private async Task WaitForTaskCancellationAsync(Task? task, string taskName, Guid turnIdBeingCancelled)\n {\n if ( task is { IsCompleted: false } )\n {\n _logger.LogTrace(\"{SessionId} | Waiting briefly for {TaskName} task cancellation acknowledgment (Turn {TurnId}).\", SessionId, taskName, turnIdBeingCancelled);\n try\n {\n await task;\n }\n catch (OperationCanceledException)\n {\n /* Ignored */\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Exception while waiting for {TaskName} task cancellation (Turn {TurnId}). Task Status: {Status}\", SessionId, taskName, turnIdBeingCancelled, task.Status);\n }\n }\n else\n {\n _logger.LogTrace(\"{SessionId} | {TaskName} task was null or already completed (Turn {TurnId}). No wait needed.\", SessionId, taskName, turnIdBeingCancelled);\n }\n }\n\n private void HandleInterruption()\n {\n var interruptedTurnId = _currentTurnId;\n\n if ( !interruptedTurnId.HasValue )\n {\n _logger.LogWarning(\"{SessionId} | Interruption handled but no active turn ID found.\", SessionId);\n\n return;\n }\n\n _metrics.IncrementTurnsInterrupted(SessionId, interruptedTurnId.Value);\n\n CommitChanges(false);\n }\n\n private async Task HandleInterruptionCancelAndRefireAsync(IInputEvent inputEvent, StateMachine.Transition transition)\n {\n HandleInterruption();\n\n if ( transition.Source is ConversationState.Speaking )\n {\n _context.CompleteTurnPart(ASSISTANT_PARTICIPANT.Id, true);\n }\n\n switch ( transition.Trigger )\n {\n case ConversationTrigger.InputDetected:\n await _stateMachine.FireAsync(_inputDetectedTrigger, inputEvent);\n\n return;\n case ConversationTrigger.InputFinalized:\n await _stateMachine.FireAsync(_inputFinalizedTrigger, inputEvent);\n\n return;\n default:\n throw new ArgumentException($\"{transition} failed. The state machine is in an invalid state.\", nameof(transition));\n }\n }\n\n private async Task PauseActivitiesAsync()\n {\n _logger.LogInformation(\"{SessionId} | Action: PauseActivitiesAsync - Stopping Adapters\", SessionId);\n\n // TODO: Need to think about this\n foreach ( var adapter in _inputAdapters )\n {\n try\n {\n await adapter.StopAsync(_sessionCts.Token);\n } // Use session token? Or None?\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error stopping input adapter {AdapterId} during pause.\", SessionId, adapter.AdapterId);\n }\n }\n }\n\n private async Task ResumeActivitiesAsync()\n {\n _logger.LogInformation(\"{SessionId} | Action: ResumeActivitiesAsync - Starting Adapters\", SessionId);\n\n // TODO: Need to think about this\n foreach ( var adapter in _inputAdapters )\n {\n try\n {\n await adapter.StartAsync(_sessionCts.Token);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error starting input adapter {AdapterId} during resume.\", SessionId, adapter.AdapterId);\n }\n }\n }\n\n private async Task HandleErrorAsync(Exception error)\n {\n _logger.LogError(error, \"{SessionId} | Action: HandleErrorAsync - An error occurred in the state machine.\", SessionId);\n _metrics.IncrementErrors(SessionId, _currentTurnId, error);\n await _stateMachine.FireAsync(ConversationTrigger.StopRequested);\n }\n\n private async Task CleanupSessionAsync()\n {\n await CancelCurrentTurnProcessingAsync();\n\n var inputCleanupTasks = _inputAdapters.Select(async adapter =>\n {\n try\n {\n await adapter.StopAsync(CancellationToken.None);\n await adapter.DisposeAsync();\n _logger.LogDebug(\"{SessionId} | Input Adapter {AdapterId} stopped and disposed.\", SessionId, adapter.AdapterId);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error cleaning up input adapter {AdapterId}.\", SessionId, adapter.AdapterId);\n }\n }).ToList();\n\n var outputCleanupTask = Task.Run(async () =>\n {\n try\n {\n await _outputAdapter.StopAsync(CancellationToken.None);\n await _outputAdapter.DisposeAsync();\n _logger.LogDebug(\"{SessionId} | Output Adapter {AdapterId} stopped and disposed.\", SessionId, _outputAdapter.AdapterId);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Error cleaning up output adapter {AdapterId}.\", SessionId, _outputAdapter.AdapterId);\n }\n });\n\n await Task.WhenAll(inputCleanupTasks.Append(outputCleanupTask));\n _inputAdapters.Clear();\n _logger.LogDebug(\"{SessionId} | Cleanup finished.\", SessionId);\n }\n\n private void HandleLlmStreamRequested()\n {\n var turnId = _currentTurnId;\n var turnCts = _currentTurnCts;\n var outputWriter = _outputChannelWriter;\n\n if ( !turnId.HasValue || turnCts is null )\n {\n _logger.LogError(\"{SessionId} | HandleLlmStreamRequested called in invalid state (TurnId: {TurnId}, Cts: {Cts}).\",\n SessionId, turnId, turnCts != null);\n\n _ = FireErrorAsync(new InvalidOperationException(\"Cannot start LLM stream in invalid state.\"), false);\n\n return;\n }\n\n _currentLlmChannel = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false });\n\n _llmTask = _chatEngine.GetStreamingChatResponseAsync(_context, outputWriter, turnId.Value, SessionId, cancellationToken: turnCts.Token);\n }\n\n private void HandleTtsStreamRequest()\n {\n var turnId = _currentTurnId;\n var turnCts = _currentTurnCts;\n var outputChannelWriter = _outputChannelWriter;\n var outputChannelReader = _currentLlmChannel;\n\n if ( !turnId.HasValue || turnCts is null || outputChannelReader is null )\n {\n _logger.LogWarning(\"{SessionId} | HandleTtsStreamRequest called without a valid TurnId.\", SessionId);\n\n return;\n }\n\n _currentTtsChannel = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false });\n\n _ttsTask = _ttsEngine.SynthesizeStreamingAsync(outputChannelReader, outputChannelWriter, turnId.Value, SessionId, cancellationToken: turnCts.Token);\n\n if ( _outputAdapter is IAudioOutputAdapter audioOutput )\n {\n _audioTask = audioOutput.SendAsync(_currentTtsChannel, outputChannelWriter, turnId.Value, turnCts.Token);\n }\n }\n\n private async Task HandleLlmStreamChunkReceived(IOutputEvent outputEvent, StateMachine.Transition _)\n {\n if ( outputEvent is not LlmChunkEvent chunkEvent )\n {\n _logger.LogWarning(\"{SessionId} | HandleLlmStreamChunkReceived received unexpected event type: {EventType}\", SessionId, outputEvent.GetType().Name);\n await _stateMachine.FireAsync(ConversationTrigger.ErrorOccurred, new ArgumentException(\"Invalid event type for LlmStreamChunkReceived trigger.\", nameof(outputEvent)));\n\n return;\n }\n\n var turnId = _currentTurnId;\n var turnCts = _currentTurnCts;\n var outputWriter = _currentLlmChannel?.Writer;\n\n if ( !turnId.HasValue || turnCts is null || outputWriter is null )\n {\n _logger.LogWarning(\"{SessionId} | HandleLlmStreamChunkReceived called without a valid TurnId.\", SessionId);\n\n return;\n }\n\n if ( _firstLlmTokenLatencyStopwatch != null )\n {\n _firstLlmTokenLatencyStopwatch.Stop();\n _currentTurnFirstLlmTokenLatencyMs = _firstLlmTokenLatencyStopwatch.Elapsed.TotalMilliseconds;\n _logger.LogDebug(\"{SessionId} | {TurnId} | ⏱️ | First LLM [{LatencyMs:N0} ms]\", SessionId, turnId.Value, _currentTurnFirstLlmTokenLatencyMs.Value);\n _firstLlmTokenLatencyStopwatch = null;\n }\n\n _context.AppendToTurn(ASSISTANT_PARTICIPANT.Id, chunkEvent.Chunk);\n\n await outputWriter.WriteAsync(chunkEvent, turnCts.Token);\n }\n\n private async Task HandleTtsStreamChunkReceived(IOutputEvent outputEvent, StateMachine.Transition _)\n {\n if ( outputEvent is not TtsChunkEvent chunkEvent )\n {\n _logger.LogWarning(\"{SessionId} | HandleTtsStreamChunkReceived received unexpected event type: {EventType}\", SessionId, outputEvent.GetType().Name);\n await _stateMachine.FireAsync(ConversationTrigger.ErrorOccurred, new ArgumentException(\"Invalid event type for HandleTtsStreamChunkReceived trigger.\", nameof(outputEvent)));\n\n return;\n }\n\n var turnId = _currentTurnId;\n var turnCts = _currentTurnCts;\n var outputWriter = _currentTtsChannel?.Writer;\n\n if ( !turnId.HasValue || turnCts is null || outputWriter is null )\n {\n _logger.LogWarning(\"{SessionId} | HandleTtsStreamChunkReceived called without a valid TurnId.\", SessionId);\n\n return;\n }\n\n if ( _firstTtsChunkLatencyStopwatch != null )\n {\n _firstTtsChunkLatencyStopwatch.Stop();\n _currentTurnFirstTtsChunkLatencyMs = _firstTtsChunkLatencyStopwatch.Elapsed.TotalMilliseconds;\n _logger.LogDebug(\"{SessionId} | {TurnId} | ⏱️ | First TTS [{LatencyMs:N0} ms]\", SessionId, turnId.Value, _currentTurnFirstTtsChunkLatencyMs.Value);\n _firstTtsChunkLatencyStopwatch = null;\n }\n\n await outputWriter.WriteAsync(chunkEvent, turnCts.Token);\n }\n\n private void HandleLlmStreamEnded()\n {\n var outputWriter = _currentLlmChannel?.Writer;\n\n if ( outputWriter is null )\n {\n _logger.LogWarning(\"{SessionId} | HandleLlmStreamEnded called without a valid LLM channel.\", SessionId);\n\n return;\n }\n\n outputWriter.TryComplete();\n\n if ( _outputAdapter is not IAudioOutputAdapter )\n {\n _context.CompleteTurnPart(ASSISTANT_PARTICIPANT.Id);\n }\n }\n\n private void HandleTtsStreamEnded()\n {\n var outputWriter = _currentTtsChannel?.Writer;\n\n if ( outputWriter is null )\n {\n _logger.LogWarning(\"{SessionId} | HandleTtsStreamEnded called without a valid TTS channel.\", SessionId);\n\n return;\n }\n\n outputWriter.TryComplete();\n }\n\n private async Task FireErrorAsync(Exception ex, bool stopSession = true)\n {\n try\n {\n if ( _stateMachine.State != ConversationState.Error && _stateMachine.State != ConversationState.Ended )\n {\n await _stateMachine.FireAsync(ConversationTrigger.ErrorOccurred, ex);\n }\n\n if ( stopSession && _stateMachine.State != ConversationState.Ended )\n {\n await StopAsync();\n }\n }\n catch (Exception fireEx)\n {\n _logger.LogError(fireEx, \"{SessionId} | Failed to fire ErrorOccurred/StopRequested after initial exception.\", SessionId);\n if ( !_sessionCts.IsCancellationRequested )\n {\n await _sessionCts.CancelAsync();\n }\n }\n }\n\n private async Task EnsureStateMachineStoppedAsync()\n {\n if ( _stateMachine.State != ConversationState.Ended && _stateMachine.State != ConversationState.Error )\n {\n _logger.LogWarning(\"{SessionId} | Session loop ended unexpectedly in state {State}. Forcing StopRequested.\", SessionId, _stateMachine.State);\n try\n {\n if ( !_sessionCts.IsCancellationRequested )\n {\n await _sessionCts.CancelAsync();\n }\n\n await _stateMachine.FireAsync(ConversationTrigger.StopRequested);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"{SessionId} | Exception while trying to force StopRequested.\", SessionId);\n }\n }\n }\n\n private void CommitSpokenText() { _context.CompleteTurnPart(ASSISTANT_PARTICIPANT.Id); }\n\n private void HandleIdle()\n {\n var completedTurnId = _currentTurnId;\n var turnDuration = _turnStopwatch?.Elapsed.TotalMilliseconds;\n\n if ( completedTurnId.HasValue && turnDuration.HasValue )\n {\n var llmTime = _currentTurnFirstLlmTokenLatencyMs ?? 0;\n var ttsTime = _currentTurnFirstTtsChunkLatencyMs ?? 0;\n var audioTime = _currentTurnFirstAudioLatencyMs ?? 0;\n\n _logger.LogInformation(\n \"{SessionId} | {TurnId} | ⏱️ | LLM @{LlmMs:N0}ms ⇢ TTS @{TtsMs:N0}ms ⇢ AUDIO @{AudioMs:N0}ms | TOTAL @{TotalMs:N0}ms\",\n SessionId,\n completedTurnId.Value,\n llmTime,\n ttsTime - llmTime,\n audioTime - ttsTime,\n audioTime\n );\n }\n\n CommitChanges(false);\n\n _currentTurnId = null;\n _turnStopwatch = null;\n _llmStopwatch = null;\n _ttsStopwatch = null;\n _audioPlaybackStopwatch = null;\n _firstAudioLatencyStopwatch = null;\n _firstLlmTokenLatencyStopwatch = null;\n _firstTtsChunkLatencyStopwatch = null;\n\n _currentTurnFirstAudioLatencyMs = null;\n _currentTurnFirstLlmTokenLatencyMs = null;\n _currentTurnFirstTtsChunkLatencyMs = null;\n _sttStartTime = null;\n\n _currentLlmChannel?.Writer.TryComplete();\n _currentTtsChannel?.Writer.TryComplete();\n _currentLlmChannel = null;\n _currentTtsChannel = null;\n }\n\n private void CommitChanges(bool interrupted)\n {\n foreach ( var inputAdapter in _inputAdapters )\n {\n _context.CompleteTurnPart(inputAdapter.Participant.Id, interrupted);\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/KokoroVoiceProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Voice provider implementation to manage voice embeddings\n/// \npublic class KokoroVoiceProvider : IKokoroVoiceProvider\n{\n private readonly ITtsCache _cache;\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly ConcurrentDictionary _voicePaths = new();\n\n private bool _disposed;\n\n public KokoroVoiceProvider(\n IModelProvider ittsModelProvider,\n ITtsCache cache,\n ILogger logger)\n {\n _modelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _cache = cache ?? throw new ArgumentNullException(nameof(cache));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n public async Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(voiceId) )\n {\n throw new ArgumentException(\"Voice ID cannot be null or empty\", nameof(voiceId));\n }\n\n try\n {\n // Use cache to avoid repeated loading\n return await _cache.GetOrAddAsync($\"voice_{voiceId}\", async ct =>\n {\n _logger.LogDebug(\"Loading voice data for {VoiceId}\", voiceId);\n\n // Get voice directory\n var voiceDirPath = await GetVoicePathAsync(voiceId, ct);\n\n // Load binary data\n var bytes = await File.ReadAllBytesAsync(voiceDirPath, ct);\n\n // Convert to float array\n var embedding = new float[bytes.Length / sizeof(float)];\n Buffer.BlockCopy(bytes, 0, embedding, 0, bytes.Length);\n\n _logger.LogInformation(\"Loaded voice {VoiceId} with {EmbeddingSize} embedding dimensions\",\n voiceId, embedding.Length);\n\n return new VoiceData(voiceId, embedding);\n }, cancellationToken);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading voice {VoiceId}\", voiceId);\n\n throw;\n }\n }\n\n /// \n public async Task> GetAvailableVoicesAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n // Get voice directory\n var model = await _modelProvider.GetModelAsync(ModelType.KokoroVoices, cancellationToken);\n var voicesDir = model.Path;\n\n if ( !Directory.Exists(voicesDir) )\n {\n _logger.LogWarning(\"Voices directory not found: {Path}\", voicesDir);\n\n return Array.Empty();\n }\n\n // Get all .bin files\n var voiceFiles = Directory.GetFiles(voicesDir, \"*.bin\");\n\n // Extract voice IDs from filenames\n var voiceIds = new List(voiceFiles.Length);\n\n foreach ( var file in voiceFiles )\n {\n var voiceId = Path.GetFileNameWithoutExtension(file);\n voiceIds.Add(voiceId);\n\n // Cache the path for faster lookup\n _voicePaths[voiceId] = file;\n }\n\n _logger.LogInformation(\"Found {Count} available Kokoro voices\", voiceIds.Count);\n\n return voiceIds;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available voices\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voicePaths.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Gets the file path for a voice\n /// \n private async Task GetVoicePathAsync(string voiceId, CancellationToken cancellationToken)\n {\n // Check if path is cached\n if ( _voicePaths.TryGetValue(voiceId, out var cachedPath) )\n {\n return cachedPath;\n }\n\n // Get base directory\n var model = await _modelProvider.GetModelAsync(ModelType.KokoroVoices, cancellationToken);\n var voicesDir = model.Path;\n\n // Build path\n var voicePath = Path.Combine(voicesDir, $\"{voiceId}.bin\");\n\n // Check if file exists\n if ( !File.Exists(voicePath) )\n {\n _logger.LogWarning(\"Voice file not found: {Path}\", voicePath);\n\n throw new FileNotFoundException($\"Voice file not found for {voiceId}\", voicePath);\n }\n\n // Cache the path\n _voicePaths[voiceId] = voicePath;\n\n return voicePath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/TimedPlaybackController.cs", "using System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Implementation of IPlaybackController that works with large audio segments.\n/// \npublic class TimedPlaybackController : IPlaybackController\n{\n private readonly int _initialBufferMs;\n\n private readonly double _latencyThresholdMs;\n\n private readonly ILogger _logger;\n\n private readonly Stopwatch _playbackTimer = new();\n\n // For time updates\n private readonly object _timeLock = new();\n\n private readonly int _timeUpdateIntervalMs;\n\n private readonly Timer _timeUpdateTimer;\n\n // Latency tracking\n\n private int _currentSampleRate;\n\n private double _lastReportedLatencyMs;\n\n private long _startTimeMs; // When playback actually started (system time)\n\n /// \n /// Initializes a new instance of the TimedPlaybackController class.\n /// \n /// Initial buffer size in milliseconds.\n /// Threshold for significant latency changes in milliseconds.\n /// Interval in milliseconds for time updates.\n /// Logger instance.\n public TimedPlaybackController(\n int initialBufferMs = 20,\n double latencyThresholdMs = 20.0,\n int timeUpdateIntervalMs = 20,\n ILogger? logger = null)\n {\n _initialBufferMs = initialBufferMs;\n _latencyThresholdMs = latencyThresholdMs;\n _timeUpdateIntervalMs = timeUpdateIntervalMs;\n _logger = logger ?? NullLogger.Instance;\n\n // Start a timer to update the playback time periodically\n _timeUpdateTimer = new Timer(UpdateTime, null, Timeout.Infinite, Timeout.Infinite);\n }\n\n /// \n public float CurrentTime { get; private set; }\n\n /// \n public long TotalSamplesPlayed { get; private set; }\n\n /// \n public double CurrentLatencyMs { get; private set; }\n\n /// \n public bool HasLatencyInformation { get; private set; }\n\n /// \n /// Event that fires when the playback time changes substantially.\n /// \n public event EventHandler TimeChanged\n {\n add\n {\n lock (_timeLock)\n {\n TimeChangedInternal += value;\n }\n }\n remove\n {\n lock (_timeLock)\n {\n TimeChangedInternal -= value;\n }\n }\n }\n\n /// \n public event EventHandler? LatencyChanged;\n\n /// \n public void Reset()\n {\n _playbackTimer.Reset();\n TotalSamplesPlayed = 0;\n CurrentTime = 0;\n _startTimeMs = 0;\n\n // Stop the time update timer\n _timeUpdateTimer.Change(Timeout.Infinite, Timeout.Infinite);\n }\n\n /// \n public void UpdateLatency(double latencyMs)\n {\n var oldLatency = CurrentLatencyMs;\n CurrentLatencyMs = latencyMs;\n HasLatencyInformation = true;\n\n // Only notify if the change is significant\n if ( Math.Abs(latencyMs - _lastReportedLatencyMs) >= _latencyThresholdMs )\n {\n _logger.LogInformation(\"Playback latency updated: {OldLatency:F1}ms -> {NewLatency:F1}ms\",\n oldLatency, latencyMs);\n\n _lastReportedLatencyMs = latencyMs;\n LatencyChanged?.Invoke(this, latencyMs);\n }\n }\n\n /// \n public Task SchedulePlaybackAsync(int samplesPerChannel, int sampleRate, CancellationToken cancellationToken)\n {\n // Store the sample rate for time calculations\n _currentSampleRate = sampleRate;\n\n // Update total samples\n TotalSamplesPlayed += samplesPerChannel;\n\n // Start the playback timer if this is the first call\n if ( !_playbackTimer.IsRunning )\n {\n _logger.LogDebug(\"Starting playback timer\");\n\n // Account for initial buffering\n var initialBufferMs = HasLatencyInformation\n ? Math.Max(50, _initialBufferMs + CurrentLatencyMs)\n : _initialBufferMs;\n\n // Record when playback will actually start (now + buffer)\n _startTimeMs = Environment.TickCount64 + (long)initialBufferMs;\n\n // Start the stopwatch for measuring elapsed time\n _playbackTimer.Start();\n\n // Start the timer to update current time periodically\n _timeUpdateTimer.Change(_timeUpdateIntervalMs, _timeUpdateIntervalMs);\n }\n\n // Always send the data - the transport will handle chunking\n return Task.FromResult(true);\n }\n\n /// \n /// Disposes resources used by the controller.\n /// \n public void Dispose() { _timeUpdateTimer.Dispose(); }\n\n private event EventHandler? TimeChangedInternal;\n\n // Private methods\n\n private void UpdateTime(object? state)\n {\n if ( !_playbackTimer.IsRunning || _currentSampleRate <= 0 )\n {\n return;\n }\n\n // Calculate current system time\n var currentTimeMs = Environment.TickCount64;\n\n // Calculate how much time has passed since playback started\n var elapsedSinceStartMs = currentTimeMs > _startTimeMs\n ? currentTimeMs - _startTimeMs\n : 0;\n\n // Apply latency adjustment if available\n var adjustedElapsedMs = HasLatencyInformation\n ? elapsedSinceStartMs - CurrentLatencyMs\n : elapsedSinceStartMs;\n\n // Don't allow negative time\n adjustedElapsedMs = Math.Max(0, adjustedElapsedMs);\n\n // Convert to seconds\n var newPlaybackTime = (float)(adjustedElapsedMs / 1000.0);\n\n // Only update and notify if the time changed significantly\n if ( Math.Abs(newPlaybackTime - CurrentTime) >= 0.01f ) // 10ms threshold\n {\n CurrentTime = newPlaybackTime;\n\n EventHandler? handler;\n lock (_timeLock)\n {\n handler = TimeChangedInternal;\n }\n\n handler?.Invoke(this, newPlaybackTime);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Audio/BlacklistAudioFilter.cs", "using System.Globalization;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nusing PersonaEngine.Lib.TTS.Profanity;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.Audio;\n\n/// \n/// Audio filter that censors profane content by replacing it with a beep tone.\n/// \npublic class BlacklistAudioFilter : IAudioFilter\n{\n // Configuration constants\n private const float DEFAULT_BEEP_FREQUENCY = 880; // Changed from 400Hz to 1000Hz (standard censor beep)\n\n private const float DEFAULT_BEEP_VOLUME = 0.35f; // Slightly increased for better audibility\n\n private const int REFERENCE_SAMPLE_RATE = 24000;\n\n // Common suffixes to check when matching profanity\n private static readonly string[] COMMON_SUFFIXES = { \"s\", \"es\", \"ed\", \"ing\", \"er\", \"ers\" };\n\n // Pre-calculated beep tone samples\n private readonly float[] _beepCycle;\n\n private readonly float _beepFrequency;\n\n private readonly float _beepVolume;\n\n private readonly ProfanityDetector _profanityDetector;\n\n private readonly HashSet _profanityDictionary;\n\n // Cache for previously checked words to improve performance\n private readonly Dictionary _wordCheckCache = new(StringComparer.OrdinalIgnoreCase);\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The profanity detector service.\n public BlacklistAudioFilter(ProfanityDetector profanityDetector)\n : this(profanityDetector, DEFAULT_BEEP_FREQUENCY) { }\n\n /// \n /// Initializes a new instance of the class with custom audio parameters.\n /// \n /// The profanity detector service.\n /// The frequency of the beep tone in Hz.\n /// The volume of the beep tone (0.0-1.0).\n /// Thrown when profanityDetector is null.\n public BlacklistAudioFilter(\n ProfanityDetector profanityDetector,\n float beepFrequency = DEFAULT_BEEP_FREQUENCY,\n float beepVolume = DEFAULT_BEEP_VOLUME)\n {\n _profanityDetector = profanityDetector ?? throw new ArgumentNullException(nameof(profanityDetector));\n _beepFrequency = beepFrequency;\n _beepVolume = Math.Clamp(beepVolume, 0.0f, 1.0f);\n\n // Load profanity dictionary\n var profanityListPath = ModelUtils.GetModelPath(ModelType.BadWords);\n _profanityDictionary = LoadProfanityDictionary(profanityListPath);\n\n // Pre-calculate one cycle of the beep tone for efficient reuse\n // Using a square wave instead of sine wave for a more traditional censorship beep\n var samplesPerCycle = (int)(REFERENCE_SAMPLE_RATE / _beepFrequency);\n _beepCycle = new float[samplesPerCycle];\n\n for ( var i = 0; i < samplesPerCycle; i++ )\n {\n // Generate square wave (values are either +volume or -volume)\n _beepCycle[i] = i < samplesPerCycle / 2 ? _beepVolume : -_beepVolume;\n }\n }\n\n /// \n /// Processes an audio segment to censor profane content with beep tones.\n /// \n /// The audio segment to process.\n public void Process(AudioSegment segment)\n {\n if ( segment == null || segment.AudioData.IsEmpty || segment.Tokens == null || segment.Tokens.Count == 0 )\n {\n return; // Early exit for invalid segments\n }\n\n var tokens = segment.Tokens;\n var audioSpan = segment.AudioData.Span;\n var sampleRate = segment.SampleRate;\n\n // First step: Identify and mark profane tokens\n MarkProfaneTokens(tokens);\n\n // Second step: Apply beep sound to marked tokens\n foreach ( var (token, index) in tokens.Select((t, i) => (t, i)) )\n {\n if ( token is not { Text: \"[REDACTED]\" } )\n {\n continue; // Skip null or non-redacted tokens\n }\n\n // Determine valid time boundaries for the audio replacement\n var (startTime, endTime) = DetermineTimeBoundaries(token, tokens, index);\n\n // Convert timestamps to sample indices\n var startIndex = (int)(startTime * sampleRate);\n var endIndex = (int)(endTime * sampleRate);\n\n // Validate indices to prevent out-of-bounds access\n startIndex = Math.Max(0, startIndex);\n endIndex = Math.Min(audioSpan.Length, endIndex);\n\n if ( startIndex >= endIndex || startIndex >= audioSpan.Length )\n {\n continue; // Invalid range\n }\n\n // Apply beep tone to the segment\n ApplyBeepTone(audioSpan, startIndex, endIndex, sampleRate);\n }\n }\n\n public int Priority => -100;\n\n /// \n /// Marks tokens containing profanity based on the overall severity level.\n /// \n /// The list of tokens to process.\n /// The tolerance level for profanity.\n private void MarkProfaneTokens(IReadOnlyList tokens, ProfanitySeverity tolerance = ProfanitySeverity.Clean)\n {\n if ( tokens.Count == 0 )\n {\n return;\n }\n\n // Build the full sentence from tokens for overall evaluation\n var sentence = BuildSentenceFromTokens(tokens);\n\n // Evaluate overall profanity severity\n var overallSeverity = _profanityDetector.EvaluateProfanity(sentence);\n\n // If the overall severity is within tolerance, no need to censor\n if ( overallSeverity <= tolerance )\n {\n return;\n }\n\n // Mark individual profane tokens\n foreach ( var token in tokens )\n {\n if ( token == null || string.IsNullOrWhiteSpace(token.Text) )\n {\n continue;\n }\n\n // Split the token into words to check each individually\n var words = SplitIntoWords(token.Text);\n\n foreach ( var word in words )\n {\n if ( IsProfaneWord(word) )\n {\n token.Text = \"[REDACTED]\";\n\n break; // Break once we find any profanity in the token\n }\n }\n }\n }\n\n /// \n /// Splits text into individual words, preserving only alphanumeric characters.\n /// \n private static IEnumerable SplitIntoWords(string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n yield break;\n }\n\n // Use regex to split text into words (sequences of letters)\n var matches = Regex.Matches(text, @\"\\b[a-zA-Z]+\\b\");\n\n foreach ( Match match in matches )\n {\n yield return match.Value;\n }\n }\n\n /// \n /// Builds a complete sentence from a list of tokens.\n /// \n private static string BuildSentenceFromTokens(IReadOnlyList tokens)\n {\n if ( tokens.Count == 0 )\n {\n return string.Empty;\n }\n\n var builder = new StringBuilder();\n\n // Add all tokens except the last one with their whitespace\n for ( var i = 0; i < tokens.Count - 1; i++ )\n {\n if ( tokens[i] == null || tokens[i].Text == null )\n {\n continue;\n }\n\n builder.Append(tokens[i].Text);\n if ( tokens[i].Whitespace == \" \" )\n {\n builder.Append(' ');\n }\n }\n\n // Add the last token\n if ( tokens[^1] != null && tokens[^1].Text != null )\n {\n builder.Append(tokens[^1].Text);\n }\n\n return builder.ToString();\n }\n\n /// \n /// Determines the start and end time boundaries for audio replacement.\n /// \n private (double Start, double End) DetermineTimeBoundaries(Token token, IReadOnlyList allTokens, int tokenIndex)\n {\n if ( token == null )\n {\n return (0, 0); // Default for null tokens\n }\n\n double startTime,\n endTime;\n\n // Handle the case where this is the first token with missing timestamps\n if ( tokenIndex == 0 && (!token.StartTs.HasValue || !token.EndTs.HasValue) )\n {\n startTime = 0;\n\n // For end time, use token's end time if available, otherwise use a reasonable default\n endTime = token.EndTs ?? EstimateTokenDuration(token);\n }\n else\n {\n // Determine start time\n if ( !token.StartTs.HasValue )\n {\n // If no start time is available, use previous token's end time if possible\n if ( tokenIndex > 0 && allTokens[tokenIndex - 1] != null )\n {\n var prevToken = allTokens[tokenIndex - 1];\n startTime = prevToken.EndTs ?? prevToken.StartTs ?? 0;\n }\n else\n {\n startTime = 0;\n }\n }\n else\n {\n startTime = token.StartTs.Value;\n }\n\n // Determine end time\n if ( !token.EndTs.HasValue )\n {\n // If no end time is available, check if we can use the next token's start time\n if ( tokenIndex < allTokens.Count - 1 && allTokens[tokenIndex + 1] != null )\n {\n var nextToken = allTokens[tokenIndex + 1];\n endTime = nextToken.StartTs ?? startTime + EstimateTokenDuration(token);\n }\n else\n {\n // For the last token, estimate a reasonable duration\n endTime = startTime + EstimateTokenDuration(token);\n }\n }\n else\n {\n endTime = token.EndTs.Value;\n }\n }\n\n // Ensure we always have a positive duration\n if ( endTime <= startTime )\n {\n endTime = startTime + 0.1; // Add minimal duration if times are invalid\n }\n\n return (startTime, endTime);\n }\n\n /// \n /// Estimates a reasonable duration for a token based on its content length.\n /// \n private double EstimateTokenDuration(Token token)\n {\n if ( token == null )\n {\n return 0.1; // Default for null tokens\n }\n\n // Average speaking rate is roughly 5-6 characters per second\n const double charsPerSecond = 5.5;\n\n // Minimum duration to ensure even single characters get enough time\n const double minimumDuration = 0.1;\n\n return Math.Max(minimumDuration, (token.Text?.Length ?? 0) / charsPerSecond);\n }\n\n /// \n /// Applies a beep tone to a section of audio with smooth fade-in and fade-out.\n /// \n private void ApplyBeepTone(Span audioData, int startIndex, int endIndex, int sampleRate)\n {\n var length = endIndex - startIndex;\n if ( length <= 0 )\n {\n return;\n }\n\n // Calculate how to map our pre-calculated beep cycle to the current sample rate\n var cycleScaleFactor = (double)sampleRate / REFERENCE_SAMPLE_RATE;\n\n // Number of samples for one complete cycle at the current sample rate\n var samplesPerCycle = (int)(_beepCycle.Length * cycleScaleFactor);\n\n // Make sure we have at least one sample per cycle\n samplesPerCycle = Math.Max(1, samplesPerCycle);\n\n // Apply a short fade-in and fade-out to avoid clicks\n // 5ms fade at current sample rate or 1/4 of segment length, whichever is smaller\n var fadeLength = Math.Min((int)(0.005 * sampleRate), length / 4);\n fadeLength = Math.Max(1, fadeLength); // Ensure at least 1 sample for fade\n\n for ( var i = 0; i < length; i++ )\n {\n // Calculate the position in the beep cycle\n var cycleIndex = (int)(i % samplesPerCycle / cycleScaleFactor) % _beepCycle.Length;\n\n // Get beep sample from pre-calculated cycle (with bounds check)\n var beepSample = _beepCycle[Math.Max(0, Math.Min(cycleIndex, _beepCycle.Length - 1))];\n\n // Apply fade-in and fade-out for smoother audio transitions\n var fadeMultiplier = 1.0f;\n if ( i < fadeLength )\n {\n fadeMultiplier = (float)i / fadeLength; // Linear fade-in\n }\n else if ( i > length - fadeLength )\n {\n fadeMultiplier = (float)(length - i) / fadeLength; // Linear fade-out\n }\n\n // Replace the original sample with the beep\n audioData[startIndex + i] = beepSample * fadeMultiplier;\n }\n }\n\n /// \n /// Checks if the given word is profane, including checking for variations.\n /// \n private bool IsProfaneWord(string word)\n {\n if ( string.IsNullOrWhiteSpace(word) )\n {\n return false;\n }\n\n // Check cache first to avoid redundant processing\n if ( _wordCheckCache.TryGetValue(word, out var result) )\n {\n return result;\n }\n\n // Normalize the word\n var normalized = NormalizeText(word);\n\n // Direct match check\n if ( _profanityDictionary.Contains(normalized) )\n {\n _wordCheckCache[word] = true;\n\n return true;\n }\n\n // Check for variations with common suffixes\n foreach ( var suffix in COMMON_SUFFIXES )\n {\n if ( normalized.EndsWith(suffix, StringComparison.OrdinalIgnoreCase) )\n {\n // Try removing the suffix and check if the base word is profane\n var baseWord = normalized.Substring(0, normalized.Length - suffix.Length);\n\n // Only check non-empty base words\n if ( !string.IsNullOrEmpty(baseWord) && _profanityDictionary.Contains(baseWord) )\n {\n _wordCheckCache[word] = true;\n\n return true;\n }\n }\n }\n\n // Word not found to be profane after all checks\n _wordCheckCache[word] = false;\n\n return false;\n }\n\n /// \n /// Normalizes text by removing diacritics, punctuation, and converting to lowercase.\n /// \n private static string NormalizeText(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return string.Empty;\n }\n\n // Convert to lowercase and normalize diacritics\n var normalized = text.ToLowerInvariant().Normalize(NormalizationForm.FormD);\n\n // Remove diacritical marks and punctuation in a single pass for efficiency\n var sb = new StringBuilder(normalized.Length);\n foreach ( var c in normalized )\n {\n // Keep only characters that are not diacritics or punctuation\n if ( CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark && !char.IsPunctuation(c) )\n {\n sb.Append(c);\n }\n }\n\n return sb.ToString().Trim();\n }\n\n /// \n /// Loads the profanity dictionary from a file with error handling.\n /// \n private static HashSet LoadProfanityDictionary(string filePath)\n {\n try\n {\n if ( string.IsNullOrEmpty(filePath) || !File.Exists(filePath) )\n {\n Console.Error.WriteLine($\"Warning: Profanity list file not found at: {filePath}\");\n\n return new HashSet(StringComparer.OrdinalIgnoreCase);\n }\n\n return new HashSet(\n File.ReadAllLines(filePath)\n .Where(line => !string.IsNullOrWhiteSpace(line))\n .Select(word => NormalizeText(word.Trim())),\n StringComparer.OrdinalIgnoreCase\n );\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Error loading profanity dictionary: {ex.Message}\");\n\n return new HashSet(StringComparer.OrdinalIgnoreCase);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SilenceAudioSource.cs", "using System.Buffers;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that stores a continuous memory with only silence and returns it when needed.\n/// \npublic sealed class SilenceAudioSource : IAudioSource\n{\n private readonly Lazy byteSilence;\n\n private readonly Lazy floatSilence;\n\n private readonly bool useMemoryPool;\n\n public SilenceAudioSource(TimeSpan duration, uint sampleRate, IReadOnlyDictionary metadata, ushort channelCount = 1, ushort bitsPerSample = 16, bool useMemoryPool = true)\n {\n SampleRate = sampleRate;\n Metadata = metadata;\n ChannelCount = channelCount;\n BitsPerSample = bitsPerSample;\n this.useMemoryPool = useMemoryPool;\n Duration = duration;\n FramesCount = (long)(duration.TotalSeconds * sampleRate);\n\n byteSilence = new Lazy(GenerateByteSilence);\n floatSilence = new Lazy(GenerateFloatSilence);\n }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration { get; }\n\n public TimeSpan TotalDuration => Duration;\n\n public uint SampleRate { get; }\n\n public long FramesCount { get; }\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public void Dispose()\n {\n if ( useMemoryPool )\n {\n // We don't want to clear this as it is silence anyway (no user data to clear)\n if ( byteSilence.IsValueCreated )\n {\n ArrayPool.Shared.Return(byteSilence.Value);\n }\n\n if ( floatSilence.IsValueCreated )\n {\n ArrayPool.Shared.Return(floatSilence.Value, true);\n }\n }\n }\n\n public Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var startIndex = (int)(startFrame * frameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * frameSize);\n\n var slice = byteSilence.Value.AsMemory(startIndex, lengthBytes);\n\n return Task.FromResult(slice);\n }\n\n public Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var startIndex = (int)(startFrame * ChannelCount);\n var lengthSamples = (int)(Math.Min(maxFrames, FramesCount - startFrame) * ChannelCount);\n\n var slice = floatSilence.Value.AsMemory(startIndex, lengthSamples);\n\n return Task.FromResult(slice);\n }\n\n public Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var startIndex = (int)(startFrame * frameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * frameSize);\n\n var slice = byteSilence.Value.AsMemory(startIndex, lengthBytes);\n slice.CopyTo(destination);\n var frames = lengthBytes / frameSize;\n\n return Task.FromResult(frames);\n }\n\n private byte[] GenerateByteSilence()\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var totalBytes = FramesCount * frameSize;\n\n var silence = useMemoryPool ? ArrayPool.Shared.Rent((int)totalBytes) : new byte[totalBytes];\n\n // 8-bit PCM silence is centered at 128, not 0\n if ( BitsPerSample == 8 )\n {\n Array.Fill(silence, 128, 0, (int)totalBytes);\n }\n else\n {\n Array.Clear(silence, 0, (int)totalBytes); // Zero out for non-8-bit audio\n }\n\n return silence;\n }\n\n private float[] GenerateFloatSilence()\n {\n var totalSamples = FramesCount * ChannelCount;\n var silence = useMemoryPool ? ArrayPool.Shared.Rent((int)totalSamples) : new float[totalSamples];\n\n Array.Clear(silence, 0, (int)totalSamples); // Silence is zeroed-out memory\n\n return silence;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsMemoryCache.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Enhanced memory-efficient TTS cache implementation with expiration and metrics\n/// \npublic class TtsMemoryCache : ITtsCache, IAsyncDisposable\n{\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly Timer _cleanupTimer;\n\n private readonly ILogger _logger;\n\n private readonly TtsCacheOptions _options;\n\n private readonly ConcurrentDictionary _pendingOperations = new();\n\n private bool _disposed;\n\n private long _evictions;\n\n // Metrics\n private long _hits;\n\n private long _misses;\n\n public TtsMemoryCache(\n ILogger logger,\n IOptions options = null)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _options = options?.Value ?? new TtsCacheOptions();\n\n // Set up periodic cleanup if expiration is enabled\n if ( _options.ItemExpiration.HasValue )\n {\n // Run cleanup at half the expiration interval or at least every minute\n var cleanupInterval = TimeSpan.FromMilliseconds(\n Math.Max(_options.ItemExpiration.Value.TotalMilliseconds / 2, 60000));\n\n _cleanupTimer = new Timer(CleanupExpiredItems, null, cleanupInterval, cleanupInterval);\n }\n }\n\n /// \n /// Gets or adds an item to the cache with metrics and expiration support\n /// \n public async Task GetOrAddAsync(\n string key,\n Func> valueFactory,\n CancellationToken cancellationToken = default) where T : class\n {\n // Argument validation\n if ( string.IsNullOrEmpty(key) )\n {\n throw new ArgumentException(\"Cache key cannot be null or empty\", nameof(key));\n }\n\n if ( valueFactory == null )\n {\n throw new ArgumentNullException(nameof(valueFactory));\n }\n\n // Check for cancellation\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check if the item exists in cache and is valid\n if ( _cache.TryGetValue(key, out var cacheItem) )\n {\n if ( cacheItem.Value is T typedValue && !IsExpired(cacheItem) )\n {\n Interlocked.Increment(ref _hits);\n _logger.LogDebug(\"Cache hit for key {Key}\", key);\n\n return typedValue;\n }\n\n // Item exists but is either wrong type or expired - remove it\n _cache.TryRemove(key, out _);\n }\n\n // Item not in cache or was invalid, create it\n Interlocked.Increment(ref _misses);\n _logger.LogDebug(\"Cache miss for key {Key}, creating new value\", key);\n\n var stopwatch = new Stopwatch();\n if ( _options.CollectMetrics )\n {\n _pendingOperations[key] = stopwatch;\n stopwatch.Start();\n }\n\n try\n {\n // Create the value\n var value = await valueFactory(cancellationToken);\n\n if ( value == null )\n {\n _logger.LogWarning(\"Value factory for key {Key} returned null\", key);\n\n return null;\n }\n\n // Enforce maximum cache size if configured\n EnforceSizeLimit();\n\n // Add to cache using GetOrAdd to handle the case where another thread might have\n // added the same key while we were creating the value\n var newItem = new CacheItem { Value = value };\n var actualItem = _cache.GetOrAdd(key, newItem);\n\n // If another thread beat us to it and that value is of the correct type, use it\n if ( actualItem != newItem && actualItem.Value is T existingValue && !IsExpired(actualItem) )\n {\n _logger.LogDebug(\"Another thread already added key {Key}\", key);\n\n return existingValue;\n }\n\n return value;\n }\n catch (Exception ex) when (ex is not OperationCanceledException)\n {\n _logger.LogError(ex, \"Error creating value for key {Key}\", key);\n\n throw;\n }\n finally\n {\n if ( _options.CollectMetrics && _pendingOperations.TryRemove(key, out var sw) )\n {\n sw.Stop();\n _logger.LogDebug(\"Value creation for key {Key} took {ElapsedMs}ms\", key, sw.ElapsedMilliseconds);\n }\n }\n }\n\n /// \n /// Removes an item from the cache\n /// \n public void Remove(string key)\n {\n if ( string.IsNullOrEmpty(key) )\n {\n throw new ArgumentException(\"Cache key cannot be null or empty\", nameof(key));\n }\n\n if ( _cache.TryRemove(key, out _) )\n {\n _logger.LogDebug(\"Removed item with key {Key} from cache\", key);\n }\n }\n\n /// \n /// Clears the cache\n /// \n public void Clear()\n {\n _cache.Clear();\n _logger.LogInformation(\"Cache cleared\");\n }\n\n /// \n /// Disposes the cache resources\n /// \n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n\n _cleanupTimer?.Dispose();\n _cache.Clear();\n\n var stats = GetStatistics();\n _logger.LogInformation(\n \"Cache disposed. Final stats: Size={Size}, Hits={Hits}, Misses={Misses}, Evictions={Evictions}\",\n stats.Size, stats.Hits, stats.Misses, stats.Evictions);\n\n await Task.CompletedTask;\n }\n\n /// \n /// Gets the current cache statistics\n /// \n public (int Size, long Hits, long Misses, long Evictions) GetStatistics() { return (_cache.Count, _hits, _misses, _evictions); }\n\n /// \n /// Determines if a cache item has expired\n /// \n private bool IsExpired(CacheItem item)\n {\n if ( _options.ItemExpiration == null )\n {\n return false;\n }\n\n return DateTime.UtcNow - item.CreatedAt > _options.ItemExpiration.Value;\n }\n\n /// \n /// Enforces the maximum cache size by removing oldest items if necessary\n /// \n private void EnforceSizeLimit()\n {\n if ( _options.MaxItems <= 0 || _cache.Count < _options.MaxItems )\n {\n return;\n }\n\n // Get all items with their ages\n var items = _cache.ToArray();\n\n // Sort by creation time (oldest first)\n Array.Sort(items, (a, b) => a.Value.CreatedAt.CompareTo(b.Value.CreatedAt));\n\n // Remove oldest items to get back under the limit\n // We'll remove 10% of max capacity to avoid doing this too frequently\n var toRemove = Math.Max(1, _options.MaxItems / 10);\n\n for ( var i = 0; i < toRemove && i < items.Length; i++ )\n {\n if ( _cache.TryRemove(items[i].Key, out _) )\n {\n Interlocked.Increment(ref _evictions);\n }\n }\n\n _logger.LogInformation(\"Removed {Count} items from cache due to size limit\", toRemove);\n }\n\n /// \n /// Periodically removes expired items from the cache\n /// \n private void CleanupExpiredItems(object state)\n {\n if ( _disposed )\n {\n return;\n }\n\n try\n {\n var removed = 0;\n foreach ( var key in _cache.Keys )\n {\n if ( _cache.TryGetValue(key, out var item) && IsExpired(item) )\n {\n if ( _cache.TryRemove(key, out _) )\n {\n removed++;\n Interlocked.Increment(ref _evictions);\n }\n }\n }\n\n if ( removed > 0 )\n {\n _logger.LogInformation(\"Removed {Count} expired items from cache\", removed);\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during cache cleanup\");\n }\n }\n\n private class CacheItem\n {\n public object Value { get; set; }\n\n public DateTime CreatedAt { get; } = DateTime.UtcNow;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/DefaultAudioBufferManager.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Default implementation of IAudioBufferManager.\n/// \npublic class DefaultAudioBufferManager : IAudioBufferManager\n{\n private readonly BlockingCollection<(Memory Data, AudioSegment Segment)> _audioQueue;\n\n private readonly ILogger _logger;\n\n private readonly int _maxBufferCount;\n\n private bool _disposed;\n\n public DefaultAudioBufferManager(int maxBufferCount = 32, ILogger? logger = null)\n {\n _maxBufferCount = maxBufferCount > 0\n ? maxBufferCount\n : throw new ArgumentException(\"Max buffer count must be positive\", nameof(maxBufferCount));\n\n _logger = logger ?? NullLogger.Instance;\n _audioQueue = new BlockingCollection<(Memory, AudioSegment)>(_maxBufferCount);\n }\n\n public int BufferCount => _audioQueue.Count;\n\n public bool ProducerCompleted { get; private set; }\n\n public async Task EnqueueSegmentsAsync(\n IAsyncEnumerable audioSegments,\n CancellationToken cancellationToken)\n {\n try\n {\n ProducerCompleted = false;\n\n await foreach ( var segment in audioSegments.WithCancellation(cancellationToken) )\n {\n if ( segment.AudioData.Length <= 0 || cancellationToken.IsCancellationRequested )\n {\n continue;\n }\n\n try\n {\n // Add to bounded collection - will block if queue is full (applying backpressure)\n _audioQueue.Add((segment.AudioData, segment), cancellationToken);\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n // Expected when cancellation is requested\n break;\n }\n catch (InvalidOperationException) when (_audioQueue.IsAddingCompleted)\n {\n // Queue was completed during processing\n break;\n }\n }\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n _logger.LogInformation(\"Audio enqueuing cancelled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error while enqueuing audio segments\");\n\n throw;\n }\n finally\n {\n ProducerCompleted = true;\n }\n }\n\n public bool TryGetNextBuffer(\n out (Memory Data, AudioSegment Segment) buffer,\n int timeoutMs,\n CancellationToken cancellationToken)\n {\n return _audioQueue.TryTake(out buffer, timeoutMs, cancellationToken);\n }\n\n public void Clear()\n {\n while ( _audioQueue.TryTake(out _) ) { }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n\n try\n {\n _audioQueue.Dispose();\n await Task.CompletedTask; // For async consistency\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing audio buffer manager\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/RouletteWheelEditor.cs", "using System.Diagnostics;\nusing System.Drawing;\nusing System.Numerics;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class RouletteWheelEditor : ConfigSectionEditorBase\n{\n private readonly string[] _anchorOptions = { \"TopLeft\", \"TopCenter\", \"TopRight\", \"MiddleLeft\", \"MiddleCenter\", \"MiddleRight\", \"BottomLeft\", \"BottomCenter\", \"BottomRight\" };\n\n private readonly FontProvider _fontProvider;\n\n private readonly string[] _positionOptions = { \"Center\", \"Custom Position\", \"Anchor Position\" };\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly RouletteWheel.RouletteWheel _wheel;\n\n private bool _animateToggle;\n\n private float _animationDuration;\n\n private List _availableFonts = new();\n\n private RouletteWheelOptions _currentConfig;\n\n private bool _defaultEnabled;\n\n private string _fontName;\n\n private int _fontSize;\n\n private int _height;\n\n private bool _loadingFonts = false;\n\n private float _minRotations;\n\n private string _newSectionLabel = string.Empty;\n\n private bool _radialTextOrientation = true;\n\n private float _rotationDegrees;\n\n private string[] _sectionLabels;\n\n private int _selectedAnchor = 4;\n\n private int _selectedPositionOption = 0;\n\n private int _selectedSection = 0;\n\n private float _spinDuration;\n\n private ActiveOperation? _spinningOperation = null;\n\n private int _strokeWidth;\n\n private string _textColor;\n\n private float _textScale;\n\n private bool _useAdaptiveSize = true;\n\n private int _width;\n\n private float _xPosition = 0.5f;\n\n private float _yPosition = 0.5f;\n\n public RouletteWheelEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IUiThemeManager themeManager,\n RouletteWheel.RouletteWheel wheel,\n FontProvider fontProvider)\n : base(configManager, stateManager)\n {\n _wheel = wheel;\n _themeManager = themeManager;\n _fontProvider = fontProvider;\n\n _currentConfig = ConfigManager.GetConfiguration(\"RouletteWheel\");\n LoadConfiguration(_currentConfig);\n }\n\n public override string SectionKey => \"Roulette\";\n\n public override string DisplayName => \"Roulette Configuration\";\n\n public override void Initialize() { LoadAvailableFontsAsync(); }\n\n private async void Spin(int? targetSection = null)\n {\n if ( _wheel.IsSpinning )\n {\n return;\n }\n\n try\n {\n _spinningOperation = new ActiveOperation(\"wheel-spinning\", \"Spinning Wheel\");\n StateManager.RegisterActiveOperation(_spinningOperation);\n await _wheel.SpinAsync(targetSection);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"Spinning cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during spinning: {ex.Message}\");\n\n if ( _spinningOperation != null )\n {\n StateManager.ClearActiveOperation(_spinningOperation.Id);\n _spinningOperation = null;\n }\n }\n }\n\n private async void LoadAvailableFontsAsync()\n {\n try\n {\n _loadingFonts = true;\n\n var operation = new ActiveOperation(\"load-fonts\", \"Loading Fonts\");\n StateManager.RegisterActiveOperation(operation);\n\n var fonts = await _fontProvider.GetAvailableFontsAsync();\n _availableFonts = fonts.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading fonts: {ex.Message}\");\n _availableFonts = [];\n }\n finally\n {\n _loadingFonts = false;\n }\n }\n\n private void LoadConfiguration(RouletteWheelOptions config)\n {\n _width = config.Width;\n _height = config.Height;\n _fontName = config.Font;\n _fontSize = config.FontSize;\n _textScale = config.TextScale;\n _textColor = config.TextColor;\n _strokeWidth = config.TextStroke;\n _useAdaptiveSize = config.AdaptiveText;\n _radialTextOrientation = config.RadialTextOrientation;\n _sectionLabels = config.SectionLabels;\n _spinDuration = config.SpinDuration;\n _minRotations = config.MinRotations;\n _animateToggle = config.AnimateToggle;\n _animationDuration = config.AnimationDuration;\n _defaultEnabled = config.Enabled;\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n if ( ImGui.BeginTabBar(\"RouletteConfigTabs\") )\n {\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettingsTab();\n RenderSectionsTab();\n RenderBehaviorTab();\n RenderStyleTab();\n\n ImGui.EndTabItem();\n }\n\n RenderPositioningTab();\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all Wheel settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n private void RenderBasicSettingsTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n bool widthChanged,\n heightChanged;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Wheel Dimensions\");\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(125);\n widthChanged = ImGui.InputInt(\"Width##WheelWidth\", ref _width, 10);\n if ( widthChanged )\n {\n _width = Math.Max(50, _width); // Minimum width\n }\n\n ImGui.SameLine();\n\n ImGui.SetCursorPosX(availWidth - 175);\n if ( ImGui.Button(\"Equal Dimensions\", new Vector2(175, 0)) )\n {\n var size = Math.Max(_width, _height);\n _width = _height = size;\n _wheel.SetDiameter(size);\n widthChanged = true;\n heightChanged = true;\n }\n\n ImGui.SetNextItemWidth(125);\n heightChanged = ImGui.InputInt(\"Height##WheelHeight\", ref _height, 10);\n if ( heightChanged )\n {\n _height = Math.Max(50, _height); // Minimum height\n }\n\n if ( widthChanged || heightChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderSectionsTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n var sectionsChanged = false;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Wheel Sections\");\n ImGui.Spacing();\n\n if ( _sectionLabels.Length > 0 )\n {\n ImGui.BeginChild(\"SectionsList\", new Vector2(0, 0), ImGuiChildFlags.AutoResizeY);\n\n for ( var i = 0; i < _sectionLabels.Length; i++ )\n {\n ImGui.PushID(i);\n\n var tempLabel = _sectionLabels[i];\n ImGui.SetNextItemWidth(availWidth - 10 - 30);\n if ( ImGui.InputText(\"##SectionLabel\", ref tempLabel, 128) )\n {\n _sectionLabels[i] = tempLabel;\n sectionsChanged = true;\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"X##RemoveSection\" + i, new Vector2(30, 0)) )\n {\n var newLabels = new string[_sectionLabels.Length - 1];\n Array.Copy(_sectionLabels, 0, newLabels, 0, i);\n Array.Copy(_sectionLabels, i + 1, newLabels, i, _sectionLabels.Length - i - 1);\n _sectionLabels = newLabels;\n sectionsChanged = true;\n }\n\n ImGui.PopID();\n }\n\n ImGui.EndChild();\n }\n else\n {\n TextHelper.TextCenteredH(\"No sections defined. Add your first section below.\");\n }\n\n // Add new section\n ImGui.Spacing();\n // ImGui.Separator();\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(availWidth - 80 - 10);\n ImGui.InputText(\"##NewSectionLabel\", ref _newSectionLabel, 128);\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Add\", new Vector2(80, 0)) && !string.IsNullOrWhiteSpace(_newSectionLabel) )\n {\n // Add the new section\n var newLabels = new string[(_sectionLabels?.Length ?? 0) + 1];\n if ( _sectionLabels is { Length: > 0 } )\n {\n Array.Copy(_sectionLabels, newLabels, _sectionLabels.Length);\n }\n\n newLabels[^1] = _newSectionLabel;\n _sectionLabels = newLabels;\n _newSectionLabel = string.Empty;\n sectionsChanged = true;\n }\n\n if ( sectionsChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderStyleTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n var configChanged = false;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Text Appearance\");\n ImGui.Spacing();\n\n // Font selection with refresh button\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingFonts )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading fonts...\";\n ImGui.InputText(\"##Font\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n var fontChanged = false;\n if ( ImGui.BeginCombo(\"##Font\", string.IsNullOrEmpty(_fontName) ? \"\" : _fontName) )\n {\n if ( _availableFonts.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No fonts available\");\n }\n else\n {\n foreach ( var font in _availableFonts )\n {\n var isSelected = font == _fontName;\n if ( ImGui.Selectable(font, isSelected) )\n {\n _fontName = font;\n fontChanged = true;\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n\n configChanged |= fontChanged;\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh\", new Vector2(-1, 0)) )\n {\n LoadAvailableFontsAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available fonts list\");\n }\n }\n\n ImGui.Spacing();\n\n // ImGui.SetCursorPosX((availWidth - 110f - 200f - 110f - 200f) * .5f);\n // Create a 2-column table for consistent alignment\n if ( ImGui.BeginTable(\"StyleProperties\", 4, ImGuiTableFlags.SizingFixedFit) )\n {\n ImGui.TableSetupColumn(\"1\", 110f);\n ImGui.TableSetupColumn(\"2\", 200f);\n ImGui.TableSetupColumn(\"3\", 120f);\n ImGui.TableSetupColumn(\"4\", 220f);\n\n // Font Size\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Font Size\");\n ImGui.TableNextColumn();\n var fontSizeChanged = ImGui.InputInt(\"##FontSize\", ref _fontSize, 1);\n if ( fontSizeChanged )\n {\n _fontSize = Math.Clamp(_fontSize, 1, 72);\n configChanged = true;\n }\n\n // Text Scale\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Scale\");\n ImGui.TableNextColumn();\n var scaleChanged = ImGui.SliderFloat(\"##Scale\", ref _textScale, 0.5f, 2.0f, \"%.1f\");\n configChanged |= scaleChanged;\n\n // Text Color\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Color\");\n ImGui.TableNextColumn();\n var color = ColorTranslator.FromHtml(_textColor);\n var colorVec = new Vector4(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f);\n var colorChanged = ImGui.ColorEdit4(\"##Color\", ref colorVec, ImGuiColorEditFlags.DisplayHex);\n if ( colorChanged )\n {\n _textColor = $\"#{(int)(colorVec.W * 255):X2}{(int)(colorVec.X * 255):X2}{(int)(colorVec.Y * 255):X2}{(int)(colorVec.Z * 255):X2}\";\n configChanged = true;\n }\n\n // Stroke Width\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Stroke Width\");\n ImGui.TableNextColumn();\n var strokeChanged = ImGui.InputInt(\"##StrokeWidth\", ref _strokeWidth, 1);\n if ( strokeChanged )\n {\n _strokeWidth = Math.Clamp(_strokeWidth, 0, 5);\n configChanged = true;\n }\n\n ImGui.EndTable();\n }\n\n ImGui.Spacing();\n\n // Checkbox options in two columns\n var checkboxWidth = availWidth / 2 - 10;\n var adaptSizeChanged = ImGui.Checkbox(\"Adaptive Size\", ref _useAdaptiveSize);\n ImGui.SameLine(checkboxWidth + 43);\n var radialOrienChanged = ImGui.Checkbox(\"Radial Orientation\", ref _radialTextOrientation);\n\n configChanged |= adaptSizeChanged | radialOrienChanged;\n\n // Apply configuration changes if needed\n if ( configChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderPositioningTab()\n {\n if ( ImGui.BeginTabItem(\"Position & Rotation\") )\n {\n ImGui.Text(\"Wheel Position\");\n ImGui.Separator();\n\n // Position method selector\n ImGui.Combo(\"Position Method\", ref _selectedPositionOption, _positionOptions, _positionOptions.Length);\n\n ImGui.Spacing();\n\n // Different UI based on position method\n switch ( _selectedPositionOption )\n {\n case 0: // Center\n if ( ImGui.Button(\"Center in Viewport\", new Vector2(200, 0)) )\n {\n _wheel.CenterInViewport();\n }\n\n break;\n\n case 1: // Custom Position\n ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X * 0.4f);\n ImGui.SliderFloat(\"X Position %\", ref _xPosition, 0.0f, 1.0f, \"%.2f\");\n\n ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X * 0.4f);\n ImGui.SliderFloat(\"Y Position %\", ref _yPosition, 0.0f, 1.0f, \"%.2f\");\n\n if ( ImGui.Button(\"Apply Position\", new Vector2(200, 0)) )\n {\n _wheel.PositionByPercentage(_xPosition, _yPosition);\n }\n\n break;\n\n case 2: // Anchor Position\n ImGui.Combo(\"Anchor Point\", ref _selectedAnchor, _anchorOptions, _anchorOptions.Length);\n\n if ( ImGui.Button(\"Apply Anchor\", new Vector2(200, 0)) )\n {\n // This would need a conversion from index to the actual ViewportAnchor enum\n // For now, just showing the concept\n // _wheel.PositionAt((ViewportAnchor)_selectedAnchor, new Vector2(0, 0));\n\n // Simple implementation for demo purposes:\n switch ( _selectedAnchor )\n {\n case 0:\n _wheel.PositionByPercentage(0.0f, 0.0f);\n\n break; // TopLeft\n case 1:\n _wheel.PositionByPercentage(0.5f, 0.0f);\n\n break; // TopCenter\n case 2:\n _wheel.PositionByPercentage(1.0f, 0.0f);\n\n break; // TopRight\n case 3:\n _wheel.PositionByPercentage(0.0f, 0.5f);\n\n break; // MiddleLeft\n case 4:\n _wheel.PositionByPercentage(0.5f, 0.5f);\n\n break; // MiddleCenter\n case 5:\n _wheel.PositionByPercentage(1.0f, 0.5f);\n\n break; // MiddleRight\n case 6:\n _wheel.PositionByPercentage(0.0f, 1.0f);\n\n break; // BottomLeft\n case 7:\n _wheel.PositionByPercentage(0.5f, 1.0f);\n\n break; // BottomCenter\n case 8:\n _wheel.PositionByPercentage(1.0f, 1.0f);\n\n break; // BottomRight\n }\n }\n\n break;\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Text(\"Wheel Rotation\");\n\n // Display current rotation\n ImGui.Text($\"Current Rotation: {_rotationDegrees:F1}°\");\n\n // Rotation slider\n ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X * 0.7f);\n if ( ImGui.SliderFloat(\"Rotation (degrees)\", ref _rotationDegrees, 0.0f, 360.0f, \"%.1f°\") )\n {\n _wheel.RotateByDegrees(_rotationDegrees - _wheel.RotationDegrees);\n }\n\n // Quick rotation buttons\n if ( ImGui.Button(\"+45°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(45);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"+90°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(90);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"-45°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(-45);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"-90°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(-90);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.EndTabItem();\n }\n }\n\n private void RenderBehaviorTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Spin Configuration\");\n ImGui.Spacing();\n\n // Spin duration\n ImGui.SetNextItemWidth(125);\n var spinDurationChanged = ImGui.SliderFloat(\"Spin Duration (sec)\", ref _spinDuration, 1.0f, 10.0f, \"%.1f\");\n\n // Min rotations\n ImGui.SetNextItemWidth(125);\n var minRotChanged = ImGui.SliderFloat(\"Min Rotations\", ref _minRotations, 1.0f, 10.0f, \"%.0f\");\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Animation Settings\");\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(125);\n var aniDurChanged = ImGui.SliderFloat(\"Animation Duration (sec)\", ref _animationDuration, 0.1f, 2.0f, \"%.1f\");\n\n ImGui.SameLine();\n ImGui.SetCursorPosX(availWidth - 200);\n\n // Animation toggle\n ImGui.SetNextItemWidth(200);\n var aniShowHideChanged = ImGui.Checkbox(\"Animate Show/Hide\", ref _animateToggle);\n\n ImGui.SetCursorPosX(availWidth - 200);\n\n ImGui.SetNextItemWidth(200);\n var defaultEnabledChanged = ImGui.Checkbox(\"Default Enabled\", ref _defaultEnabled);\n\n if ( spinDurationChanged || minRotChanged || aniDurChanged || aniShowHideChanged || defaultEnabledChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderTestingSection()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Playground\");\n ImGui.Spacing();\n\n if ( _sectionLabels.Length > 0 )\n {\n ImGui.SetNextItemWidth(availWidth - 155);\n ImGui.Combo(\"##TargetSection\", ref _selectedSection, _sectionLabels, _sectionLabels.Length);\n\n ImGui.SameLine(0, 5);\n\n if ( _wheel.IsSpinning )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Spin to Selected\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Spin to Selected\", new Vector2(150, 0)) )\n {\n Spin(_selectedSection);\n }\n\n ImGui.Spacing();\n ImGui.SetCursorPosX(availWidth - 150);\n\n if ( _wheel.IsSpinning )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Spin Random\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Spin Random\", new Vector2(150, 0)) )\n {\n Spin();\n }\n\n ImGui.SameLine(-1, 0);\n\n if ( _wheel.IsEnabled )\n {\n if ( ImGui.Button(\"Hide Wheel\", new Vector2(155, 0)) )\n {\n _wheel.Disable();\n }\n }\n else\n {\n if ( ImGui.Button(\"Show Wheel\", new Vector2(155, 0)) )\n {\n _wheel.Enable();\n }\n }\n\n if ( _wheel.IsSpinning )\n {\n ImGui.SameLine(0, 10);\n ImGui.SetNextItemWidth(availWidth - 155 - 150 - 10 - 5);\n ImGui.ProgressBar(_spinningOperation?.Progress ?? 0, new Vector2(0, 0), \"Spinning...\");\n }\n }\n else\n {\n var txt = \"Add sections to test spinning\";\n ImGui.SetCursorPosX((availWidth - ImGui.CalcTextSize(txt).X) * 0.5f);\n ImGui.TextColored(new Vector4(1, 0.3f, 0.3f, 1), txt);\n }\n }\n\n private void UpdateConfiguration()\n {\n var updatedConfig = _currentConfig with {\n Font = _fontName,\n FontSize = _fontSize,\n TextColor = _textColor,\n TextScale = _textScale,\n TextStroke = _strokeWidth,\n AdaptiveText = _useAdaptiveSize,\n RadialTextOrientation = _radialTextOrientation,\n SectionLabels = _sectionLabels,\n SpinDuration = _spinDuration,\n MinRotations = _minRotations,\n Enabled = _defaultEnabled,\n Width = _width,\n Height = _height,\n RotationDegrees = _rotationDegrees,\n AnimateToggle = _animateToggle,\n AnimationDuration = _animationDuration\n };\n\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(updatedConfig, SectionKey);\n\n MarkAsChanged();\n }\n\n public override void Update(float deltaTime)\n {\n if ( _spinningOperation != null && _wheel.IsSpinning )\n {\n _spinningOperation.Progress = _wheel.Progress;\n }\n }\n\n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved();\n }\n\n private void ResetToDefaults()\n {\n var defaultConfig = new RouletteWheelOptions();\n _currentConfig = defaultConfig;\n\n LoadConfiguration(_currentConfig);\n\n ConfigManager.UpdateConfiguration(defaultConfig, SectionKey);\n MarkAsChanged();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/TtsConfigEditor.cs", "using System.Diagnostics;\nusing System.Numerics;\nusing System.Threading.Channels;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets.Dialogs;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.RVC;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for TTS section configuration\n/// \npublic class TtsConfigEditor : ConfigSectionEditorBase\n{\n private readonly IAudioOutputAdapter _audioPlayer;\n\n private readonly IRVCVoiceProvider _rvcProvider;\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly ITtsEngine _ttsEngine;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private List _availableRVCs = new();\n\n private List _availableVoices = new();\n\n private TtsConfiguration _currentConfig;\n\n private RVCFilterOptions _currentRvcFilterOptions;\n\n private KokoroVoiceOptions _currentVoiceOptions;\n\n private string _defaultRVC;\n\n private string _defaultVoice;\n\n private string _espeakPath;\n\n private bool _isPlaying = false;\n\n private bool _loadingRvcs = false;\n\n private bool _loadingVoices = false;\n\n private int _maxPhonemeLength;\n\n private string _modelDir;\n\n private ActiveOperation? _playbackOperation = null;\n\n private bool _rvcEnabled;\n\n private int _rvcF0UpKey;\n\n private int _rvcHopSize;\n\n private int _sampleRate;\n\n private float _speechRate;\n\n private string _testText = \"This is a test of the text-to-speech system.\";\n\n private bool _trimSilence;\n\n private bool _useBritishEnglish;\n\n public TtsConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n ITtsEngine ttsEngine,\n IOutputAdapter audioPlayer,\n IKokoroVoiceProvider voiceProvider,\n IUiThemeManager themeManager, IRVCVoiceProvider rvcProvider)\n : base(configManager, stateManager)\n {\n _ttsEngine = ttsEngine;\n _audioPlayer = (IAudioOutputAdapter)audioPlayer;\n _voiceProvider = voiceProvider;\n _themeManager = themeManager;\n _rvcProvider = rvcProvider;\n\n LoadConfiguration();\n\n // _audioPlayerHost.OnPlaybackStarted += OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted += OnPlaybackCompleted;\n }\n\n public override string SectionKey => \"TTS\";\n\n public override string DisplayName => \"TTS Configuration\";\n\n public override void Initialize()\n {\n // Load available voices\n LoadAvailableVoicesAsync();\n LoadAvailableRVCAsync();\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Main layout with tabs for different sections\n if ( ImGui.BeginTabBar(\"TtsConfigTabs\") )\n {\n // Basic settings tab\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettings();\n\n ImGui.EndTabItem();\n }\n\n // Advanced settings tab\n if ( ImGui.BeginTabItem(\"Advanced Settings\") )\n {\n RenderAdvancedSettings();\n ImGui.EndTabItem();\n }\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n // Reset button at bottom\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all TTS settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n public override void Update(float deltaTime)\n {\n // Simplified update just for playback operation\n if ( _playbackOperation != null && _isPlaying )\n {\n _playbackOperation.Progress += deltaTime * 0.1f;\n if ( _playbackOperation.Progress > 0.99f )\n {\n _playbackOperation.Progress = 0.99f;\n }\n }\n }\n\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args);\n\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n }\n }\n\n public override void Dispose()\n {\n // Unsubscribe from audio player events\n // _audioPlayerHost.OnPlaybackStarted -= OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted -= OnPlaybackCompleted;\n\n // Cancel any active playback\n StopPlayback();\n\n base.Dispose();\n }\n\n #region Configuration Management\n\n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(\"TTS\");\n _currentVoiceOptions = _currentConfig.Voice;\n _currentRvcFilterOptions = _currentConfig.Rvc;\n\n // Update local fields from configuration\n _modelDir = _currentConfig.ModelDirectory;\n _espeakPath = _currentConfig.EspeakPath;\n _speechRate = _currentVoiceOptions.DefaultSpeed;\n _sampleRate = _currentVoiceOptions.SampleRate;\n _trimSilence = _currentVoiceOptions.TrimSilence;\n _useBritishEnglish = _currentVoiceOptions.UseBritishEnglish;\n _defaultVoice = _currentVoiceOptions.DefaultVoice;\n _maxPhonemeLength = _currentVoiceOptions.MaxPhonemeLength;\n\n // RVC\n _defaultRVC = _currentRvcFilterOptions.DefaultVoice;\n _rvcEnabled = _currentRvcFilterOptions.Enabled;\n _rvcHopSize = _currentRvcFilterOptions.HopSize;\n _rvcF0UpKey = _currentRvcFilterOptions.F0UpKey;\n }\n\n private async void LoadAvailableVoicesAsync()\n {\n try\n {\n _loadingVoices = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-voices\", \"Loading Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _voiceProvider.GetAvailableVoicesAsync();\n _availableVoices = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableVoices = [];\n }\n finally\n {\n _loadingVoices = false;\n }\n }\n\n private async void LoadAvailableRVCAsync()\n {\n try\n {\n _loadingRvcs = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-rvc\", \"Loading RVC Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _rvcProvider.GetAvailableVoicesAsync();\n _availableRVCs = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableRVCs = [];\n }\n finally\n {\n _loadingRvcs = false;\n }\n }\n\n private void UpdateConfiguration()\n {\n var updatedVoiceOptions = new KokoroVoiceOptions {\n DefaultVoice = _defaultVoice,\n DefaultSpeed = _speechRate,\n SampleRate = _sampleRate,\n TrimSilence = _trimSilence,\n UseBritishEnglish = _useBritishEnglish,\n MaxPhonemeLength = _maxPhonemeLength\n };\n\n var updatedRVCOptions = new RVCFilterOptions { DefaultVoice = _defaultRVC, Enabled = _rvcEnabled, HopSize = _rvcHopSize, F0UpKey = _rvcF0UpKey };\n\n var updatedConfig = new TtsConfiguration { ModelDirectory = _modelDir, EspeakPath = _espeakPath, Voice = updatedVoiceOptions, Rvc = updatedRVCOptions };\n\n _currentRvcFilterOptions = updatedRVCOptions;\n _currentVoiceOptions = updatedVoiceOptions;\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(updatedConfig, SectionKey);\n\n MarkAsChanged();\n }\n\n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved();\n }\n\n private void ResetToDefaults()\n {\n // Create default configuration\n var defaultVoiceOptions = new KokoroVoiceOptions();\n var defaultConfig = new TtsConfiguration();\n\n // Update local state\n _currentVoiceOptions = defaultVoiceOptions;\n _currentConfig = defaultConfig;\n\n // Update UI fields\n _modelDir = defaultConfig.ModelDirectory;\n _espeakPath = defaultConfig.EspeakPath;\n _speechRate = defaultVoiceOptions.DefaultSpeed;\n _sampleRate = defaultVoiceOptions.SampleRate;\n _trimSilence = defaultVoiceOptions.TrimSilence;\n _useBritishEnglish = defaultVoiceOptions.UseBritishEnglish;\n _defaultVoice = defaultVoiceOptions.DefaultVoice;\n _maxPhonemeLength = defaultVoiceOptions.MaxPhonemeLength;\n\n // Update configuration\n ConfigManager.UpdateConfiguration(defaultConfig, \"TTS\");\n MarkAsChanged();\n }\n\n #endregion\n\n #region Playback Controls\n\n private async void StartPlayback()\n {\n if ( _isPlaying || string.IsNullOrWhiteSpace(_testText) )\n {\n return;\n }\n\n try\n {\n // Create a new playback operation\n _playbackOperation = new ActiveOperation(\"tts-playback\", \"Playing TTS\");\n StateManager.RegisterActiveOperation(_playbackOperation);\n\n _isPlaying = true;\n\n var options = _currentVoiceOptions;\n\n var llmInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var ttsOutput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioEvents = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); // Tts Started/Tts Ended - Audio Started/Audio Ended\n\n await llmInput.Writer.WriteAsync(new LlmChunkEvent(Guid.Empty, Guid.Empty, DateTimeOffset.UtcNow, _testText), _playbackOperation.CancellationSource.Token);\n llmInput.Writer.Complete();\n\n _ = Task.Run(async () =>\n {\n await foreach(var ttsOut in ttsOutput.Reader.ReadAllAsync(_playbackOperation.CancellationSource.Token))\n {\n if ( ttsOut is TtsChunkEvent ttsChunk )\n {\n await audioInput.Writer.WriteAsync(ttsChunk, _playbackOperation.CancellationSource.Token);\n }\n }\n });\n\n _ = _ttsEngine.SynthesizeStreamingAsync(\n llmInput,\n ttsOutput,\n Guid.Empty,\n Guid.Empty,\n options,\n _playbackOperation.CancellationSource.Token\n );\n\n await _audioPlayer.SendAsync(audioInput, audioEvents, Guid.Empty, _playbackOperation.CancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"TTS playback cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during TTS playback: {ex.Message}\");\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n }\n\n private void StopPlayback()\n {\n if ( _playbackOperation != null )\n {\n _playbackOperation.CancellationSource.Cancel();\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n\n _isPlaying = false;\n }\n\n private void OnPlaybackStarted(object sender, EventArgs args)\n {\n _isPlaying = true;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 0.0f;\n }\n }\n\n private void OnPlaybackCompleted(object sender, EventArgs args)\n {\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 1.0f;\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n\n #endregion\n\n #region UI Rendering Methods\n\n private void RenderTestingSection()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Playground\");\n ImGui.Spacing();\n\n // Text input frame with light background\n ImGui.Text(\"Test Text:\");\n ImGui.SetNextItemWidth(availWidth);\n ImGui.InputTextMultiline(\"##TestText\", ref _testText, 1000, new Vector2(0, 80));\n\n ImGui.Spacing();\n ImGui.Spacing();\n\n // Controls section with better layout\n ImGui.BeginGroup();\n {\n // Left side: Example selector\n var controlWidth = Math.Min(180, availWidth * 0.4f);\n ImGui.SetNextItemWidth(controlWidth);\n\n if ( ImGui.BeginCombo(\"##exampleLbl\", \"Select Example\") )\n {\n string[] examples = { \"Hello, world!\", \"The quick brown fox jumps over the lazy dog.\", \"Welcome to the text-to-speech system.\", \"How are you doing today?\", \"Today's date is March 3rd, 2025.\" };\n\n foreach ( var example in examples )\n {\n var isSelected = _testText == example;\n if ( ImGui.Selectable(example, ref isSelected) )\n {\n _testText = example;\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.SameLine(0, 15);\n\n var clearDisabled = string.IsNullOrEmpty(_testText);\n if ( clearDisabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( ImGui.Button(\"Clear\", new Vector2(80, 0)) && !string.IsNullOrEmpty(_testText) )\n {\n _testText = \"\";\n }\n\n if ( clearDisabled )\n {\n ImGui.EndDisabled();\n }\n }\n\n ImGui.EndGroup();\n\n ImGui.SameLine(0, 10);\n\n // Playback controls in a styled frame\n {\n // Play/Stop button with color styling\n if ( _isPlaying )\n {\n if ( UiStyler.AnimatedButton(\"Stop\", new Vector2(80, 0), _isPlaying) )\n {\n StopPlayback();\n }\n\n ImGui.SameLine(0, 15);\n ImGui.ProgressBar(_playbackOperation?.Progress ?? 0, new Vector2(-1, 0), \"Playing\");\n }\n else\n {\n var disabled = string.IsNullOrWhiteSpace(_testText);\n if ( disabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( UiStyler.AnimatedButton(\"Play\", new Vector2(80, 0), _isPlaying) )\n {\n StartPlayback();\n }\n\n if ( disabled )\n {\n ImGui.EndDisabled();\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Enter some text to play\");\n }\n }\n }\n }\n }\n\n private void RenderBasicSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // === Voice Selection Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Voice Settings\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingVoices )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading voices...\";\n ImGui.InputText(\"##VoiceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n if ( ImGui.BeginCombo(\"##VoiceSelector\", string.IsNullOrEmpty(_defaultVoice) ? \"\" : _defaultRVC) )\n {\n if ( _availableRVCs.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No voices available\");\n }\n else\n {\n foreach ( var voice in _availableRVCs )\n {\n var isSelected = voice == _defaultRVC;\n if ( ImGui.Selectable(voice, isSelected) )\n {\n _defaultRVC = voice;\n UpdateConfiguration();\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh##RefreshRVC\", new Vector2(-1, 0)) )\n {\n LoadAvailableRVCAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available voices list\");\n }\n\n if ( ImGui.BeginTable(\"RVCProps\", 4, ImGuiTableFlags.SizingFixedFit) )\n {\n ImGui.TableSetupColumn(\"1\", 100f);\n ImGui.TableSetupColumn(\"2\", 200f);\n ImGui.TableSetupColumn(\"3\", 100f);\n ImGui.TableSetupColumn(\"4\", 200f);\n\n // Hop Size\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Hop Size\");\n ImGui.TableNextColumn();\n var fontSizeChanged = ImGui.InputInt(\"##HopSize\", ref _rvcHopSize, 8);\n if ( fontSizeChanged )\n {\n _rvcHopSize = Math.Clamp(_rvcHopSize, 8, 256);\n rvcConfigChanged = true;\n }\n\n // F0 Key\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Pitch\");\n ImGui.TableNextColumn();\n var pitchChanged = ImGui.InputInt(\"##Pitch\", ref _rvcF0UpKey, 1);\n if ( pitchChanged )\n {\n _rvcF0UpKey = Math.Clamp(_rvcF0UpKey, -20, 20);\n rvcConfigChanged = true;\n }\n\n ImGui.EndTable();\n }\n\n if ( !_rvcEnabled )\n {\n ImGui.EndDisabled();\n }\n\n if ( rvcConfigChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n private void RenderAdvancedSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Section header\n ImGui.Spacing();\n ImGui.SeparatorText(\"Advanced TTS Settings\");\n ImGui.Spacing();\n\n var sampleRateChanged = false;\n var phonemeChanged = false;\n\n // ImGui.BeginDisabled();\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Sample Rate:\");\n ImGui.SameLine(200);\n\n string[] sampleRates = [\"16000 Hz (Low quality)\", \"24000 Hz (Standard quality)\", \"32000 Hz (Good quality)\", \"44100 Hz (High quality)\", \"48000 Hz (Studio quality)\"];\n int[] rateValues = [16000, 24000, 32000, 44100, 48000];\n\n var currentIdx = Array.IndexOf(rateValues, _sampleRate);\n if ( currentIdx < 0 )\n {\n currentIdx = 1; // Default to 24000 Hz\n }\n\n ImGui.SetNextItemWidth(availWidth - 200);\n\n if ( ImGui.BeginCombo(\"##SampleRate\", sampleRates[currentIdx]) )\n {\n for ( var i = 0; i < sampleRates.Length; i++ )\n {\n var isSelected = i == currentIdx;\n if ( ImGui.Selectable(sampleRates[i], isSelected) )\n {\n _sampleRate = rateValues[i];\n sampleRateChanged = true;\n }\n\n // Show additional info on hover\n if ( ImGui.IsItemHovered() )\n {\n var tooltipText = i switch {\n 0 => \"Low quality, minimal resource usage\",\n 1 => \"Standard quality, recommended for most uses\",\n 2 => \"Good quality, balanced resource usage\",\n 3 => \"High quality, CD audio standard\",\n 4 => \"Studio quality, higher resource usage\",\n _ => \"\"\n };\n\n ImGui.SetTooltip(tooltipText);\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.EndDisabled();\n }\n\n ImGui.EndGroup();\n\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Max Phoneme Length:\");\n ImGui.SameLine(200);\n\n ImGui.SetNextItemWidth(120);\n phonemeChanged = ImGui.InputInt(\"##MaxPhonemeLength\", ref _maxPhonemeLength);\n ImGui.EndDisabled();\n\n // Clamp value to valid range\n if ( phonemeChanged )\n {\n var oldValue = _maxPhonemeLength;\n _maxPhonemeLength = Math.Clamp(_maxPhonemeLength, 1, 2048);\n\n if ( oldValue != _maxPhonemeLength )\n {\n ImGui.TextColored(new Vector4(1.0f, 0.7f, 0.3f, 1.0f),\n \"Value clamped to valid range (1-2048)\");\n }\n }\n\n // Helper text\n ImGui.Spacing();\n ImGui.TextWrapped(\"This is already setup correctly to work with Kokoro. Shouldn't have to change!\");\n\n // === Paths & Resources Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Paths & Resources\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n // Model directory\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Model Directory:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var modelDirChanged = ImGui.InputText(\"##ModelDir\", ref _modelDir, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##ModelDir\", new Vector2(-1, 0)) )\n {\n var fileDialog = new OpenFolderDialog(_modelDir);\n fileDialog.Show();\n if ( fileDialog.SelectedFolder != null )\n {\n _modelDir = fileDialog.SelectedFolder;\n modelDirChanged = true;\n }\n }\n\n // Espeak path\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Espeak Path:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var espeakPathChanged = ImGui.InputText(\"##EspeakPath\", ref _espeakPath, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##EspeakPath\", new Vector2(-1, 0)) )\n {\n // In a real app, this would open a file browser dialog\n Console.WriteLine(\"Open file browser for Espeak Path\");\n }\n\n // Apply changes if needed\n if ( modelDirChanged || espeakPathChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n ImGui.EndGroup();\n\n if ( sampleRateChanged || phonemeChanged )\n {\n UpdateConfiguration();\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/RouletteWheel.cs", "using System.Drawing;\nusing System.Numerics;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic partial class RouletteWheel : IRenderComponent\n{\n private const int MAX_VERTICES = 64;\n\n private const int MAX_INDICES = MAX_VERTICES * 6 / 4;\n\n private const float OUTER_RADIUS_FACTOR = 0.8f;\n\n private const float INNER_RADIUS_FACTOR = 0.64f; // OUTER_RADIUS_FACTOR * 0.8f\n\n private const float CENTER_RADIUS_FACTOR = 0.128f; // INNER_RADIUS_FACTOR * 0.2f\n\n private static readonly short[] _indexData = GenerateIndexArray();\n\n private readonly Lock _applyingConfig = new();\n\n private readonly IOptionsMonitor _config;\n\n private readonly FontProvider _fontProvider;\n\n private readonly Dictionary _segmentFontSizes = new();\n\n private readonly float _textSizeAdaptationFactor = 1.0f;\n\n private readonly VertexPositionTexture[] _vertexData = new VertexPositionTexture[MAX_VERTICES];\n\n private GL _gl;\n\n private BufferObject _indexBuffer;\n\n private float _minRotations;\n\n private int _numSections = 0;\n\n private Action? _onSpinCompleteCallback;\n\n private Vector2 _position = Vector2.Zero;\n\n private bool _radialTextOrientation = true;\n\n private string[] _sectionLabels;\n\n private Shader _shader;\n\n private float _spinDuration;\n\n private float _spinStartTime = 0f;\n\n private float _startSegment = 0f;\n\n private float _targetSegment = 0f;\n\n private FSColor _textColor = new(255, 255, 255, 255);\n\n private TextRenderer _textRenderer;\n\n private float _textScale = 1.0f;\n\n private int _textStrokeWidth = 2;\n\n private float _time = 0f;\n\n private bool _useAdaptiveTextSize = true;\n\n private VertexArrayObject _vao;\n\n private BufferObject _vertexBuffer;\n\n private int _vertexIndex = 0;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n private float _wheelSize = 1;\n\n public RouletteWheel(IOptionsMonitor config, FontProvider fontProvider)\n {\n _config = config;\n _fontProvider = fontProvider;\n }\n\n public bool IsSpinning { get; private set; } = false;\n\n public float Progress { get; private set; } = 1f;\n\n public int NumberOfSections\n {\n get => _numSections;\n private set\n {\n _numSections = Math.Clamp(value, 2, 24);\n _targetSegment = Math.Min(_targetSegment, _numSections - 1);\n _startSegment = Math.Min(_startSegment, _numSections - 1);\n ResizeSectionLabels();\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n }\n\n public bool UseSpout => true;\n\n public string SpoutTarget => \"RouletteWheel\";\n\n public int Priority => 0;\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _textRenderer = new TextRenderer(gl);\n\n // Initialize buffers\n _vertexBuffer = new BufferObject(gl, MAX_VERTICES, BufferTargetARB.ArrayBuffer, true);\n _indexBuffer = new BufferObject(gl, _indexData.Length, BufferTargetARB.ElementArrayBuffer, false);\n _indexBuffer.SetData(_indexData, 0, _indexData.Length);\n\n // Initialize shader\n var vertSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"wheel_shader.vert\"));\n var fragSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"wheel_shader.frag\"));\n _shader = new Shader(_gl, vertSrc, fragSrc);\n\n // Setup VAO\n unsafe\n {\n _vao = new VertexArrayObject(gl, sizeof(VertexPositionTexture));\n _vao.Bind();\n }\n\n var location = _shader.GetAttribLocation(\"a_position\");\n _vao.VertexAttribPointer(location, 3, VertexAttribPointerType.Float, false, 0);\n\n location = _shader.GetAttribLocation(\"a_texCoords0\");\n _vao.VertexAttribPointer(location, 2, VertexAttribPointerType.Float, false, 12);\n\n ResizeSectionLabels();\n\n ApplyConfiguration(_config.CurrentValue);\n\n _config.OnChange(ApplyConfiguration);\n\n // Prevent wheel from spinning on creation\n _spinStartTime = -_spinDuration;\n }\n\n public void Update(float deltaTime)\n {\n _time += deltaTime;\n\n if ( IsSpinning )\n {\n var progress = Math.Min((_time - _spinStartTime) / _spinDuration, 1.0f);\n Progress = progress;\n }\n\n if ( IsSpinning && _time - _spinStartTime >= _spinDuration )\n {\n IsSpinning = false;\n _onSpinCompleteCallback?.Invoke((int)_targetSegment);\n _onSpinCompleteCallback = null;\n }\n\n UpdateVisibilityAnimation();\n }\n\n public void Render(float deltaTime)\n {\n lock (_applyingConfig)\n {\n // Skip rendering if wheel is disabled and not animating\n if ( !IsEnabled && CurrentAnimationState == AnimationState.Idle )\n {\n return;\n }\n\n var originalWheelSize = _wheelSize;\n _wheelSize *= _animationCurrentScale;\n\n Begin();\n DrawWheel();\n End();\n\n // Only render labels if wheel is sufficiently visible\n if ( _animationCurrentScale > 0.25f )\n {\n RenderSectionLabels();\n }\n\n _wheelSize = originalWheelSize;\n }\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n\n return;\n\n _vao.Dispose();\n _vertexBuffer.Dispose();\n _indexBuffer.Dispose();\n _shader.Dispose();\n _textRenderer.Dispose();\n }\n\n public string GetLabel(int index) { return _sectionLabels[index]; }\n\n public string[] GetLabels() { return _sectionLabels.ToArray(); }\n\n public void Spin(int targetSection, Action? onSpinComplete = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return;\n }\n\n _targetSegment = Math.Clamp(targetSection, 0, _numSections - 1);\n _startSegment = GetCurrentWheelPosition();\n _spinStartTime = _time;\n IsSpinning = true;\n _onSpinCompleteCallback = onSpinComplete;\n Progress = 0;\n }\n\n public int SpinRandom(Action? onSpinComplete = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return -1;\n }\n\n var target = Random.Shared.Next(_numSections);\n Spin(target, onSpinComplete);\n\n return target;\n }\n\n public Task SpinAsync(int? targetSection = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return Task.FromResult(-1);\n }\n\n var tcs = new TaskCompletionSource();\n var target = targetSection ?? Random.Shared.Next(_numSections);\n\n Spin(target, result => tcs.SetResult(result));\n\n return tcs.Task;\n }\n\n public void SetSectionLabels(string[] labels)\n {\n if ( labels.Length == 0 )\n {\n return;\n }\n\n if ( labels.Length != _numSections )\n {\n NumberOfSections = labels.Length;\n }\n\n for ( var i = 0; i < _numSections; i++ )\n {\n _sectionLabels[i] = labels[i];\n }\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n public void ConfigureTextStyle(\n bool radialText = true,\n Color? textColor = null,\n float scale = 1.0f,\n int strokeWidth = 2,\n bool useAdaptiveSize = true)\n {\n var color = textColor ?? Color.White;\n\n _textColor = new FSColor(color.R, color.G, color.B, color.A);\n _textScale = scale;\n _textStrokeWidth = strokeWidth;\n _radialTextOrientation = radialText;\n _useAdaptiveTextSize = useAdaptiveSize;\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n private static short[] GenerateIndexArray()\n {\n var result = new short[MAX_INDICES];\n for ( int i = 0,\n vi = 0; i < MAX_INDICES; i += 6, vi += 4 )\n {\n result[i] = (short)vi;\n result[i + 1] = (short)(vi + 1);\n result[i + 2] = (short)(vi + 2);\n result[i + 3] = (short)(vi + 1);\n result[i + 4] = (short)(vi + 3);\n result[i + 5] = (short)(vi + 2);\n }\n\n return result;\n }\n\n private void Begin()\n {\n _gl.Disable(EnableCap.DepthTest);\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n\n _shader.Use();\n UpdateShaderParameters();\n\n var projectionMatrix = Matrix4x4.CreateOrthographicOffCenter(0, _viewportWidth, _viewportHeight, 0, -1, 1);\n _shader.SetUniform(\"MatrixTransform\", projectionMatrix);\n\n _vao.Bind();\n _vertexBuffer.Bind();\n _indexBuffer.Bind();\n }\n\n private void End() { FlushBuffer(); }\n\n private unsafe void FlushBuffer()\n {\n if ( _vertexIndex == 0 )\n {\n return;\n }\n\n _vertexBuffer.SetData(_vertexData, 0, _vertexIndex);\n _gl.DrawElements(PrimitiveType.Triangles, (uint)(_vertexIndex * 6 / 4), DrawElementsType.UnsignedShort, null);\n _vertexIndex = 0;\n }\n\n private void DrawWheel()\n {\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var centerX = _position.X;\n var centerY = _position.Y;\n var cosR = (float)Math.Cos(Rotation);\n var sinR = (float)Math.Sin(Rotation);\n var left = centerX - radius;\n var right = centerX + radius;\n var top = centerY - radius;\n var bottom = centerY + radius;\n\n // Top-left vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(left, top, 0), centerX, centerY, cosR, sinR),\n new Vector2(0, 0));\n\n // Top-right vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(right, top, 0), centerX, centerY, cosR, sinR),\n new Vector2(1, 0));\n\n // Bottom-left vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(left, bottom, 0), centerX, centerY, cosR, sinR),\n new Vector2(0, 1));\n\n // Bottom-right vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(right, bottom, 0), centerX, centerY, cosR, sinR),\n new Vector2(1, 1));\n }\n\n private void RenderSectionLabels()\n {\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var innerRadius = radius * INNER_RADIUS_FACTOR;\n var centerRadius = radius * CENTER_RADIUS_FACTOR;\n var centerX = _position.X != 0 ? _position.X : _viewportWidth / 2.0f;\n var centerY = _position.Y != 0 ? _position.Y : _viewportHeight / 2.0f;\n var availableRadialSpace = innerRadius - centerRadius;\n var textRadius = centerRadius + availableRadialSpace * 0.5f;\n var currentRotation = GetCurrentWheelRotation();\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n\n if ( _useAdaptiveTextSize && _segmentFontSizes.Count != _numSections )\n {\n CalculateAllSegmentFontSizes();\n }\n\n _textRenderer.Begin();\n\n var fontSystem = _fontProvider.GetFontSystem(_config.CurrentValue.Font);\n\n // Reusable Vector2 for text position to avoid allocation in the loop\n var position = new Vector2();\n\n for ( var i = 0; i < _numSections; i++ )\n {\n if ( string.IsNullOrEmpty(_sectionLabels[i]) )\n {\n continue;\n }\n\n var fontSize = _useAdaptiveTextSize ? _segmentFontSizes[i] : _config.CurrentValue.FontSize;\n var segmentFont = fontSystem.GetFont(fontSize);\n\n var rotatedStartAngle = -currentRotation;\n var rotatedEndAngle = segmentAngle - currentRotation;\n var segmentCenter = (rotatedStartAngle + rotatedEndAngle) / 2.0f + (_numSections - 1 - i) * segmentAngle;\n\n // Position text\n var textX = centerX + textRadius * MathF.Cos(segmentCenter);\n var textY = centerY + textRadius * MathF.Sin(segmentCenter);\n var textSize = segmentFont.MeasureString(_sectionLabels[i]);\n\n // Update position instead of creating a new Vector2\n position.X = textX;\n position.Y = textY;\n\n // Calculate text rotation\n var textRotation = _radialTextOrientation\n ? MathF.Atan2(textY - centerY, textX - centerX)\n : 0.0f;\n\n // Draw text\n segmentFont.DrawText(\n _textRenderer,\n _sectionLabels[i],\n position,\n _textColor,\n textRotation,\n scale: new Vector2(_textScale),\n effect: FontSystemEffect.Stroked,\n effectAmount: _textStrokeWidth,\n origin: textSize / 2);\n }\n\n _textRenderer.End();\n }\n\n private Vector3 RotatePoint(Vector3 point, float centerX, float centerY, float cosR, float sinR)\n {\n var x = point.X - centerX;\n var y = point.Y - centerY;\n\n var newX = x * cosR - y * sinR + centerX;\n var newY = x * sinR + y * cosR + centerY;\n\n return new Vector3(newX, newY, point.Z);\n }\n\n private float GetCurrentWheelPosition()\n {\n if ( !IsSpinning )\n {\n return _targetSegment;\n }\n\n if ( Progress >= 1.0f )\n {\n IsSpinning = false;\n\n return _targetSegment;\n }\n\n var easedProgress = EaseOutQuint(Progress);\n\n var segmentDiff = (_targetSegment - _startSegment + _numSections) % _numSections;\n if ( segmentDiff > _numSections / 2.0f )\n {\n segmentDiff -= _numSections;\n }\n\n return (_startSegment + segmentDiff * easedProgress + _numSections) % _numSections;\n }\n\n private float GetCurrentWheelRotation()\n {\n var baseRotation = -Rotation;\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n\n var targetAngle = baseRotation + -(_targetSegment + 0.5f) * segmentAngle + MathF.PI * 1.5f;\n\n if ( !IsSpinning )\n {\n return targetAngle;\n }\n\n var startAngle = baseRotation + -(_startSegment + 0.5f) * segmentAngle + MathF.PI * 1.5f;\n var easedProgress = EaseOutQuint(Progress);\n\n var adjustedExtraAngle = targetAngle - startAngle;\n if ( adjustedExtraAngle > 0.0 )\n {\n adjustedExtraAngle -= 2.0f * MathF.PI;\n }\n\n var spinningAngle = startAngle + (adjustedExtraAngle - _minRotations * 2.0f * MathF.PI) * easedProgress;\n\n return spinningAngle;\n }\n\n private void UpdateShaderParameters()\n {\n _shader.SetUniform(\"u_targetSegment\", _targetSegment);\n _shader.SetUniform(\"u_startSegment\", _startSegment);\n _shader.SetUniform(\"u_spinDuration\", _spinDuration);\n _shader.SetUniform(\"u_minRotations\", _minRotations);\n _shader.SetUniform(\"u_spinStartTime\", _spinStartTime);\n _shader.SetUniform(\"u_time\", _time);\n _shader.SetUniform(\"u_numSlices\", (float)_numSections);\n\n float size = Math.Min(_viewportWidth, _viewportHeight);\n _shader.SetUniform(\"u_resolution\", size, size);\n }\n\n private int CalculateOptimalTextSizeForSegment(string label, int segmentIndex)\n {\n if ( string.IsNullOrEmpty(label) )\n {\n return 24;\n }\n\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var innerRadius = radius * INNER_RADIUS_FACTOR;\n var centerRadius = radius * CENTER_RADIUS_FACTOR;\n var availableRadialSpace = innerRadius - centerRadius;\n var textRadius = centerRadius + availableRadialSpace * 0.5f;\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n var maxWidth = 2.0f * textRadius * MathF.Sin(segmentAngle / 2.0f);\n\n var fontSystem = _fontProvider.GetFontSystem(_config.CurrentValue.Font);\n\n // Binary search for optimal font size\n var minFontSize = 1;\n var maxFontSize = 72;\n var optimalFontSize = _config.CurrentValue.FontSize;\n\n while ( minFontSize <= maxFontSize )\n {\n var currentFontSize = (minFontSize + maxFontSize) / 2;\n\n var testFont = fontSystem.GetFont(currentFontSize);\n var textSize = testFont.MeasureString(label);\n var scaledWidth = textSize.X * _textScale * _textSizeAdaptationFactor;\n\n if ( scaledWidth <= maxWidth * INNER_RADIUS_FACTOR )\n {\n optimalFontSize = currentFontSize;\n minFontSize = currentFontSize + 1;\n }\n else\n {\n maxFontSize = currentFontSize - 1;\n }\n }\n\n return optimalFontSize;\n }\n\n private void CalculateAllSegmentFontSizes()\n {\n if ( !_useAdaptiveTextSize )\n {\n return;\n }\n\n _segmentFontSizes.Clear();\n\n for ( var i = 0; i < _numSections; i++ )\n {\n _segmentFontSizes[i] = string.IsNullOrEmpty(_sectionLabels[i])\n ? 24\n : CalculateOptimalTextSizeForSegment(_sectionLabels[i], i);\n }\n }\n\n private void ResizeSectionLabels()\n {\n var newLabels = new string[_numSections];\n for ( var i = 0; i < _numSections; i++ )\n {\n newLabels[i] = i < _sectionLabels?.Length ? _sectionLabels[i] : $\"Section {i + 1}\";\n }\n\n _sectionLabels = newLabels;\n }\n\n private static float EaseOutQuint(float t) { return 1.0f - MathF.Pow(1.0f - t, 5); }\n\n private void ApplyConfiguration(RouletteWheelOptions options)\n {\n lock (_applyingConfig)\n {\n // Apply text configuration\n _radialTextOrientation = options.RadialTextOrientation;\n _textScale = options.TextScale;\n _textStrokeWidth = options.TextStroke;\n _useAdaptiveTextSize = options.AdaptiveText;\n\n if ( !string.IsNullOrEmpty(options.TextColor) )\n {\n var color = ColorTranslator.FromHtml(options.TextColor);\n _textColor = new FSColor(color.R, color.G, color.B, color.A);\n }\n\n // Apply section labels\n if ( options.SectionLabels?.Length > 0 )\n {\n SetSectionLabels(options.SectionLabels);\n }\n\n // Apply spin parameters\n _spinDuration = Math.Max(options.SpinDuration, 0.1f);\n _minRotations = Math.Max(options.MinRotations, 1.0f);\n\n // Apply wheel size\n _wheelSize = Math.Clamp(options.WheelSizePercentage, 0.1f, 1.0f);\n\n // Apply positioning\n if ( !string.IsNullOrEmpty(options.PositionMode) )\n {\n switch ( options.PositionMode )\n {\n case \"Absolute\":\n _positionMode = PositionMode.Absolute;\n SetAbsolutePosition(options.AbsolutePositionX, options.AbsolutePositionY);\n\n break;\n case \"Percentage\":\n _positionMode = PositionMode.Percentage;\n PositionByPercentage(options.PositionXPercentage, options.PositionYPercentage);\n\n break;\n case \"Anchored\":\n _positionMode = PositionMode.Anchored;\n if ( Enum.TryParse(options.ViewportAnchor, out ViewportAnchor anchor) )\n {\n PositionAt(anchor, new Vector2(options.AnchorOffsetX, options.AnchorOffsetY));\n }\n else\n {\n PositionAt(ViewportAnchor.Center);\n }\n\n break;\n }\n }\n\n // Apply rotation\n Rotation = options.RotationDegrees * MathF.PI / 180;\n\n // Handle viewport size changes\n var viewportChanged = _viewportWidth != options.Width || _viewportHeight != options.Height;\n if ( viewportChanged )\n {\n _viewportWidth = options.Width;\n _viewportHeight = options.Height;\n\n // Update text renderer viewport\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n\n // Update position based on mode\n switch ( _positionMode )\n {\n case PositionMode.Anchored:\n UpdatePositionFromAnchor();\n\n break;\n case PositionMode.Percentage:\n UpdatePositionFromPercentage();\n\n break;\n }\n }\n\n // Apply enabled state (if changed)\n if ( options.Enabled != IsEnabled )\n {\n if ( options.Enabled )\n {\n Enable();\n }\n else\n {\n Disable();\n }\n }\n\n // Recalculate font sizes if needed (after all other changes)\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/TextExtensions.cs", "using System.Text;\n\nnamespace PersonaEngine.Lib.Utils;\n\npublic static class TextExtensions\n{\n public static string SafeNormalizeUnicode(this string input)\n {\n if ( string.IsNullOrEmpty(input) )\n {\n return input;\n }\n\n try\n {\n return input.Normalize(NormalizationForm.FormKC);\n }\n catch (ArgumentException)\n {\n // Failed,try to remove invalid unicode chars\n }\n\n // Remove invalid characters\n var result = new StringBuilder(input.Length);\n var currentPos = 0;\n\n while ( currentPos < input.Length )\n {\n var invalidPos = FindInvalidCharIndex(input[currentPos..]);\n if ( invalidPos == -1 )\n {\n // No more invalid characters found, add the rest\n result.Append(input.AsSpan(currentPos));\n\n break;\n }\n\n // Add the valid portion before the invalid character\n if ( invalidPos > 0 )\n {\n result.Append(input.AsSpan(currentPos, invalidPos));\n }\n\n // Skip the invalid character (or pair)\n if ( input[currentPos + invalidPos] >= 0xD800 && input[currentPos + invalidPos] <= 0xDBFF )\n {\n // Skip surrogate pair\n currentPos += invalidPos + 2;\n }\n else\n {\n // Skip single character\n currentPos += invalidPos + 1;\n }\n }\n\n // Now normalize the cleaned string\n return result.ToString().Normalize(NormalizationForm.FormKC);\n }\n\n /// \n /// Searches invalid charachters (non-chars defined in Unicode standard and invalid surrogate pairs) in a string\n /// \n /// the string to search for invalid chars \n /// the index of the first bad char or -1 if no bad char is found\n private static int FindInvalidCharIndex(string aString)\n {\n for ( var i = 0; i < aString.Length; i++ )\n {\n int ch = aString[i];\n if ( ch < 0xD800 ) // char is up to first high surrogate\n {\n continue;\n }\n\n if ( ch is >= 0xD800 and <= 0xDBFF )\n {\n // found high surrogate -> check surrogate pair\n i++;\n if ( i == aString.Length )\n {\n // last char is high surrogate, so it is missing its pair\n return i - 1;\n }\n\n int chlow = aString[i];\n if ( chlow is < 0xDC00 or > 0xDFFF )\n {\n // did not found a low surrogate after the high surrogate\n return i - 1;\n }\n\n // convert to UTF32 - like in Char.ConvertToUtf32(highSurrogate, lowSurrogate)\n ch = (ch - 0xD800) * 0x400 + (chlow - 0xDC00) + 0x10000;\n if ( ch > 0x10FFFF )\n {\n // invalid Unicode code point - maximum excedeed\n return i;\n }\n\n if ( (ch & 0xFFFE) == 0xFFFE )\n {\n // other non-char found\n return i;\n }\n\n // found a good surrogate pair\n continue;\n }\n\n if ( ch is >= 0xDC00 and <= 0xDFFF )\n {\n // unexpected low surrogate\n return i;\n }\n\n if ( ch is >= 0xFDD0 and <= 0xFDEF )\n {\n // non-chars are considered invalid by System.Text.Encoding.GetBytes() and String.Normalize()\n return i;\n }\n\n if ( (ch & 0xFFFE) == 0xFFFE )\n {\n // other non-char found\n return i;\n }\n }\n\n return -1;\n }\n\n public static int GetWordCount(this string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n return 0;\n }\n\n var wordCount = 0;\n var inWord = false;\n\n foreach ( var c in text )\n {\n if ( char.IsWhiteSpace(c) )\n {\n inWord = false;\n }\n else\n {\n if ( inWord )\n {\n continue;\n }\n\n wordCount++;\n inWord = true;\n }\n }\n\n return wordCount;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TextProcessor.cs", "using Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of text processing for TTS\n/// \npublic class TextProcessor : ITextProcessor\n{\n private readonly ILogger _logger;\n\n private readonly ITextNormalizer _normalizer;\n\n private readonly ISentenceSegmenter _segmenter;\n\n public TextProcessor(\n ITextNormalizer normalizer,\n ISentenceSegmenter segmenter,\n ILogger logger)\n {\n _normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer));\n _segmenter = segmenter ?? throw new ArgumentNullException(nameof(segmenter));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n /// \n /// Processes text for TTS by normalizing and segmenting into sentences\n /// \n public Task ProcessAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n _logger.LogInformation(\"Empty text received for processing\");\n\n return Task.FromResult(new ProcessedText(string.Empty, Array.Empty()));\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n // Normalize the text\n var normalizedText = _normalizer.Normalize(text);\n\n if ( string.IsNullOrEmpty(normalizedText) )\n {\n _logger.LogWarning(\"Text normalization resulted in empty text\");\n\n return Task.FromResult(new ProcessedText(string.Empty, Array.Empty()));\n }\n\n // Segment into sentences\n var sentences = _segmenter.Segment(normalizedText);\n\n _logger.LogDebug(\"Processed text into {SentenceCount} sentences\", sentences.Count);\n\n return Task.FromResult(new ProcessedText(normalizedText, sentences));\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error processing text\");\n\n throw;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismExpressionMotion.cs", "using System.Text.Json.Nodes;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// 表情のモーションクラス。\n/// \npublic class CubismExpressionMotion : ACubismMotion\n{\n /// \n /// 加算適用の初期値\n /// \n public const float DefaultAdditiveValue = 0.0f;\n\n /// \n /// 乗算適用の初期値\n /// \n public const float DefaultMultiplyValue = 1.0f;\n\n public const string ExpressionKeyFadeIn = \"FadeInTime\";\n\n public const string ExpressionKeyFadeOut = \"FadeOutTime\";\n\n public const string ExpressionKeyParameters = \"Parameters\";\n\n public const string ExpressionKeyId = \"Id\";\n\n public const string ExpressionKeyValue = \"Value\";\n\n public const string ExpressionKeyBlend = \"Blend\";\n\n public const string BlendValueAdd = \"Add\";\n\n public const string BlendValueMultiply = \"Multiply\";\n\n public const string BlendValueOverwrite = \"Overwrite\";\n\n public const float DefaultFadeTime = 1.0f;\n\n /// \n /// インスタンスを作成する。\n /// \n /// expファイルが読み込まれているバッファ\n public CubismExpressionMotion(string buf)\n {\n using var stream = File.Open(buf, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonNode.Parse(stream) ?? throw new Exception(\"Load ExpressionMotion error\");\n var json = obj.AsObject();\n\n FadeInSeconds = json.ContainsKey(ExpressionKeyFadeIn)\n ? (float)json[ExpressionKeyFadeIn]!\n : DefaultFadeTime; // フェードイン\n\n FadeOutSeconds = json.ContainsKey(ExpressionKeyFadeOut)\n ? (float)json[ExpressionKeyFadeOut]!\n : DefaultFadeTime; // フェードアウト\n\n if ( FadeInSeconds < 0.0f )\n {\n FadeInSeconds = DefaultFadeTime;\n }\n\n if ( FadeOutSeconds < 0.0f )\n {\n FadeOutSeconds = DefaultFadeTime;\n }\n\n // 各パラメータについて\n var list = json[ExpressionKeyParameters]!;\n var parameterCount = list.AsArray().Count;\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n var param = list[i]!;\n var parameterId = CubismFramework.CubismIdManager.GetId(param[ExpressionKeyId]!.ToString()); // パラメータID\n var value = (float)param[ExpressionKeyValue]!; // 値\n\n // 計算方法の設定\n ExpressionBlendType blendType;\n var type = param[ExpressionKeyBlend]?.ToString();\n if ( type == null || type == BlendValueAdd )\n {\n blendType = ExpressionBlendType.Add;\n }\n else if ( type == BlendValueMultiply )\n {\n blendType = ExpressionBlendType.Multiply;\n }\n else if ( type == BlendValueOverwrite )\n {\n blendType = ExpressionBlendType.Overwrite;\n }\n else\n {\n // その他 仕様にない値を設定したときは加算モードにすることで復旧\n blendType = ExpressionBlendType.Add;\n }\n\n // 設定オブジェクトを作成してリストに追加する\n Parameters.Add(new ExpressionParameter { ParameterId = parameterId, BlendType = blendType, Value = value });\n }\n }\n\n /// \n /// 表情のパラメータ情報リスト\n /// \n public List Parameters { get; init; } = [];\n\n /// \n /// 表情のフェードのウェイト値\n /// \n [Obsolete(\"CubismExpressionMotion._fadeWeightが削除予定のため非推奨\\nCubismExpressionMotionManager.getFadeWeight(int index) を使用してください。\")]\n public float FadeWeight { get; private set; }\n\n public override void DoUpdateParameters(CubismModel model, float userTimeSeconds, float weight, CubismMotionQueueEntry motionQueueEntry)\n {\n foreach ( var item in Parameters )\n {\n switch ( item.BlendType )\n {\n case ExpressionBlendType.Add:\n {\n model.AddParameterValue(item.ParameterId, item.Value, weight); // 相対変化 加算\n\n break;\n }\n case ExpressionBlendType.Multiply:\n {\n model.MultiplyParameterValue(item.ParameterId, item.Value, weight); // 相対変化 乗算\n\n break;\n }\n case ExpressionBlendType.Overwrite:\n {\n model.SetParameterValue(item.ParameterId, item.Value, weight); // 絶対変化 上書き\n\n break;\n }\n }\n }\n }\n\n /// \n /// モデルの表情に関するパラメータを計算する。\n /// \n /// 対象のモデル\n /// 対象のモデル\n /// CubismMotionQueueManagerで管理されているモーション\n /// モデルに適用する各パラメータの値\n /// 表情のインデックス\n public void CalculateExpressionParameters(CubismModel model, float userTimeSeconds, CubismMotionQueueEntry? motionQueueEntry,\n List? expressionParameterValues, int expressionIndex, float fadeWeight)\n {\n if ( motionQueueEntry == null || expressionParameterValues == null )\n {\n return;\n }\n\n if ( !motionQueueEntry.Available )\n {\n return;\n }\n\n // CubismExpressionMotion._fadeWeight は廃止予定です。\n // 互換性のために処理は残りますが、実際には使用しておりません。\n FadeWeight = UpdateFadeWeight(motionQueueEntry, userTimeSeconds);\n\n // モデルに適用する値を計算\n for ( var i = 0; i < expressionParameterValues.Count; ++i )\n {\n var expressionParameterValue = expressionParameterValues[i];\n\n if ( expressionParameterValue.ParameterId == null )\n {\n continue;\n }\n\n var currentParameterValue = expressionParameterValue.OverwriteValue =\n model.GetParameterValue(expressionParameterValue.ParameterId);\n\n var expressionParameters = Parameters;\n var parameterIndex = -1;\n for ( var j = 0; j < expressionParameters.Count; ++j )\n {\n if ( expressionParameterValue.ParameterId != expressionParameters[j].ParameterId )\n {\n continue;\n }\n\n parameterIndex = j;\n\n break;\n }\n\n // 再生中のExpressionが参照していないパラメータは初期値を適用\n if ( parameterIndex < 0 )\n {\n if ( expressionIndex == 0 )\n {\n expressionParameterValues[i].AdditiveValue = DefaultAdditiveValue;\n\n expressionParameterValues[i].MultiplyValue = DefaultMultiplyValue;\n\n expressionParameterValues[i].OverwriteValue = currentParameterValue;\n }\n else\n {\n expressionParameterValues[i].AdditiveValue =\n CalculateValue(expressionParameterValue.AdditiveValue, DefaultAdditiveValue, fadeWeight);\n\n expressionParameterValues[i].MultiplyValue =\n CalculateValue(expressionParameterValue.MultiplyValue, DefaultMultiplyValue, fadeWeight);\n\n expressionParameterValues[i].OverwriteValue =\n CalculateValue(expressionParameterValue.OverwriteValue, currentParameterValue, fadeWeight);\n }\n\n continue;\n }\n\n // 値を計算\n var value = expressionParameters[parameterIndex].Value;\n float newAdditiveValue,\n newMultiplyValue,\n newSetValue;\n\n switch ( expressionParameters[parameterIndex].BlendType )\n {\n case ExpressionBlendType.Add:\n newAdditiveValue = value;\n newMultiplyValue = DefaultMultiplyValue;\n newSetValue = currentParameterValue;\n\n break;\n case ExpressionBlendType.Multiply:\n newAdditiveValue = DefaultAdditiveValue;\n newMultiplyValue = value;\n newSetValue = currentParameterValue;\n\n break;\n case ExpressionBlendType.Overwrite:\n newAdditiveValue = DefaultAdditiveValue;\n newMultiplyValue = DefaultMultiplyValue;\n newSetValue = value;\n\n break;\n default:\n return;\n }\n\n if ( expressionIndex == 0 )\n {\n expressionParameterValues[i].AdditiveValue = newAdditiveValue;\n expressionParameterValues[i].MultiplyValue = newMultiplyValue;\n expressionParameterValues[i].OverwriteValue = newSetValue;\n }\n else\n {\n expressionParameterValues[i].AdditiveValue = expressionParameterValue.AdditiveValue * (1.0f - FadeWeight) + newAdditiveValue * FadeWeight;\n expressionParameterValues[i].MultiplyValue = expressionParameterValue.MultiplyValue * (1.0f - FadeWeight) + newMultiplyValue * FadeWeight;\n expressionParameterValues[i].OverwriteValue = expressionParameterValue.OverwriteValue * (1.0f - FadeWeight) + newSetValue * FadeWeight;\n }\n }\n }\n\n private float CalculateValue(float source, float destination, float fadeWeight) { return source * (1.0f - fadeWeight) + destination * fadeWeight; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITtsEngine.cs", "using System.Threading.Channels;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic interface ITtsEngine : IDisposable\n{\n Task SynthesizeStreamingAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default\n );\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/IChatEngine.cs", "using System.Threading.Channels;\n\nusing Microsoft.SemanticKernel;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic record VisualChatMessage(string Query, ReadOnlyMemory ImageData);\n\npublic interface IChatEngine : IDisposable\n{\n Task GetStreamingChatResponseAsync(\n IConversationContext context,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n PromptExecutionSettings? executionSettings = null,\n CancellationToken cancellationToken = default);\n}\n\npublic interface IVisualChatEngine : IDisposable\n{\n IAsyncEnumerable GetStreamingChatResponseAsync(\n VisualChatMessage userInput,\n PromptExecutionSettings? executionSettings = null,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IStreamingAudioPlayer.cs", "// using System.Threading.Channels;\n//\n// using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n// using PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n// using PersonaEngine.Lib.TTS.Synthesis;\n//\n// namespace PersonaEngine.Lib.Audio.Player;\n//\n// public class AudioPlaybackEventArgs : EventArgs\n// {\n// public AudioPlaybackEventArgs(AudioSegment segment) { Segment = segment; }\n//\n// public AudioSegment Segment { get; }\n// }\n//\n// public interface IStreamingAudioPlayer : IAsyncDisposable\n// {\n// Task StartPlaybackAsync(IAsyncEnumerable audioSegments, CancellationToken cancellationToken = default);\n//\n// public Task StopPlaybackAsync();\n// }\n//\n// public interface IStreamingAudioPlayerHost\n// {\n// float CurrentTime { get; }\n//\n// PlayerState State { get; }\n//\n// event EventHandler? OnPlaybackStarted;\n//\n// event EventHandler? OnPlaybackCompleted;\n// }\n//\n// public interface IAggregatedStreamingAudioPlayer : IStreamingAudioPlayer\n// {\n// IReadOnlyCollection Players { get; }\n//\n// void AddPlayer(IStreamingAudioPlayer player);\n//\n// bool RemovePlayer(IStreamingAudioPlayer player);\n// }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysics.cs", "using System.Numerics;\nusing System.Text.Json;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// 物理演算のクラス。\n/// \npublic class CubismPhysics\n{\n /// physics types tags.\n public const string PhysicsTypeTagX = \"X\";\n\n public const string PhysicsTypeTagY = \"Y\";\n\n public const string PhysicsTypeTagAngle = \"Angle\";\n\n /// Constant of air resistance.\n public const float AirResistance = 5.0f;\n\n /// Constant of maximum weight of input and output ratio.\n public const float MaximumWeight = 100.0f;\n\n /// Constant of threshold of movement.\n public const float MovementThreshold = 0.001f;\n\n /// Constant of maximum allowed delta time\n public const float MaxDeltaTime = 5.0f;\n\n /// \n /// 最新の振り子計算の結果\n /// \n private readonly List _currentRigOutputs = [];\n\n /// \n /// 物理演算のデータ\n /// \n private readonly CubismPhysicsRig _physicsRig;\n\n /// \n /// 一つ前の振り子計算の結果\n /// \n private readonly List _previousRigOutputs = [];\n\n /// \n /// 物理演算が処理していない時間\n /// \n private float _currentRemainTime;\n\n /// \n /// Evaluateで利用するパラメータのキャッシュs\n /// \n private float[] _parameterCaches = [];\n\n /// \n /// UpdateParticlesが動くときの入力をキャッシュ\n /// \n private float[] _parameterInputCaches = [];\n\n /// \n /// 重力方向\n /// \n public Vector2 Gravity;\n\n /// \n /// 風の方向\n /// \n public Vector2 Wind;\n\n /// \n /// インスタンスを作成する。\n /// \n /// physics3.jsonが読み込まれいるバッファ\n public CubismPhysics(string buffer)\n {\n // set default options.\n Gravity.Y = -1.0f;\n Gravity.X = 0;\n Wind.X = 0;\n Wind.Y = 0;\n _currentRemainTime = 0.0f;\n\n using var stream = File.Open(buffer, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismPhysicsObjContext.Default.CubismPhysicsObj)\n ?? throw new Exception(\"Load Physics error\");\n\n _physicsRig = new CubismPhysicsRig {\n Gravity = obj.Meta.EffectiveForces.Gravity,\n Wind = obj.Meta.EffectiveForces.Wind,\n SubRigCount = obj.Meta.PhysicsSettingCount,\n Fps = obj.Meta.Fps,\n Settings = new CubismPhysicsSubRig[obj.Meta.PhysicsSettingCount],\n Inputs = new CubismPhysicsInput[obj.Meta.TotalInputCount],\n Outputs = new CubismPhysicsOutput[obj.Meta.TotalOutputCount],\n Particles = new CubismPhysicsParticle[obj.Meta.VertexCount]\n };\n\n _currentRigOutputs.Clear();\n _previousRigOutputs.Clear();\n\n int inputIndex = 0,\n outputIndex = 0,\n particleIndex = 0;\n\n for ( var i = 0; i < _physicsRig.Settings.Length; ++i )\n {\n var set = obj.PhysicsSettings[i];\n _physicsRig.Settings[i] = new CubismPhysicsSubRig {\n NormalizationPosition = new CubismPhysicsNormalization { Minimum = set.Normalization.Position.Minimum, Maximum = set.Normalization.Position.Maximum, Default = set.Normalization.Position.Default },\n NormalizationAngle = new CubismPhysicsNormalization { Minimum = set.Normalization.Angle.Minimum, Maximum = set.Normalization.Angle.Maximum, Default = set.Normalization.Angle.Default },\n // Input\n InputCount = set.Input.Count,\n BaseInputIndex = inputIndex\n };\n\n for ( var j = 0; j < _physicsRig.Settings[i].InputCount; ++j )\n {\n var input = set.Input[j];\n _physicsRig.Inputs[inputIndex + j] = new CubismPhysicsInput { SourceParameterIndex = -1, Weight = input.Weight, Reflect = input.Reflect, Source = new CubismPhysicsParameter { TargetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter, Id = input.Source.Id } };\n\n if ( input.Type == PhysicsTypeTagX )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_X;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputTranslationXFromNormalizedParameterValue;\n }\n else if ( input.Type == PhysicsTypeTagY )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Y;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputTranslationYFromNormalizedParameterValue;\n }\n else if ( input.Type == PhysicsTypeTagAngle )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Angle;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputAngleFromNormalizedParameterValue;\n }\n }\n\n inputIndex += _physicsRig.Settings[i].InputCount;\n\n // Output\n _physicsRig.Settings[i].OutputCount = set.Output.Count;\n _physicsRig.Settings[i].BaseOutputIndex = outputIndex;\n\n _currentRigOutputs.Add(new float[set.Output.Count]);\n _previousRigOutputs.Add(new float[set.Output.Count]);\n\n for ( var j = 0; j < _physicsRig.Settings[i].OutputCount; ++j )\n {\n var output = set.Output[j];\n _physicsRig.Outputs[outputIndex + j] = new CubismPhysicsOutput {\n DestinationParameterIndex = -1,\n VertexIndex = output.VertexIndex,\n AngleScale = output.Scale,\n Weight = output.Weight,\n Destination = new CubismPhysicsParameter { TargetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter, Id = output.Destination.Id },\n Reflect = output.Reflect\n };\n\n var key = output.Type;\n if ( key == PhysicsTypeTagX )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_X;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputTranslationX;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleTranslationX;\n }\n else if ( key == PhysicsTypeTagY )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Y;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputTranslationY;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleTranslationY;\n }\n else if ( key == PhysicsTypeTagAngle )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Angle;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputAngle;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleAngle;\n }\n }\n\n outputIndex += _physicsRig.Settings[i].OutputCount;\n\n // Particle\n _physicsRig.Settings[i].ParticleCount = set.Vertices.Count;\n _physicsRig.Settings[i].BaseParticleIndex = particleIndex;\n for ( var j = 0; j < _physicsRig.Settings[i].ParticleCount; ++j )\n {\n var par = set.Vertices[j];\n _physicsRig.Particles[particleIndex + j] = new CubismPhysicsParticle {\n Mobility = par.Mobility,\n Delay = par.Delay,\n Acceleration = par.Acceleration,\n Radius = par.Radius,\n Position = par.Position\n };\n }\n\n particleIndex += _physicsRig.Settings[i].ParticleCount;\n }\n\n Initialize();\n\n _physicsRig.Gravity.Y = 0;\n }\n\n /// \n /// パラメータをリセットする。\n /// \n public void Reset()\n {\n // set default options.\n Gravity.Y = -1.0f;\n Gravity.X = 0.0f;\n Wind.X = 0.0f;\n Wind.Y = 0.0f;\n\n _physicsRig.Gravity.X = 0.0f;\n _physicsRig.Gravity.Y = 0.0f;\n _physicsRig.Wind.X = 0.0f;\n _physicsRig.Wind.Y = 0.0f;\n\n Initialize();\n }\n\n /// \n /// 現在のパラメータ値で物理演算が安定化する状態を演算する。\n /// \n /// 物理演算の結果を適用するモデル\n public unsafe void Stabilization(CubismModel model)\n {\n float totalAngle;\n float weight;\n float radAngle;\n float outputValue;\n Vector2 totalTranslation;\n int i,\n settingIndex,\n particleIndex;\n\n float* parameterValues;\n float* parameterMaximumValues;\n float* parameterMinimumValues;\n float* parameterDefaultValues;\n\n parameterValues = CubismCore.GetParameterValues(model.Model);\n parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n parameterDefaultValues = CubismCore.GetParameterDefaultValues(model.Model);\n\n if ( _parameterCaches.Length < model.GetParameterCount() )\n {\n _parameterCaches = new float[model.GetParameterCount()];\n }\n\n if ( _parameterInputCaches.Length < model.GetParameterCount() )\n {\n _parameterInputCaches = new float[model.GetParameterCount()];\n }\n\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterCaches[j] = parameterValues[j];\n _parameterInputCaches[j] = parameterValues[j];\n }\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n totalAngle = 0.0f;\n totalTranslation.X = 0.0f;\n totalTranslation.Y = 0.0f;\n\n var currentSetting = _physicsRig.Settings[settingIndex];\n var currentInputIndex = currentSetting.BaseInputIndex;\n var currentOutputIndex = currentSetting.BaseOutputIndex;\n var currentParticleIndex = currentSetting.BaseParticleIndex;\n\n // Load input parameters\n for ( i = 0; i < currentSetting.InputCount; ++i )\n {\n weight = _physicsRig.Inputs[i + currentInputIndex].Weight / MaximumWeight;\n\n if ( _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex == -1 )\n {\n _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex = model.GetParameterIndex(_physicsRig.Inputs[i + currentInputIndex].Source.Id);\n }\n\n _physicsRig.Inputs[i + currentInputIndex].GetNormalizedParameterValue(\n ref totalTranslation,\n ref totalAngle,\n parameterValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMinimumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMaximumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterDefaultValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n currentSetting.NormalizationPosition,\n currentSetting.NormalizationAngle,\n _physicsRig.Inputs[i + currentInputIndex].Reflect,\n weight\n );\n\n _parameterCaches[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex] =\n parameterValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex];\n }\n\n radAngle = CubismMath.DegreesToRadian(-totalAngle);\n\n totalTranslation.X = totalTranslation.X * MathF.Cos(radAngle) - totalTranslation.Y * MathF.Sin(radAngle);\n totalTranslation.Y = totalTranslation.X * MathF.Sin(radAngle) + totalTranslation.Y * MathF.Cos(radAngle);\n\n // Calculate particles position.\n UpdateParticlesForStabilization(\n _physicsRig.Particles,\n currentSetting.BaseParticleIndex,\n currentSetting.ParticleCount,\n totalTranslation,\n totalAngle,\n Wind,\n MovementThreshold * currentSetting.NormalizationPosition.Maximum\n );\n\n // Update output parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n particleIndex = _physicsRig.Outputs[i + currentOutputIndex].VertexIndex;\n\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex = model.GetParameterIndex(\n _physicsRig.Outputs[i + currentOutputIndex].Destination.Id);\n }\n\n if ( particleIndex < 1 || particleIndex >= currentSetting.ParticleCount )\n {\n continue;\n }\n\n Vector2 translation = new() { X = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.X - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.X, Y = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.Y - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.Y };\n\n outputValue = _physicsRig.Outputs[i + currentOutputIndex].GetValue(\n translation,\n _physicsRig.Particles,\n currentParticleIndex,\n particleIndex,\n _physicsRig.Outputs[i + currentOutputIndex].Reflect,\n Gravity\n );\n\n _currentRigOutputs[settingIndex][i] = outputValue;\n _previousRigOutputs[settingIndex][i] = outputValue;\n\n UpdateOutputParameterValue(\n ref parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n outputValue,\n _physicsRig.Outputs[i + currentOutputIndex]);\n\n _parameterCaches[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex] = parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex];\n }\n }\n }\n\n /// \n /// 物理演算を評価する。\n /// Pendulum interpolation weights\n /// 振り子の計算結果は保存され、パラメータへの出力は保存された前回の結果で補間されます。\n /// The result of the pendulum calculation is saved and\n /// the output to the parameters is interpolated with the saved previous result of the pendulum calculation.\n /// 図で示すと[1]と[2]で補間されます。\n /// The figure shows the interpolation between [1] and [2].\n /// 補間の重みは最新の振り子計算タイミングと次回のタイミングの間で見た現在時間で決定する。\n /// The weight of the interpolation are determined by the current time seen between\n /// the latest pendulum calculation timing and the next timing.\n /// 図で示すと[2]と[4]の間でみた(3)の位置の重みになる。\n /// Figure shows the weight of position (3) as seen between [2] and [4].\n /// 解釈として振り子計算のタイミングと重み計算のタイミングがズレる。\n /// As an interpretation, the pendulum calculation and weights are misaligned.\n /// physics3.jsonにFPS情報が存在しない場合は常に前の振り子状態で設定される。\n /// If there is no FPS information in physics3.json, it is always set in the previous pendulum state.\n /// この仕様は補間範囲を逸脱したことが原因の震えたような見た目を回避を目的にしている。\n /// The purpose of this specification is to avoid the quivering appearance caused by deviations from the interpolation\n /// range.\n /// ------------ time -------------->\n /// |+++++|------|\n /// <- weight\n /// ==[1]====#=====[2]---(3)----(4)\n /// ^ output contents\n /// \n /// 1 :_previousRigOutputs\n /// 2 :_currentRigOutputs\n /// 3 :_currentRemainTime ( now rendering)\n /// 4 :next particles timing\n /// \n /// @ param model\n /// @ param deltaTimeSeconds rendering delta time.\n /// \n /// 物理演算の結果を適用するモデル\n /// デルタ時間[秒]\n public unsafe void Evaluate(CubismModel model, float deltaTimeSeconds)\n {\n float totalAngle;\n float weight;\n float radAngle;\n float outputValue;\n Vector2 totalTranslation;\n int i,\n settingIndex,\n particleIndex;\n\n if ( 0.0f >= deltaTimeSeconds )\n {\n return;\n }\n\n float physicsDeltaTime;\n _currentRemainTime += deltaTimeSeconds;\n if ( _currentRemainTime > MaxDeltaTime )\n {\n _currentRemainTime = 0.0f;\n }\n\n var parameterValues = CubismCore.GetParameterValues(model.Model);\n var parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n var parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n var parameterDefaultValues = CubismCore.GetParameterDefaultValues(model.Model);\n\n if ( _parameterCaches.Length < model.GetParameterCount() )\n {\n _parameterCaches = new float[model.GetParameterCount()];\n }\n\n if ( _parameterInputCaches.Length < model.GetParameterCount() )\n {\n _parameterInputCaches = new float[model.GetParameterCount()];\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterInputCaches[j] = parameterValues[j];\n }\n }\n\n if ( _physicsRig.Fps > 0.0f )\n {\n physicsDeltaTime = 1.0f / _physicsRig.Fps;\n }\n else\n {\n physicsDeltaTime = deltaTimeSeconds;\n }\n\n CubismPhysicsSubRig currentSetting;\n CubismPhysicsOutput currentOutputs;\n\n while ( _currentRemainTime >= physicsDeltaTime )\n {\n // copyRigOutputs _currentRigOutputs to _previousRigOutputs\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n if ( currentSetting.BaseOutputIndex >= _physicsRig.Outputs.Length )\n {\n continue;\n }\n\n currentOutputs = _physicsRig.Outputs[currentSetting.BaseOutputIndex];\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n _previousRigOutputs[settingIndex][i] = _currentRigOutputs[settingIndex][i];\n }\n }\n\n // 入力キャッシュとパラメータで線形補間してUpdateParticlesするタイミングでの入力を計算する。\n // Calculate the input at the timing to UpdateParticles by linear interpolation with the _parameterInputCaches and parameterValues.\n // _parameterCachesはグループ間での値の伝搬の役割があるので_parameterInputCachesとの分離が必要。\n // _parameterCaches needs to be separated from _parameterInputCaches because of its role in propagating values between groups.\n var inputWeight = physicsDeltaTime / _currentRemainTime;\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterCaches[j] = _parameterInputCaches[j] * (1.0f - inputWeight) + parameterValues[j] * inputWeight;\n _parameterInputCaches[j] = _parameterCaches[j];\n }\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n totalAngle = 0.0f;\n totalTranslation.X = 0.0f;\n totalTranslation.Y = 0.0f;\n currentSetting = _physicsRig.Settings[settingIndex];\n var currentInputIndex = currentSetting.BaseInputIndex;\n var currentOutputIndex = currentSetting.BaseOutputIndex;\n var currentParticleIndex = currentSetting.BaseParticleIndex;\n\n // Load input parameters.\n for ( i = 0; i < currentSetting.InputCount; ++i )\n {\n weight = _physicsRig.Inputs[i + currentInputIndex].Weight / MaximumWeight;\n\n if ( _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex == -1 )\n {\n _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex = model.GetParameterIndex(_physicsRig.Inputs[i + currentInputIndex].Source.Id);\n }\n\n _physicsRig.Inputs[i + currentInputIndex].GetNormalizedParameterValue(\n ref totalTranslation,\n ref totalAngle,\n _parameterCaches[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMinimumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMaximumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterDefaultValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n currentSetting.NormalizationPosition,\n currentSetting.NormalizationAngle,\n _physicsRig.Inputs[i + currentInputIndex].Reflect,\n weight\n );\n }\n\n radAngle = CubismMath.DegreesToRadian(-totalAngle);\n\n totalTranslation.X = totalTranslation.X * MathF.Cos(radAngle) - totalTranslation.Y * MathF.Sin(radAngle);\n totalTranslation.Y = totalTranslation.X * MathF.Sin(radAngle) + totalTranslation.Y * MathF.Cos(radAngle);\n\n // Calculate particles position.\n UpdateParticles(\n _physicsRig.Particles,\n currentParticleIndex,\n currentSetting.ParticleCount,\n totalTranslation,\n totalAngle,\n Wind,\n MovementThreshold * currentSetting.NormalizationPosition.Maximum,\n physicsDeltaTime,\n AirResistance\n );\n\n // Update output parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n particleIndex = _physicsRig.Outputs[i + currentOutputIndex].VertexIndex;\n\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex = model.GetParameterIndex(_physicsRig.Outputs[i + currentOutputIndex].Destination.Id);\n }\n\n if ( particleIndex < 1 || particleIndex >= currentSetting.ParticleCount )\n {\n continue;\n }\n\n Vector2 translation;\n translation.X = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.X - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.X;\n translation.Y = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.Y - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.Y;\n\n outputValue = _physicsRig.Outputs[i + currentOutputIndex].GetValue(\n translation,\n _physicsRig.Particles,\n currentParticleIndex,\n particleIndex,\n _physicsRig.Outputs[i + currentOutputIndex].Reflect,\n Gravity\n );\n\n _currentRigOutputs[settingIndex][i] = outputValue;\n\n UpdateOutputParameterValue(\n ref _parameterCaches[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n outputValue,\n _physicsRig.Outputs[i + currentOutputIndex]);\n }\n }\n\n _currentRemainTime -= physicsDeltaTime;\n }\n\n var alpha = _currentRemainTime / physicsDeltaTime;\n Interpolate(model, alpha);\n }\n\n /// \n /// オプションを設定する。\n /// \n public void SetOptions(Vector2 gravity, Vector2 wind)\n {\n Gravity = gravity;\n Wind = wind;\n }\n\n /// \n /// オプションを取得する。\n /// \n /// オプション\n public (Vector2 Gravity, Vector2 Wind) GetOptions() { return (Gravity, Wind); }\n\n /// \n /// 初期化する。\n /// \n private void Initialize()\n {\n CubismPhysicsSubRig currentSetting;\n int i,\n settingIndex;\n\n Vector2 radius;\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n var index = currentSetting.BaseParticleIndex;\n\n // Initialize the top of particle.\n _physicsRig.Particles[index].InitialPosition = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[index].LastPosition = _physicsRig.Particles[index].InitialPosition;\n _physicsRig.Particles[index].LastGravity = new Vector2(0.0f, -1.0f);\n _physicsRig.Particles[index].LastGravity.Y *= -1.0f;\n _physicsRig.Particles[index].Velocity = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[index].Force = new Vector2(0.0f, 0.0f);\n\n // Initialize particles.\n for ( i = 1; i < currentSetting.ParticleCount; ++i )\n {\n radius = new Vector2(0.0f, _physicsRig.Particles[i + index].Radius);\n _physicsRig.Particles[i + index].InitialPosition = _physicsRig.Particles[i - 1 + index].InitialPosition + radius;\n _physicsRig.Particles[i + index].Position = _physicsRig.Particles[i + index].InitialPosition;\n _physicsRig.Particles[i + index].LastPosition = _physicsRig.Particles[i + index].InitialPosition;\n _physicsRig.Particles[i + index].LastGravity = new Vector2(0.0f, -1.0f);\n _physicsRig.Particles[i + index].LastGravity.Y *= -1.0f;\n _physicsRig.Particles[i + index].Velocity = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[i + index].Force = new Vector2(0.0f, 0.0f);\n }\n }\n }\n\n /// \n /// 振り子演算の最新の結果と一つ前の結果から指定した重みで適用する。\n /// \n /// 物理演算の結果を適用するモデル\n /// 最新結果の重み\n private unsafe void Interpolate(CubismModel model, float weight)\n {\n int i,\n settingIndex;\n\n float* parameterValues;\n float* parameterMaximumValues;\n float* parameterMinimumValues;\n\n int currentOutputIndex;\n CubismPhysicsSubRig currentSetting;\n\n parameterValues = CubismCore.GetParameterValues(model.Model);\n parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n currentOutputIndex = currentSetting.BaseOutputIndex;\n\n // Load input parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n continue;\n }\n\n var value = _previousRigOutputs[settingIndex][i] * (1 - weight) + _currentRigOutputs[settingIndex][i] * weight;\n\n UpdateOutputParameterValue(\n ref parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n value,\n _physicsRig.Outputs[i + currentOutputIndex]\n );\n }\n }\n }\n\n private float GetRangeValue(float min, float max)\n {\n var maxValue = CubismMath.Max(min, max);\n var minValue = CubismMath.Min(min, max);\n\n return MathF.Abs(maxValue - minValue);\n }\n\n /// Gets sign.\n /// \n /// @param value Evaluation target value.\n /// \n /// @return Sign of value.\n private static int Sign(float value)\n {\n var ret = 0;\n\n if ( value > 0.0f )\n {\n ret = 1;\n }\n else if ( value < 0.0f )\n {\n ret = -1;\n }\n\n return ret;\n }\n\n private float GetDefaultValue(float min, float max)\n {\n var minValue = CubismMath.Min(min, max);\n\n return minValue + GetRangeValue(min, max) / 2.0f;\n }\n\n private float NormalizeParameterValue(\n float value,\n float parameterMinimum,\n float parameterMaximum,\n float parameterDefault,\n float normalizedMinimum,\n float normalizedMaximum,\n float normalizedDefault,\n bool isInverted)\n {\n var result = 0.0f;\n\n var maxValue = CubismMath.Max(parameterMaximum, parameterMinimum);\n\n if ( maxValue < value )\n {\n value = maxValue;\n }\n\n var minValue = CubismMath.Min(parameterMaximum, parameterMinimum);\n\n if ( minValue > value )\n {\n value = minValue;\n }\n\n var minNormValue = CubismMath.Min(normalizedMinimum, normalizedMaximum);\n var maxNormValue = CubismMath.Max(normalizedMinimum, normalizedMaximum);\n var middleNormValue = normalizedDefault;\n\n var middleValue = GetDefaultValue(minValue, maxValue);\n var paramValue = value - middleValue;\n\n switch ( Sign(paramValue) )\n {\n case 1:\n {\n var nLength = maxNormValue - middleNormValue;\n var pLength = maxValue - middleValue;\n if ( pLength != 0.0f )\n {\n result = paramValue * (nLength / pLength);\n result += middleNormValue;\n }\n\n break;\n }\n case -1:\n {\n var nLength = minNormValue - middleNormValue;\n var pLength = minValue - middleValue;\n if ( pLength != 0.0f )\n {\n result = paramValue * (nLength / pLength);\n result += middleNormValue;\n }\n\n break;\n }\n case 0:\n {\n result = middleNormValue;\n\n break;\n }\n }\n\n return isInverted ? result : result * -1.0f;\n }\n\n private void GetInputTranslationXFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle, bool isInverted,\n float weight)\n {\n targetTranslation.X += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationPosition.Minimum,\n normalizationPosition.Maximum,\n normalizationPosition.Default,\n isInverted\n ) * weight;\n }\n\n private void GetInputTranslationYFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted, float weight)\n {\n targetTranslation.Y += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationPosition.Minimum,\n normalizationPosition.Maximum,\n normalizationPosition.Default,\n isInverted\n ) * weight;\n }\n\n private void GetInputAngleFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted, float weight)\n {\n targetAngle += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationAngle.Minimum,\n normalizationAngle.Maximum,\n normalizationAngle.Default,\n isInverted\n ) * weight;\n }\n\n private float GetOutputTranslationX(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n var outputValue = translation.X;\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputTranslationY(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n var outputValue = translation.Y;\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputAngle(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n float outputValue;\n\n if ( particleIndex >= 2 )\n {\n parentGravity = particles[particleIndex - 1 + start].Position - particles[particleIndex - 2 + start].Position;\n }\n else\n {\n parentGravity *= -1.0f;\n }\n\n outputValue = CubismMath.DirectionToRadian(parentGravity, translation);\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputScaleTranslationX(Vector2 translationScale, float angleScale) { return translationScale.X; }\n\n private float GetOutputScaleTranslationY(Vector2 translationScale, float angleScale) { return translationScale.Y; }\n\n private float GetOutputScaleAngle(Vector2 translationScale, float angleScale) { return angleScale; }\n\n /// Updates particles.\n /// \n /// @param strand Target array of particle.\n /// @param strandCount Count of particle.\n /// @param totalTranslation Total translation value.\n /// @param totalAngle Total angle.\n /// @param windDirection Direction of wind.\n /// @param thresholdValue Threshold of movement.\n /// @param deltaTimeSeconds Delta time.\n /// @param airResistance Air resistance.\n private static void UpdateParticles(CubismPhysicsParticle[] strand, int start, int strandCount, Vector2 totalTranslation, float totalAngle,\n Vector2 windDirection, float thresholdValue, float deltaTimeSeconds, float airResistance)\n {\n int i;\n float totalRadian;\n float delay;\n float radian;\n Vector2 currentGravity;\n Vector2 direction;\n Vector2 velocity;\n Vector2 force;\n Vector2 newDirection;\n\n strand[start].Position = totalTranslation;\n\n totalRadian = CubismMath.DegreesToRadian(totalAngle);\n currentGravity = CubismMath.RadianToDirection(totalRadian);\n currentGravity = Vector2.Normalize(currentGravity);\n\n for ( i = 1; i < strandCount; ++i )\n {\n strand[i + start].Force = currentGravity * strand[i + start].Acceleration + windDirection;\n\n strand[i + start].LastPosition = strand[i + start].Position;\n\n delay = strand[i + start].Delay * deltaTimeSeconds * 30.0f;\n\n direction.X = strand[i + start].Position.X - strand[i - 1 + start].Position.X;\n direction.Y = strand[i + start].Position.Y - strand[i - 1 + start].Position.Y;\n\n radian = CubismMath.DirectionToRadian(strand[i + start].LastGravity, currentGravity) / airResistance;\n\n direction.X = MathF.Cos(radian) * direction.X - direction.Y * MathF.Sin(radian);\n direction.Y = MathF.Sin(radian) * direction.X + direction.Y * MathF.Cos(radian);\n\n strand[i + start].Position = strand[i - 1 + start].Position + direction;\n\n velocity.X = strand[i + start].Velocity.X * delay;\n velocity.Y = strand[i + start].Velocity.Y * delay;\n force = strand[i + start].Force * delay * delay;\n\n strand[i + start].Position = strand[i + start].Position + velocity + force;\n\n newDirection = strand[i + start].Position - strand[i - 1 + start].Position;\n\n newDirection = Vector2.Normalize(newDirection);\n\n strand[i + start].Position = strand[i - 1 + start].Position + newDirection * strand[i + start].Radius;\n\n if ( MathF.Abs(strand[i + start].Position.X) < thresholdValue )\n {\n strand[i + start].Position.X = 0.0f;\n }\n\n if ( delay != 0.0f )\n {\n strand[i + start].Velocity.X = strand[i + start].Position.X - strand[i + start].LastPosition.X;\n strand[i + start].Velocity.Y = strand[i + start].Position.Y - strand[i + start].LastPosition.Y;\n strand[i + start].Velocity /= delay;\n strand[i + start].Velocity *= strand[i + start].Mobility;\n }\n\n strand[i + start].Force = new Vector2(0.0f, 0.0f);\n strand[i + start].LastGravity = currentGravity;\n }\n }\n\n /**\n * Updates particles for stabilization.\n * \n * @param strand Target array of particle.\n * @param strandCount Count of particle.\n * @param totalTranslation Total translation value.\n * @param totalAngle Total angle.\n * @param windDirection Direction of Wind.\n * @param thresholdValue Threshold of movement.\n */\n private static void UpdateParticlesForStabilization(CubismPhysicsParticle[] strand, int start, int strandCount, Vector2 totalTranslation, float totalAngle,\n Vector2 windDirection, float thresholdValue)\n {\n int i;\n float totalRadian;\n Vector2 currentGravity;\n Vector2 force;\n\n strand[start].Position = totalTranslation;\n\n totalRadian = CubismMath.DegreesToRadian(totalAngle);\n currentGravity = CubismMath.RadianToDirection(totalRadian);\n currentGravity = Vector2.Normalize(currentGravity);\n\n for ( i = 1; i < strandCount; ++i )\n {\n strand[i + start].Force = currentGravity * strand[i + start].Acceleration + windDirection;\n\n strand[i + start].LastPosition = strand[i + start].Position;\n\n strand[i + start].Velocity = new Vector2(0.0f, 0.0f);\n\n force = strand[i + start].Force;\n force = Vector2.Normalize(force);\n\n force *= strand[i + start].Radius;\n strand[i + start].Position = strand[i - 1].Position + force;\n\n if ( MathF.Abs(strand[i + start].Position.X) < thresholdValue )\n {\n strand[i + start].Position.X = 0.0f;\n }\n\n strand[i + start].Force = new Vector2(0.0f, 0.0f);\n strand[i + start].LastGravity = currentGravity;\n }\n }\n\n /// Updates output parameter value.\n /// \n /// @param parameterValue Target parameter value.\n /// @param parameterValueMinimum Minimum of parameter value.\n /// @param parameterValueMaximum Maximum of parameter value.\n /// @param translation Translation value.\n private static void UpdateOutputParameterValue(ref float parameterValue, float parameterValueMinimum, float parameterValueMaximum,\n float translation, CubismPhysicsOutput output)\n {\n float outputScale;\n float value;\n float weight;\n\n outputScale = output.GetScale(output.TranslationScale, output.AngleScale);\n\n value = translation * outputScale;\n\n if ( value < parameterValueMinimum )\n {\n if ( value < output.ValueBelowMinimum )\n {\n output.ValueBelowMinimum = value;\n }\n\n value = parameterValueMinimum;\n }\n else if ( value > parameterValueMaximum )\n {\n if ( value > output.ValueExceededMaximum )\n {\n output.ValueExceededMaximum = value;\n }\n\n value = parameterValueMaximum;\n }\n\n weight = output.Weight / MaximumWeight;\n\n if ( weight >= 1.0f )\n {\n parameterValue = value;\n }\n else\n {\n value = parameterValue * (1.0f - weight) + value * weight;\n parameterValue = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionProcessor.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.LLM;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Processor for extracting emotion tags from text before TTS synthesis\n/// \npublic class EmotionProcessor(IEmotionService emotionService, ILoggerFactory loggerFactory) : ITextFilter\n{\n private const string MetadataKey = \"EmotionMarkers\";\n\n private const string MarkerPrefix = \"__EM\";\n\n private const string MarkerSuffix = \"__\";\n\n private static readonly Regex EmotionTagRegex = new(@\"\\[EMOTION:(.*?)\\]\",\n RegexOptions.Compiled | RegexOptions.CultureInvariant);\n\n private readonly ILogger _logger = loggerFactory.CreateLogger();\n\n public int Priority => 100;\n\n public ValueTask ProcessAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n var markers = new List();\n var processedTextBuilder = new StringBuilder();\n var lastIndex = 0;\n var markerIndex = 0;\n\n var matches = EmotionTagRegex.Matches(text);\n if ( matches.Count == 0 )\n {\n _logger.LogTrace(\"No emotion tags found in the input text.\");\n\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n _logger.LogDebug(\"Found {Count} potential emotion tags.\", matches.Count);\n\n foreach ( Match match in matches )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n processedTextBuilder.Append(text, lastIndex, match.Index - lastIndex);\n var emotionValue = match.Groups[1].Value;\n if ( string.IsNullOrWhiteSpace(emotionValue) )\n {\n _logger.LogWarning(\"Found emotion tag with empty value at index {Index}. Skipping.\", match.Index);\n processedTextBuilder.Append(match.Value);\n lastIndex = match.Index + match.Length;\n\n continue;\n }\n\n // e.g., [__EM0__](//), [__EM1__](//) This causes the phonemizer to see it as a feature and ignore it\n var markerId = $\"{MarkerPrefix}{markerIndex++}{MarkerSuffix}\";\n var markerToken = $\"[{markerId}](//)\";\n processedTextBuilder.Append(markerToken);\n\n var markerInfo = new EmotionMarkerInfo { MarkerId = markerId, Emotion = emotionValue };\n markers.Add(markerInfo);\n\n _logger.LogTrace(\"Replaced tag '{Tag}' with marker '{Marker}' for emotion '{Emotion}'.\",\n match.Value, markerId, emotionValue);\n\n lastIndex = match.Index + match.Length;\n }\n\n processedTextBuilder.Append(text, lastIndex, text.Length - lastIndex);\n var processedText = processedTextBuilder.ToString();\n _logger.LogDebug(\"Processed text length: {Length}. Original length: {OriginalLength}.\",\n processedText.Length, text.Length);\n\n var metadata = new Dictionary();\n if ( markers.Count != 0 )\n {\n metadata[MetadataKey] = markers;\n }\n\n var result = new TextFilterResult { ProcessedText = processedText, Metadata = metadata };\n\n return ValueTask.FromResult(result);\n }\n\n public ValueTask PostProcessAsync(TextFilterResult textFilterResult, AudioSegment segment, CancellationToken cancellationToken = default)\n {\n if ( !segment.Tokens.Any() ||\n !textFilterResult.Metadata.TryGetValue(MetadataKey, out var markersObj) ||\n markersObj is not List markers || markers.Count == 0 )\n {\n _logger.LogTrace(\"No emotion markers found in metadata or segment/tokens are missing/empty for segment Id {SegmentId}. Skipping post-processing.\", segment?.Id);\n\n return ValueTask.CompletedTask;\n }\n\n _logger.LogDebug(\"Starting emotion post-processing for segment Id {SegmentId} with {MarkerCount} markers.\", segment.Id, markers.Count);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n var emotionTimings = new List();\n var processedMarkers = new HashSet();\n var allMarkersFound = false;\n\n var markerDict = markers.ToDictionary(m => m.MarkerId, m => m.Emotion);\n\n foreach ( var token in segment.Tokens )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n foreach ( var (markerId, emotion) in markerDict )\n {\n if ( processedMarkers.Contains(markerId) || !token.Text.Contains(markerId) )\n {\n continue;\n }\n\n // Usually okay, the only case wher StartTS is 0 is if it's the first token.\n var timestamp = token.StartTs ?? 0;\n\n emotionTimings.Add(new EmotionTiming { Timestamp = timestamp, Emotion = emotion });\n processedMarkers.Add(markerId);\n token.Text = string.Empty;\n\n _logger.LogDebug(\"Mapped emotion '{Emotion}' (from marker '{Marker}') to timestamp {Timestamp:F2}s based on token '{TokenText}'.\",\n emotion, markerId, timestamp, token.Text);\n\n if ( processedMarkers.Count == markers.Count )\n {\n _logger.LogDebug(\"All {Count} markers have been processed. Exiting token scan early.\", markers.Count);\n allMarkersFound = true;\n\n break;\n }\n }\n\n if ( allMarkersFound )\n {\n break;\n }\n }\n\n if ( emotionTimings.Count != 0 )\n {\n _logger.LogInformation(\"Registering {Count} timed emotions for segment Id {SegmentId}.\", emotionTimings.Count, segment.Id);\n try\n {\n emotionService.RegisterEmotions(segment.Id, emotionTimings);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error registering emotions for segment Id {SegmentId}.\", segment.Id);\n }\n }\n else\n {\n _logger.LogWarning(\"Could not map any emotion markers to timestamps for segment Id {SegmentId}. This might happen if markers were removed by later filters or TTS engine issues.\", segment.Id);\n }\n\n if ( processedMarkers.Count >= markers.Count )\n {\n return ValueTask.CompletedTask;\n }\n\n {\n var unprocessed = markers.Where(m => !processedMarkers.Contains(m.MarkerId)).Select(m => m.MarkerId);\n _logger.LogWarning(\"The following emotion markers were found in ProcessAsync but not located in the final tokens for segment Id {SegmentId}: {UnprocessedMarkers}\",\n segment.Id, string.Join(\", \", unprocessed));\n }\n\n return ValueTask.CompletedTask;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/EspeakFallbackPhonemizer.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Espeak-based fallback phonemizer matching the Python reference implementation\n/// \npublic class EspeakFallbackPhonemizer : IFallbackPhonemizer\n{\n // Dictionary of espeak to model phoneme mappings, sorted by key length descending (matching Python E2M)\n private static readonly IReadOnlyDictionary E2M = new Dictionary {\n { \"ʔˌn\\u0329\", \"tn\" },\n { \"ʔn\\u0329\", \"tn\" },\n { \"ʔn\", \"tn\" },\n { \"ʔ\", \"t\" },\n { \"a^ɪ\", \"I\" },\n { \"a^ʊ\", \"W\" },\n { \"d^ʒ\", \"ʤ\" },\n { \"e^ɪ\", \"A\" },\n { \"e\", \"A\" },\n { \"t^ʃ\", \"ʧ\" },\n { \"ɔ^ɪ\", \"Y\" },\n { \"ə^l\", \"ᵊl\" },\n { \"ʲo\", \"jo\" },\n { \"ʲə\", \"jə\" },\n { \"ʲ\", \"\" },\n { \"ɚ\", \"əɹ\" },\n { \"r\", \"ɹ\" },\n { \"x\", \"k\" },\n { \"ç\", \"k\" },\n { \"ɐ\", \"ə\" },\n { \"ɬ\", \"l\" },\n { \"\\u0303\", \"\" }\n }.OrderByDescending(kv => kv.Key.Length).ToDictionary(kv => kv.Key, kv => kv.Value);\n\n // Add a cache to avoid repeated processing\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly ILogger _logger;\n\n private readonly SemaphoreSlim _processLock = new(1, 1);\n\n private readonly int _processReadTimeoutMs = 2000;\n\n private readonly int _processStartTimeoutMs = 5000;\n\n private readonly IOptionsMonitor _ttsConfig;\n\n private readonly IDisposable? _ttsConfigChangeToken;\n\n private readonly IOptionsMonitor _voiceOptions;\n\n private readonly IDisposable? _voiceOptionsChangeToken;\n\n private bool _disposed;\n\n private volatile string _espeakPath;\n\n // Process state\n private Process? _espeakProcess;\n\n private volatile bool _needProcessReset;\n\n private volatile bool _useBritishEnglish;\n\n public EspeakFallbackPhonemizer(\n IOptionsMonitor ttsConfig,\n IOptionsMonitor voiceOptions,\n ILogger logger)\n {\n _ttsConfig = ttsConfig ?? throw new ArgumentNullException(nameof(ttsConfig));\n _voiceOptions = voiceOptions ?? throw new ArgumentNullException(nameof(voiceOptions));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n _espeakPath = _ttsConfig.CurrentValue.EspeakPath ?? throw new ArgumentNullException(nameof(ttsConfig.CurrentValue.EspeakPath));\n _useBritishEnglish = _voiceOptions.CurrentValue.UseBritishEnglish;\n\n _voiceOptionsChangeToken = _voiceOptions.OnChange(options =>\n {\n _useBritishEnglish = options.UseBritishEnglish;\n _logger.LogDebug(\"Voice options updated: UseBritishEnglish={UseBritishEnglish}\", _useBritishEnglish);\n _needProcessReset = true;\n\n // Clear cache when voice options change\n _cache.Clear();\n });\n\n _ttsConfigChangeToken = _ttsConfig.OnChange(config =>\n {\n if ( string.IsNullOrEmpty(config.EspeakPath) || _espeakPath == config.EspeakPath )\n {\n return;\n }\n\n _espeakPath = config.EspeakPath;\n _logger.LogDebug(\"TTS configuration updated: EspeakPath={EspeakPath}\", _espeakPath);\n _needProcessReset = true;\n\n // Clear cache when espeak path changes\n _cache.Clear();\n });\n }\n\n /// \n /// Gets phonemes for a word using espeak-ng command-line tool\n /// \n public async Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(\n string word,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(word) )\n {\n return (null, null);\n }\n\n // Check cache first\n if ( _cache.TryGetValue(word, out var cachedResult) )\n {\n return cachedResult;\n }\n\n var cancelled = false;\n\n try\n {\n await _processLock.WaitAsync(cancellationToken);\n\n // Check cache again in case another thread added the result while we were waiting\n if ( _cache.TryGetValue(word, out cachedResult) )\n {\n return cachedResult;\n }\n\n var cleanWord = SanitizeInput(word);\n\n // Ensure the process is running\n var process = await EnsureProcessIsInitializedAsync(cancellationToken);\n\n // Write the word to the process stdin\n await process.StandardInput.WriteLineAsync(cleanWord);\n await process.StandardInput.FlushAsync();\n\n // Read the output with a timeout\n var readTask = process.StandardOutput.ReadLineAsync();\n\n if ( await Task.WhenAny(readTask, Task.Delay(_processReadTimeoutMs, cancellationToken)) != readTask )\n {\n _logger.LogWarning(\"Timeout reading output from espeak-ng for word {Word}\", word);\n _needProcessReset = true;\n\n return (null, null);\n }\n\n var output = await readTask;\n\n if ( string.IsNullOrEmpty(output) )\n {\n _logger.LogDebug(\"Empty output from espeak-ng for word {Word}\", word);\n _needProcessReset = true;\n\n return (null, null);\n }\n\n var phonemes = NormalizeEspeakOutput(output.Trim(), _useBritishEnglish);\n\n var result = (phonemes, 2);\n\n // Add to cache\n _cache[word] = result;\n\n return result;\n }\n catch (OperationCanceledException)\n {\n cancelled = true;\n\n return (null, null);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting phonemes from espeak-ng for word {Word}\", word);\n _needProcessReset = true;\n\n return (null, null);\n }\n finally\n {\n if ( !cancelled )\n {\n _processLock.Release();\n }\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voiceOptionsChangeToken?.Dispose();\n _ttsConfigChangeToken?.Dispose();\n\n if ( _espeakProcess != null )\n {\n try\n {\n if ( !_espeakProcess.HasExited )\n {\n _espeakProcess.Kill();\n }\n\n _espeakProcess.Dispose();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing espeak-ng process\");\n }\n }\n\n _processLock.Dispose();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Ensures the espeak process is initialized and running\n /// \n private async Task EnsureProcessIsInitializedAsync(CancellationToken cancellationToken)\n {\n // If process needs to be reset or doesn't exist or has exited, create a new one\n if ( _needProcessReset || _espeakProcess == null || _espeakProcess.HasExited )\n {\n // Dispose of the old process if it exists\n if ( _espeakProcess != null )\n {\n try\n {\n if ( !_espeakProcess.HasExited )\n {\n _espeakProcess.Kill();\n }\n\n _espeakProcess.Dispose();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing espeak-ng process\");\n }\n\n _espeakProcess = null;\n }\n\n // Create a new process\n var language = _useBritishEnglish ? \"en-gb\" : \"en-us\";\n var startInfo = new ProcessStartInfo {\n FileName = _espeakPath,\n Arguments = $\"--ipa=1 -v {language} -q --tie=^\",\n RedirectStandardOutput = true,\n RedirectStandardInput = true,\n StandardOutputEncoding = Encoding.UTF8,\n StandardInputEncoding = Encoding.UTF8,\n UseShellExecute = false,\n CreateNoWindow = true\n };\n\n var process = new Process { StartInfo = startInfo };\n\n // Start the process with a timeout\n var startTask = Task.Run(() =>\n {\n process.Start();\n\n return true;\n });\n\n if ( await Task.WhenAny(startTask, Task.Delay(_processStartTimeoutMs, cancellationToken)) != startTask )\n {\n try\n {\n if ( !process.HasExited )\n {\n process.Kill();\n }\n\n process.Dispose();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing espeak-ng process after start timeout\");\n }\n\n throw new TimeoutException(\"Timeout starting espeak-ng process\");\n }\n\n if ( !startTask.Result )\n {\n throw new InvalidOperationException(\"Failed to start espeak-ng process\");\n }\n\n _espeakProcess = process;\n _needProcessReset = false;\n _logger.LogDebug(\"Started new espeak-ng process\");\n }\n\n return _espeakProcess;\n }\n\n /// \n /// Sanitizes input for espeak command line\n /// \n private string SanitizeInput(string input)\n {\n // Remove characters that could cause command line issues\n return input.Replace(\"\\\"\", \"\")\n .Replace(\"\\\\\", \"\")\n .Replace(\";\", \"\")\n .Replace(\"&\", \"\")\n .Replace(\"|\", \"\")\n .Replace(\">\", \"\")\n .Replace(\"<\", \"\")\n .Replace(\"`\", \"\");\n }\n\n /// \n /// Normalizes espeak output to match the Python implementation\n /// \n private string NormalizeEspeakOutput(string output, bool useBritishEnglish)\n {\n // Apply all replacements from E2M dictionary\n var result = output;\n\n // Apply all the E2M replacements in order of key length (longest first)\n foreach ( var kvp in E2M )\n {\n result = result.Replace(kvp.Key, kvp.Value);\n }\n\n // Apply the regex substitution similar to the Python version\n // This converts characters with combining subscript (U+0329) to have a schwa prefix\n result = Regex.Replace(result, @\"(\\S)\\u0329\", \"ᵊ$1\");\n result = result.Replace(\"\\u0329\", \"\");\n\n // Apply language-specific replacements as in the Python implementation\n if ( useBritishEnglish )\n {\n result = result.Replace(\"e^ə\", \"ɛː\");\n result = result.Replace(\"iə\", \"ɪə\");\n result = result.Replace(\"ə^ʊ\", \"Q\");\n }\n else // American English\n {\n result = result.Replace(\"o^ʊ\", \"O\");\n result = result.Replace(\"ɜːɹ\", \"ɜɹ\");\n result = result.Replace(\"ɜː\", \"ɜɹ\");\n result = result.Replace(\"ɪə\", \"iə\");\n result = result.Replace(\"ː\", \"\");\n }\n\n // Common replacement for both language variants\n result = result.Replace(\"o\", \"ɔ\"); // for espeak < 1.52\n\n // Final clean-up - remove tie character and spaces\n return result.Replace(\"^\", \"\").Replace(\" \", \"\");\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Num2Words.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class Num2Words\n{\n private static readonly string[] _units = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n private static readonly string[] _tens = { \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n private static readonly string[] _ordinalUnits = { \"zeroth\", \"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", \"seventh\", \"eighth\", \"ninth\", \"tenth\", \"eleventh\", \"twelfth\", \"thirteenth\", \"fourteenth\", \"fifteenth\", \"sixteenth\", \"seventeenth\", \"eighteenth\", \"nineteenth\" };\n\n private static readonly string[] _ordinalTens = { \"\", \"\", \"twentieth\", \"thirtieth\", \"fortieth\", \"fiftieth\", \"sixtieth\", \"seventieth\", \"eightieth\", \"ninetieth\" };\n\n public static string Convert(int number, string to = \"cardinal\")\n {\n if ( number == 0 )\n {\n return _units[0];\n }\n\n if ( number < 0 )\n {\n return \"negative \" + Convert(-number, to);\n }\n\n return to.ToLower() switch {\n \"ordinal\" => ConvertToOrdinal(number),\n \"year\" => ConvertToYear(number),\n _ => ConvertToCardinal(number)\n };\n }\n\n public static string Convert(double number)\n {\n // Handle integer part\n var intPart = (int)Math.Floor(number);\n var result = ConvertToCardinal(intPart);\n\n // Handle decimal part\n var decimalPart = number - intPart;\n if ( decimalPart > 0 )\n {\n // Get decimal digits as string and remove trailing zeros\n var decimalString = decimalPart.ToString(\"F20\", CultureInfo.InvariantCulture)\n .TrimStart('0', '.')\n .TrimEnd('0');\n\n if ( !string.IsNullOrEmpty(decimalString) )\n {\n result += \" point\";\n foreach ( var digit in decimalString )\n {\n result += \" \" + _units[int.Parse(digit.ToString())];\n }\n }\n }\n\n return result;\n }\n\n private static string ConvertToCardinal(int number)\n {\n if ( number < 20 )\n {\n return _units[number];\n }\n\n if ( number < 100 )\n {\n return _tens[number / 10] + (number % 10 > 0 ? \"-\" + _units[number % 10] : \"\");\n }\n\n if ( number < 1000 )\n {\n return _units[number / 100] + \" hundred\" + (number % 100 > 0 ? \" and \" + ConvertToCardinal(number % 100) : \"\");\n }\n\n if ( number < 1000000 )\n {\n var thousands = number / 1000;\n var remainder = number % 1000;\n\n var result = ConvertToCardinal(thousands) + \" thousand\";\n\n if ( remainder > 0 )\n {\n // If remainder is less than 100, or if it has a tens/units part\n if ( remainder < 100 )\n {\n result += \" and \" + ConvertToCardinal(remainder);\n }\n else\n {\n // For numbers like 1,234 -> \"one thousand two hundred and thirty-four\"\n var hundreds = remainder / 100;\n var tensAndUnits = remainder % 100;\n\n result += \" \" + _units[hundreds] + \" hundred\";\n if ( tensAndUnits > 0 )\n {\n result += \" and \" + ConvertToCardinal(tensAndUnits);\n }\n }\n }\n\n return result;\n }\n\n if ( number < 1000000000 )\n {\n return ConvertToCardinal(number / 1000000) + \" million\" + (number % 1000000 > 0 ? (number % 1000000 < 100 ? \" and \" : \" \") + ConvertToCardinal(number % 1000000) : \"\");\n }\n\n return ConvertToCardinal(number / 1000000000) + \" billion\" + (number % 1000000000 > 0 ? (number % 1000000000 < 100 ? \" and \" : \" \") + ConvertToCardinal(number % 1000000000) : \"\");\n }\n\n private static string ConvertToOrdinal(int number)\n {\n if ( number < 20 )\n {\n return _ordinalUnits[number];\n }\n\n if ( number < 100 )\n {\n if ( number % 10 == 0 )\n {\n return _ordinalTens[number / 10];\n }\n\n return _tens[number / 10] + \"-\" + _ordinalUnits[number % 10];\n }\n\n var cardinal = ConvertToCardinal(number);\n\n // Replace the last word with its ordinal form\n var lastSpace = cardinal.LastIndexOf(' ');\n if ( lastSpace == -1 )\n {\n // Single word\n var lastWord = cardinal;\n if ( lastWord.EndsWith(\"y\") )\n {\n return lastWord.Substring(0, lastWord.Length - 1) + \"ieth\";\n }\n\n if ( lastWord.EndsWith(\"eight\") )\n {\n return lastWord + \"h\";\n }\n\n if ( lastWord.EndsWith(\"nine\") )\n {\n return lastWord + \"th\";\n }\n\n return lastWord + \"th\";\n }\n else\n {\n // Multiple words\n var lastWord = cardinal.Substring(lastSpace + 1);\n var prefix = cardinal.Substring(0, lastSpace + 1);\n\n if ( lastWord.EndsWith(\"y\") )\n {\n return prefix + lastWord.Substring(0, lastWord.Length - 1) + \"ieth\";\n }\n\n if ( lastWord == \"one\" )\n {\n return prefix + \"first\";\n }\n\n if ( lastWord == \"two\" )\n {\n return prefix + \"second\";\n }\n\n if ( lastWord == \"three\" )\n {\n return prefix + \"third\";\n }\n\n if ( lastWord == \"five\" )\n {\n return prefix + \"fifth\";\n }\n\n if ( lastWord == \"eight\" )\n {\n return prefix + \"eighth\";\n }\n\n if ( lastWord == \"nine\" || lastWord == \"twelve\" )\n {\n return prefix + lastWord + \"th\";\n }\n\n return prefix + lastWord + \"th\";\n }\n }\n\n private static string ConvertToYear(int year)\n {\n // Handle years specially\n if ( year >= 2000 )\n {\n // 2xxx is \"two thousand [and] xxx\"\n var remainder = year - 2000;\n if ( remainder == 0 )\n {\n return \"two thousand\";\n }\n\n if ( remainder < 100 )\n {\n return \"two thousand and \" + ConvertToCardinal(remainder);\n }\n\n return \"two thousand \" + ConvertToCardinal(remainder);\n }\n\n if ( year >= 1000 )\n {\n // Years like 1984 are \"nineteen eighty-four\"\n var century = year / 100;\n var remainder = year % 100;\n\n if ( remainder == 0 )\n {\n return ConvertToCardinal(century) + \" hundred\";\n }\n\n return ConvertToCardinal(century) + \" \" + ConvertToCardinal(remainder);\n }\n\n // Years less than 1000\n return ConvertToCardinal(year);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/OnnxRVC.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class OnnxRVC : IDisposable\n{\n private readonly ArrayPool _arrayPool;\n\n private readonly int _hopSize;\n\n private readonly InferenceSession _model;\n\n private readonly ArrayPool _shortArrayPool;\n\n // Preallocated buffers and tensors\n private readonly DenseTensor _speakerIdTensor;\n\n private readonly ContentVec _vecModel;\n\n public OnnxRVC(string modelPath, int hopsize, string vecPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR\n };\n\n options.AppendExecutionProvider_CUDA();\n \n _model = new InferenceSession(modelPath, options);\n _hopSize = hopsize;\n _vecModel = new ContentVec(vecPath);\n\n // Preallocate the speaker ID tensor\n _speakerIdTensor = new DenseTensor(new[] { 1 });\n\n // Create array pools for temporary buffers\n _arrayPool = ArrayPool.Shared;\n _shortArrayPool = ArrayPool.Shared;\n }\n\n public void Dispose()\n {\n _model?.Dispose();\n _vecModel?.Dispose();\n }\n\n public int ProcessAudio(ReadOnlyMemory inputAudio, Memory outputAudio,\n IF0Predictor f0Predictor, int speakerId, int f0UpKey)\n {\n // Early exit if input is empty\n if ( inputAudio.Length == 0 )\n {\n return 0;\n }\n\n // Check if output buffer is large enough\n if ( outputAudio.Length < inputAudio.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(outputAudio));\n }\n\n // Set the speaker ID\n _speakerIdTensor[0] = speakerId;\n\n // Process the audio\n return ProcessInPlace(inputAudio, outputAudio, f0Predictor, _speakerIdTensor, f0UpKey);\n }\n\n private int ProcessInPlace(ReadOnlyMemory input, Memory output,\n IF0Predictor f0Predictor,\n DenseTensor speakerIdTensor, int f0UpKey)\n {\n const int f0Min = 50;\n const int f0Max = 1100;\n var f0MelMin = 1127 * Math.Log(1 + f0Min / 700.0);\n var f0MelMax = 1127 * Math.Log(1 + f0Max / 700.0);\n\n if ( input.Length / 16000.0 > 30.0 )\n {\n throw new Exception(\"Audio segment is too long (>30s)\");\n }\n\n // Calculate original scale for normalization (matching original implementation)\n var minValue = float.MaxValue;\n var maxValue = float.MinValue;\n var inputSpan = input.Span;\n for ( var i = 0; i < input.Length; i++ )\n {\n minValue = Math.Min(minValue, inputSpan[i]);\n maxValue = Math.Max(maxValue, inputSpan[i]);\n }\n\n var originalScale = maxValue - minValue;\n\n // Get the hubert features\n var hubert = _vecModel.Forward(input);\n\n // Repeat and transpose the features\n var hubertRepeated = RVCUtils.RepeatTensor(hubert, 2);\n hubertRepeated = RVCUtils.Transpose(hubertRepeated, 0, 2, 1);\n\n hubert = null; // Allow for garbage collection\n\n var hubertLength = hubertRepeated.Dimensions[1];\n var hubertLengthTensor = new DenseTensor(new[] { 1 }) { [0] = hubertLength };\n\n // Allocate buffers for F0 calculations\n var f0Buffer = _arrayPool.Rent(hubertLength);\n var f0Memory = new Memory(f0Buffer, 0, hubertLength);\n\n try\n {\n // Calculate F0 directly into buffer\n f0Predictor.ComputeF0(input, f0Memory, hubertLength);\n\n // Create pitch tensors\n var pitchBuffer = _arrayPool.Rent(hubertLength);\n var pitchTensor = new DenseTensor(new[] { 1, hubertLength });\n var pitchfTensor = new DenseTensor(new[] { 1, hubertLength });\n\n try\n {\n // Apply pitch shift and convert to mel scale\n for ( var i = 0; i < hubertLength; i++ )\n {\n // Apply pitch shift\n var shiftedF0 = f0Buffer[i] * (float)Math.Pow(2, f0UpKey / 12.0);\n pitchfTensor[0, i] = shiftedF0;\n\n // Convert to mel scale for pitch\n var f0Mel = 1127 * Math.Log(1 + shiftedF0 / 700.0);\n if ( f0Mel > 0 )\n {\n f0Mel = (f0Mel - f0MelMin) * 254 / (f0MelMax - f0MelMin) + 1;\n f0Mel = Math.Round(f0Mel);\n }\n\n if ( f0Mel <= 1 )\n {\n f0Mel = 1;\n }\n\n if ( f0Mel > 255 )\n {\n f0Mel = 255;\n }\n\n pitchTensor[0, i] = (long)f0Mel;\n }\n\n // Generate random noise tensor\n var rndTensor = new DenseTensor(new[] { 1, 192, hubertLength });\n var random = new Random();\n for ( var i = 0; i < 192 * hubertLength; i++ )\n {\n rndTensor[0, i / hubertLength, i % hubertLength] = (float)random.NextDouble();\n }\n\n // Run the model\n var outWav = Forward(hubertRepeated, hubertLengthTensor, pitchTensor,\n pitchfTensor, speakerIdTensor, rndTensor);\n\n // Apply padding to match original implementation\n // (adding padding at the end only, like in original Pad method)\n var paddedSize = outWav.Length + 2 * _hopSize;\n var paddedOutput = _shortArrayPool.Rent(paddedSize);\n try\n {\n // Copy original output to the beginning of padded output\n for ( var i = 0; i < outWav.Length; i++ )\n {\n paddedOutput[i] = outWav[i];\n }\n // Rest of array is already zeroed when rented from pool\n\n // Find min and max values for normalization\n var minOutValue = short.MaxValue;\n var maxOutValue = short.MinValue;\n for ( var i = 0; i < outWav.Length; i++ )\n {\n minOutValue = Math.Min(minOutValue, outWav[i]);\n maxOutValue = Math.Max(maxOutValue, outWav[i]);\n }\n\n // Copy the output to the buffer with normalization matching original\n var outputSpan = output.Span;\n if ( outputSpan.Length < paddedSize )\n {\n throw new InvalidOperationException($\"Output buffer too small. Needed {paddedSize}, but only had {outputSpan.Length}\");\n }\n\n var maxLen = Math.Min(paddedSize, outputSpan.Length);\n\n // Apply normalization that matches the original implementation\n float range = maxOutValue - minOutValue;\n if ( range > 0 )\n {\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = paddedOutput[i] * originalScale / range;\n }\n }\n else\n {\n // Handle edge case where all values are the same\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = 0;\n }\n }\n\n return outWav.Length;\n }\n finally\n {\n _shortArrayPool.Return(paddedOutput);\n }\n }\n finally\n {\n _arrayPool.Return(pitchBuffer);\n }\n }\n finally\n {\n _arrayPool.Return(f0Buffer);\n }\n }\n\n private short[] Forward(DenseTensor hubert, DenseTensor hubertLength,\n DenseTensor pitch, DenseTensor pitchf,\n DenseTensor speakerId, DenseTensor noise)\n {\n var inputs = new List {\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(0), hubert),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(1), hubertLength),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(2), pitch),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(3), pitchf),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(4), speakerId),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(5), noise)\n };\n\n var results = _model.Run(inputs);\n var output = results.First().AsTensor();\n\n return output.Select(x => (short)(x * 32767)).ToArray();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppWavFileHandler.cs", "using System.Text;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\npublic class WavFileInfo\n{\n public int _bitsPerSample;\n\n public string _fileName;\n\n public int _numberOfChannels;\n\n public int _samplePerChannel;\n\n public int _samplingRate;\n}\n\npublic class LAppWavFileHandler\n{\n private readonly ByteReader _byteReader;\n\n private readonly WavFileInfo _wavFileInfo;\n\n private double _lastRms;\n\n private float[] _pcmData;\n\n private double _sampleOffset;\n\n private double _userTimeSeconds;\n\n public LAppWavFileHandler()\n {\n _pcmData = Array.Empty();\n _userTimeSeconds = 0.0;\n _lastRms = 0.0;\n _sampleOffset = 0.0;\n _wavFileInfo = new WavFileInfo();\n _byteReader = new ByteReader();\n }\n\n public bool Update(float deltaTimeSeconds)\n {\n double goalOffset;\n float rms;\n\n // データロード前/ファイル末尾に達した場合は更新しない\n if ( _pcmData == null || _sampleOffset >= _wavFileInfo._samplePerChannel )\n {\n _lastRms = 0.0f;\n\n return false;\n }\n\n // 経過時間後の状態を保持\n _userTimeSeconds += deltaTimeSeconds;\n goalOffset = Math.Floor(_userTimeSeconds * _wavFileInfo._samplingRate);\n if ( goalOffset > _wavFileInfo._samplePerChannel )\n {\n goalOffset = _wavFileInfo._samplePerChannel;\n }\n\n // RMS計測\n rms = 0.0f;\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n for ( var sampleCount = (int)_sampleOffset; sampleCount < goalOffset; sampleCount++ )\n {\n var index = sampleCount * _wavFileInfo._numberOfChannels + channelCount;\n if ( index >= _pcmData.Length )\n {\n // Ensure we do not go out of bounds\n break;\n }\n\n var pcm = _pcmData[index];\n rms += pcm * pcm;\n }\n }\n\n rms = (float)Math.Sqrt(rms / (_wavFileInfo._numberOfChannels * (goalOffset - _sampleOffset)));\n\n _lastRms = rms;\n _sampleOffset = goalOffset;\n\n return true;\n }\n\n public void Start(string filePath)\n {\n // サンプル位参照位置を初期化\n _sampleOffset = 0;\n _userTimeSeconds = 0.0f;\n\n // RMS値をリセット\n _lastRms = 0.0f;\n }\n\n public double GetRms() { return _lastRms; }\n\n public async Task LoadWavFile(string filePath)\n {\n if ( _pcmData != null )\n {\n ReleasePcmData();\n }\n\n // ファイルロード\n var response = await FetchAsync(filePath);\n if ( response != null )\n {\n // Process the response to load PCM data\n return await AsyncWavFileManager(filePath);\n }\n\n return false;\n }\n\n private async Task FetchAsync(string filePath) { return await Task.Run(() => File.ReadAllBytes(filePath)); }\n\n public async Task AsyncWavFileManager(string filePath)\n {\n var ret = false;\n _byteReader._fileByte = await FetchAsync(filePath);\n _byteReader._fileDataView = new MemoryStream(_byteReader._fileByte);\n _byteReader._fileSize = _byteReader._fileByte.Length;\n _byteReader._readOffset = 0;\n\n // Check if file load failed or if there is not enough size for the signature \"RIFF\"\n if ( _byteReader._fileByte == null || _byteReader._fileSize < 4 )\n {\n return false;\n }\n\n // File name\n _wavFileInfo._fileName = filePath;\n\n try\n {\n // Signature \"RIFF\"\n if ( !_byteReader.GetCheckSignature(\"RIFF\") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'RIFF'.\");\n }\n\n // File size - 8 (skip)\n _byteReader.Get32LittleEndian();\n // Signature \"WAVE\"\n if ( !_byteReader.GetCheckSignature(\"WAVE\") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'WAVE'.\");\n }\n\n // Signature \"fmt \"\n if ( !_byteReader.GetCheckSignature(\"fmt \") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'fmt'.\");\n }\n\n // fmt chunk size\n var fmtChunkSize = (int)_byteReader.Get32LittleEndian();\n // Format ID must be 1 (linear PCM)\n if ( _byteReader.Get16LittleEndian() != 1 )\n {\n ret = false;\n\n throw new Exception(\"File is not linear PCM.\");\n }\n\n // Number of channels\n _wavFileInfo._numberOfChannels = (int)_byteReader.Get16LittleEndian();\n // Sampling rate\n _wavFileInfo._samplingRate = (int)_byteReader.Get32LittleEndian();\n // Data rate [byte/sec] (skip)\n _byteReader.Get32LittleEndian();\n // Block size (skip)\n _byteReader.Get16LittleEndian();\n // Bits per sample\n _wavFileInfo._bitsPerSample = (int)_byteReader.Get16LittleEndian();\n // Skip the extended part of the fmt chunk\n if ( fmtChunkSize > 16 )\n {\n _byteReader._readOffset += fmtChunkSize - 16;\n }\n\n // Skip until \"data\" chunk appears\n while ( !_byteReader.GetCheckSignature(\"data\") && _byteReader._readOffset < _byteReader._fileSize )\n {\n _byteReader._readOffset += (int)_byteReader.Get32LittleEndian() + 4;\n }\n\n // \"data\" chunk not found in the file\n if ( _byteReader._readOffset >= _byteReader._fileSize )\n {\n ret = false;\n\n throw new Exception(\"Cannot find 'data' Chunk.\");\n }\n\n // Number of samples\n {\n var dataChunkSize = (int)_byteReader.Get32LittleEndian();\n _wavFileInfo._samplePerChannel = dataChunkSize * 8 / (_wavFileInfo._bitsPerSample * _wavFileInfo._numberOfChannels);\n }\n\n // Allocate memory\n _pcmData = new float[_wavFileInfo._numberOfChannels * _wavFileInfo._samplePerChannel];\n // Retrieve waveform data\n for ( var sampleCount = 0; sampleCount < _wavFileInfo._samplePerChannel; sampleCount++ )\n {\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n _pcmData[sampleCount * _wavFileInfo._numberOfChannels + channelCount] = GetPcmSample();\n }\n }\n\n ret = true;\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n\n return ret;\n }\n\n public float GetPcmSample()\n {\n int pcm32;\n\n // Expand to 32-bit width and round to the range -1 to 1\n switch ( _wavFileInfo._bitsPerSample )\n {\n case 8:\n pcm32 = _byteReader.Get8() - 128;\n pcm32 <<= 24;\n\n break;\n case 16:\n pcm32 = (int)_byteReader.Get16LittleEndian() << 16;\n\n break;\n case 24:\n pcm32 = (int)_byteReader.Get24LittleEndian() << 8;\n\n break;\n default:\n // Unsupported bit width\n pcm32 = 0;\n\n break;\n }\n\n return pcm32 / 2147483647f; // float.MaxValue;\n }\n\n private void ReleasePcmData()\n {\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n for ( var sampleCount = 0; sampleCount < _wavFileInfo._samplePerChannel; sampleCount++ )\n {\n _pcmData[sampleCount * _wavFileInfo._numberOfChannels + channelCount] = 0.0f;\n }\n }\n\n _pcmData = Array.Empty();\n }\n}\n\npublic class ByteReader\n{\n public byte[] _fileByte;\n\n public MemoryStream _fileDataView;\n\n public int _fileSize;\n\n public int _readOffset;\n\n public int Get8()\n {\n var returnValue = _fileDataView.ReadByte();\n _readOffset++;\n\n return returnValue;\n }\n\n /**\n * @brief 16ビット読み込み(リトルエンディアン)\n * @return Csm::csmUint16 読み取った16ビット値\n */\n public uint Get16LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8);\n\n return ret;\n }\n\n /// \n /// 24ビット読み込み(リトルエンディアン)\n /// \n /// 読み取った24ビット値(下位24ビットに設定)\n public uint Get24LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8) |\n (uint)(Get8() << 16);\n\n return ret;\n }\n\n /// \n /// 32ビット読み込み(リトルエンディアン)\n /// \n /// 読み取った32ビット値\n public uint Get32LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8) |\n (uint)(Get8() << 16) |\n (uint)(Get8() << 24);\n\n return ret;\n }\n\n /// \n /// シグネチャの取得と参照文字列との一致チェック\n /// \n /// 検査対象のシグネチャ文字列\n /// true 一致している, false 一致していない\n public bool GetCheckSignature(string reference)\n {\n if ( reference.Length != 4 )\n {\n return false;\n }\n\n var getSignature = new byte[4];\n var referenceString = Encoding.UTF8.GetBytes(reference);\n\n for ( var signatureOffset = 0; signatureOffset < 4; signatureOffset++ )\n {\n getSignature[signatureOffset] = (byte)Get8();\n }\n\n return getSignature[0] == referenceString[0] &&\n getSignature[1] == referenceString[1] &&\n getSignature[2] == referenceString[2] &&\n getSignature[3] == referenceString[3];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/IConversationSessionFactory.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Context;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic interface IConversationSessionFactory\n{\n IConversationSession CreateSession(ConversationContext context, ConversationOptions? options = null, Guid? sessionId = null);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemizerG2P.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemizerG2P : IPhonemizer\n{\n private readonly IFallbackPhonemizer? _fallback;\n\n private readonly ILexicon _lexicon;\n\n private readonly Regex _linkRegex;\n\n private readonly IPosTagger _posTagger;\n\n private readonly Regex _subtokenRegex;\n\n private readonly string _unk;\n\n private bool _disposed;\n\n public PhonemizerG2P(IPosTagger posTagger, ILexicon lexicon, IFallbackPhonemizer? fallback = null, string unk = \"❓\")\n {\n _posTagger = posTagger ?? throw new ArgumentNullException(nameof(posTagger));\n _fallback = fallback;\n _unk = unk;\n _lexicon = lexicon;\n\n // Initialize regular expressions once for performance\n _linkRegex = new Regex(@\"\\[([^\\]]+)\\]\\(([^\\)]*)\\)\", RegexOptions.Compiled);\n _subtokenRegex = new Regex(\n @\"^[''']+|\\p{Lu}(?=\\p{Lu}\\p{Ll})|(?:^-)?(?:\\d?[,.]?\\d)+|[-_]+|[''']{2,}|\\p{L}*?(?:[''']\\p{L})*?\\p{Ll}(?=\\p{Lu})|\\p{L}+(?:[''']\\p{L})*|[^-_\\p{L}'''\\d]|[''']+$\",\n RegexOptions.Compiled);\n\n _disposed = false;\n }\n\n public async Task ToPhonemesAsync(string text, CancellationToken cancellationToken = default)\n {\n // 1. Preprocess text\n var (processedText, textTokens, features) = Preprocess(text);\n\n // 2. Tag text with POS tagger\n var posTokens = await _posTagger.TagAsync(processedText, cancellationToken);\n\n // 3. Convert to internal token representation\n var tokens = ConvertToTokens(posTokens);\n\n // 4. Apply features from preprocessing\n ApplyFeatures(tokens, textTokens, features);\n\n // 5. Fold left (merge non-head tokens with previous token)\n tokens = FoldLeft(tokens);\n\n // 6. Retokenize (split complex tokens and handle special cases)\n var retokenizedTokens = Retokenize(tokens);\n\n // 7. Process phonemes using lexicon and fallback\n var ctx = new TokenContext();\n await ProcessTokensAsync(retokenizedTokens, ctx, cancellationToken);\n\n // 8. Merge retokenized tokens\n var mergedTokens = MergeRetokenizedTokens(retokenizedTokens);\n\n // 9. Generate final phoneme string\n var phonemes = string.Concat(mergedTokens.Select(t => (t.Phonemes ?? _unk) + t.Whitespace));\n\n return new PhonemeResult(phonemes, mergedTokens);\n }\n\n public void Dispose() { GC.SuppressFinalize(this); }\n\n private List ConvertToTokens(IReadOnlyList posTokens)\n {\n var tokens = new List(posTokens.Count);\n\n foreach ( var pt in posTokens )\n {\n tokens.Add(new Token { Text = pt.Text, Tag = pt.PartOfSpeech ?? string.Empty, Whitespace = pt.IsWhitespace ? \" \" : string.Empty });\n }\n\n return tokens;\n }\n\n private (string ProcessedText, List Tokens, Dictionary Features) Preprocess(string text)\n {\n text = text.TrimStart();\n var result = new StringBuilder(text.Length);\n var tokens = new List();\n var features = new Dictionary();\n\n var lastEnd = 0;\n\n foreach ( Match m in _linkRegex.Matches(text) )\n {\n if ( m.Index > lastEnd )\n {\n var segment = text.Substring(lastEnd, m.Index - lastEnd);\n result.Append(segment);\n tokens.AddRange(segment.Split(' ', StringSplitOptions.RemoveEmptyEntries));\n }\n\n var linkText = m.Groups[1].Value;\n var featureText = m.Groups[2].Value;\n\n object? featureValue = null;\n if ( featureText.Length >= 1 )\n {\n if ( (featureText[0] == '-' || featureText[0] == '+') &&\n int.TryParse(featureText, out var intVal) )\n {\n featureValue = intVal;\n }\n else if ( int.TryParse(featureText, out intVal) )\n {\n featureValue = intVal;\n }\n else if ( featureText == \"0.5\" || featureText == \"+0.5\" )\n {\n featureValue = 0.5;\n }\n else if ( featureText == \"-0.5\" )\n {\n featureValue = -0.5;\n }\n else if ( featureText.Length > 1 )\n {\n var firstChar = featureText[0];\n var lastChar = featureText[featureText.Length - 1];\n\n if ( firstChar == '/' && lastChar == '/' )\n {\n featureValue = firstChar + featureText.Substring(1, featureText.Length - 2);\n }\n else if ( firstChar == '#' && lastChar == '#' )\n {\n featureValue = firstChar + featureText.Substring(1, featureText.Length - 2);\n }\n }\n }\n\n if ( featureValue != null )\n {\n features[tokens.Count] = featureValue;\n }\n\n result.Append(linkText);\n tokens.Add(linkText);\n lastEnd = m.Index + m.Length;\n }\n\n if ( lastEnd < text.Length )\n {\n var segment = text.Substring(lastEnd);\n result.Append(segment);\n tokens.AddRange(segment.Split(' ', StringSplitOptions.RemoveEmptyEntries));\n }\n\n return (result.ToString(), tokens, features);\n }\n\n private void ApplyFeatures(List tokens, List textTokens, Dictionary features)\n {\n if ( features.Count == 0 )\n {\n return;\n }\n\n var alignment = CreateBidirectionalAlignment(textTokens, tokens.Select(t => t.Text).ToList());\n\n foreach ( var kvp in features )\n {\n var sourceIndex = kvp.Key;\n var value = kvp.Value;\n\n var matchedIndices = new List();\n for ( var i = 0; i < alignment.Length; i++ )\n {\n if ( alignment[i] == sourceIndex )\n {\n matchedIndices.Add(i);\n }\n }\n\n for ( var matchCount = 0; matchCount < matchedIndices.Count; matchCount++ )\n {\n var tokenIndex = matchedIndices[matchCount];\n\n if ( tokenIndex >= tokens.Count )\n {\n continue;\n }\n\n if ( value is int intValue )\n {\n tokens[tokenIndex].Stress = intValue;\n }\n else if ( value is double doubleValue )\n {\n tokens[tokenIndex].Stress = doubleValue;\n }\n else if ( value is string strValue )\n {\n if ( strValue.StartsWith(\"/\") )\n {\n // The \"i == 0\" in Python refers to the first match of this feature\n tokens[tokenIndex].IsHead = matchCount == 0;\n tokens[tokenIndex].Phonemes = matchCount == 0 ? strValue.Substring(1) : string.Empty;\n tokens[tokenIndex].Rating = 5;\n }\n else if ( strValue.StartsWith(\"#\") )\n {\n tokens[tokenIndex].NumFlags = strValue.Substring(1);\n }\n }\n }\n }\n }\n\n private int[] CreateBidirectionalAlignment(List source, List target)\n {\n // This is a simplified version - ideally it would match spaCy's algorithm more closely\n var alignment = new int[target.Count];\n\n // Create a combined string from each list to verify they match overall\n var sourceText = string.Join(\"\", source).ToLowerInvariant();\n var targetText = string.Join(\"\", target).ToLowerInvariant();\n\n // Initialize all alignments to no match\n for ( var i = 0; i < alignment.Length; i++ )\n {\n alignment[i] = -1;\n }\n\n var targetIndex = 0;\n var sourcePos = 0;\n\n // Track position in the joined strings to handle multi-token to single token mappings\n for ( var sourceIndex = 0; sourceIndex < source.Count; sourceIndex++ )\n {\n var sourceToken = source[sourceIndex].ToLowerInvariant();\n sourcePos += sourceToken.Length;\n\n var targetPos = 0;\n for ( var i = 0; i < targetIndex; i++ )\n {\n targetPos += target[i].ToLowerInvariant().Length;\n }\n\n // Map all target tokens that overlap with this source token\n while ( targetIndex < target.Count && targetPos < sourcePos )\n {\n var targetToken = target[targetIndex].ToLowerInvariant();\n alignment[targetIndex] = sourceIndex;\n\n targetPos += targetToken.Length;\n targetIndex++;\n }\n }\n\n return alignment;\n }\n\n private List FoldLeft(List tokens)\n {\n if ( tokens.Count <= 1 )\n {\n return tokens;\n }\n\n var result = new List(tokens.Count);\n result.Add(tokens[0]);\n\n for ( var i = 1; i < tokens.Count; i++ )\n {\n if ( !tokens[i].IsHead )\n {\n var merged = Token.MergeTokens(\n [result[^1], tokens[i]],\n _unk);\n\n result[^1] = merged;\n }\n else\n {\n result.Add(tokens[i]);\n }\n }\n\n return result;\n }\n\n private List Retokenize(List tokens)\n {\n var result = new List(tokens.Count * 2); // Estimate capacity\n string? currentCurrency = null;\n\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var token = tokens[i];\n List subtokens;\n\n // Split token if needed\n if ( token.Alias == null && token.Phonemes == null )\n {\n var subTokenTexts = Subtokenize(token.Text);\n subtokens = new List(subTokenTexts.Count);\n\n for ( var j = 0; j < subTokenTexts.Count; j++ )\n {\n subtokens.Add(new Token {\n Text = subTokenTexts[j],\n Tag = token.Tag,\n Whitespace = j == subTokenTexts.Count - 1 ? token.Whitespace : string.Empty,\n IsHead = token.IsHead && j == 0,\n Stress = token.Stress,\n NumFlags = token.NumFlags\n });\n }\n }\n else\n {\n subtokens = new List { token };\n }\n\n // Process each subtoken\n for ( var j = 0; j < subtokens.Count; j++ )\n {\n var t = subtokens[j];\n\n if ( t.Alias != null || t.Phonemes != null )\n {\n // Skip special handling for already processed tokens\n }\n else if ( t.Tag == \"$\" && PhonemizerConstants.Currencies.ContainsKey(t.Text) )\n {\n currentCurrency = t.Text;\n t.Phonemes = string.Empty;\n t.Rating = 4;\n }\n else if ( t is { Tag: \":\", Text: \"-\" or \"–\" } )\n {\n t.Phonemes = \"—\";\n t.Rating = 3;\n }\n else if ( PhonemizerConstants.PunctTags.Contains(t.Tag) )\n {\n if ( PhonemizerConstants.PunctTagPhonemes.TryGetValue(t.Tag, out var phoneme) )\n {\n t.Phonemes = phoneme;\n }\n else\n {\n var sb = new StringBuilder();\n foreach ( var c in t.Text )\n {\n if ( PhonemizerConstants.Puncts.Contains(c) )\n {\n sb.Append(c);\n }\n }\n\n t.Phonemes = sb.ToString();\n }\n\n t.Rating = 4;\n }\n else if ( currentCurrency != null )\n {\n if ( t.Tag != \"CD\" )\n {\n currentCurrency = null;\n }\n else if ( j + 1 == subtokens.Count && (i + 1 == tokens.Count || tokens[i + 1].Tag != \"CD\") )\n {\n t.Currency = currentCurrency;\n }\n }\n else if ( 0 < j && j < subtokens.Count - 1 &&\n t.Text == \"2\" &&\n char.IsLetter(subtokens[j - 1].Text[subtokens[j - 1].Text.Length - 1]) &&\n char.IsLetter(subtokens[j + 1].Text[0]) )\n {\n t.Alias = \"to\";\n }\n\n // Add to result\n if ( t.Alias != null || t.Phonemes != null )\n {\n result.Add(t);\n }\n else if ( result.Count > 0 &&\n result[result.Count - 1] is List lastList &&\n lastList.Count > 0 &&\n string.IsNullOrEmpty(lastList[lastList.Count - 1].Whitespace) )\n {\n t.IsHead = false;\n ((List)result[^1]).Add(t);\n }\n else\n {\n result.Add(string.IsNullOrEmpty(t.Whitespace) ? new List { t } : t);\n }\n }\n }\n\n // Simplify lists with single elements\n for ( var i = 0; i < result.Count; i++ )\n {\n if ( result[i] is List list && list.Count == 1 )\n {\n result[i] = list[0];\n }\n }\n\n return result;\n }\n\n private List Subtokenize(string word)\n {\n var matches = _subtokenRegex.Matches(word);\n if ( matches.Count == 0 )\n {\n return new List { word };\n }\n\n var result = new List(matches.Count);\n foreach ( Match match in matches )\n {\n result.Add(match.Value);\n }\n\n return result;\n }\n\n private async Task ProcessTokensAsync(List tokens, TokenContext ctx, CancellationToken cancellationToken)\n {\n // Process tokens in reverse order\n for ( var i = tokens.Count - 1; i >= 0; i-- )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n return;\n }\n\n if ( tokens[i] is Token token )\n {\n if ( token.Phonemes == null )\n {\n (token.Phonemes, token.Rating) = await GetPhonemesAsync(token, ctx, cancellationToken);\n }\n\n ctx = TokenContext.UpdateContext(ctx, token.Phonemes, token);\n }\n else if ( tokens[i] is List subtokens )\n {\n await ProcessSubtokensAsync(subtokens, ctx, cancellationToken);\n }\n }\n }\n\n private async Task ProcessSubtokensAsync(List tokens, TokenContext ctx, CancellationToken cancellationToken)\n {\n int left = 0,\n right = tokens.Count;\n\n var shouldFallback = false;\n\n while ( left < right )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n return;\n }\n\n if ( tokens.Skip(left).Take(right - left).Any(t => t.Alias != null || t.Phonemes != null) )\n {\n left++;\n\n continue;\n }\n\n var mergedToken = Token.MergeTokens(tokens.Skip(left).Take(right - left).ToList(), _unk);\n var (phonemes, rating) = await GetPhonemesAsync(mergedToken, ctx, cancellationToken);\n\n if ( phonemes != null )\n {\n tokens[left].Phonemes = phonemes;\n tokens[left].Rating = rating;\n\n for ( var i = left + 1; i < right; i++ )\n {\n tokens[i].Phonemes = string.Empty;\n tokens[i].Rating = rating;\n }\n\n ctx = TokenContext.UpdateContext(ctx, phonemes, mergedToken);\n right = left;\n left = 0;\n }\n else if ( left + 1 < right )\n {\n left++;\n }\n else\n {\n right--;\n var t = tokens[right];\n\n if ( t.Phonemes == null )\n {\n if ( t.Text.All(c => PhonemizerConstants.SubtokenJunks.Contains(c)) )\n {\n t.Phonemes = string.Empty;\n t.Rating = 3;\n }\n else if ( _fallback != null )\n {\n shouldFallback = true;\n\n break;\n }\n }\n\n left = 0;\n }\n }\n\n if ( shouldFallback && _fallback != null )\n {\n var mergedToken = Token.MergeTokens(tokens, _unk);\n var (phonemes, rating) = await _fallback.GetPhonemesAsync(mergedToken.Text, cancellationToken);\n\n if ( phonemes != null )\n {\n tokens[0].Phonemes = phonemes;\n tokens[0].Rating = rating;\n\n for ( var j = 1; j < tokens.Count; j++ )\n {\n tokens[j].Phonemes = string.Empty;\n tokens[j].Rating = rating;\n }\n }\n }\n\n ResolveTokens(tokens);\n }\n\n private async Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(Token token, TokenContext ctx, CancellationToken cancellationToken)\n {\n // Try to get from lexicon\n var (phonemes, rating) = _lexicon.ProcessToken(token, ctx);\n\n // If not found, try fallback\n if ( phonemes == null && _fallback != null )\n {\n return await _fallback.GetPhonemesAsync(token.Alias ?? token.Text, cancellationToken);\n }\n\n return (phonemes, rating);\n }\n\n private void ResolveTokens(List tokens)\n {\n // Calculate if there should be space between phonemes\n var text = string.Concat(tokens.Take(tokens.Count - 1).Select(t => t.Text + t.Whitespace)) +\n tokens[tokens.Count - 1].Text;\n\n var prespace = text.Contains(' ') || text.Contains('/') ||\n text.Where(c => !PhonemizerConstants.SubtokenJunks.Contains(c))\n .Select(c => char.IsLetter(c)\n ? 0\n : char.IsDigit(c)\n ? 1\n : 2)\n .Distinct()\n .Count() > 1;\n\n // Handle specific cases\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var t = tokens[i];\n\n if ( t.Phonemes == null )\n {\n if ( i == tokens.Count - 1 && t.Text.Length > 0 &&\n PhonemizerConstants.NonQuotePuncts.Contains(t.Text[0]) )\n {\n t.Phonemes = t.Text;\n t.Rating = 3;\n }\n else if ( t.Text.All(c => PhonemizerConstants.SubtokenJunks.Contains(c)) )\n {\n t.Phonemes = string.Empty;\n t.Rating = 3;\n }\n }\n else if ( i > 0 )\n {\n t.Prespace = prespace;\n }\n }\n\n if ( prespace )\n {\n return;\n }\n\n // Adjust stress patterns\n var indices = new List<(bool HasPrimaryStress, int Weight, int Index)>();\n for ( var i = 0; i < tokens.Count; i++ )\n {\n if ( !string.IsNullOrEmpty(tokens[i].Phonemes) )\n {\n var hasPrimary = tokens[i].Phonemes.Contains(PhonemizerConstants.PrimaryStress);\n indices.Add((hasPrimary, tokens[i].StressWeight(), i));\n }\n }\n\n if ( indices.Count == 2 && tokens[indices[0].Index].Text.Length == 1 )\n {\n var i = indices[1].Index;\n tokens[i].Phonemes = ApplyStress(tokens[i].Phonemes!, -0.5);\n\n return;\n }\n\n if ( indices.Count < 2 || indices.Count(x => x.HasPrimaryStress) <= (indices.Count + 1) / 2 )\n {\n return;\n }\n\n indices.Sort();\n foreach ( var (_, _, i) in indices.Take(indices.Count / 2) )\n {\n tokens[i].Phonemes = ApplyStress(tokens[i].Phonemes!, -0.5);\n }\n }\n\n private string ApplyStress(string phonemes, double stress)\n {\n if ( stress < -1 )\n {\n return phonemes\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty);\n }\n\n if ( stress == -1 || ((stress == 0 || stress == -0.5) && phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return phonemes\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), PhonemizerConstants.SecondaryStress.ToString());\n }\n\n if ( (stress == 0 || stress == 0.5 || stress == 1) &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.SecondaryStress + phonemes);\n }\n\n if ( stress >= 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n return phonemes.Replace(PhonemizerConstants.SecondaryStress.ToString(), PhonemizerConstants.PrimaryStress.ToString());\n }\n\n if ( stress > 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.PrimaryStress + phonemes);\n }\n\n return phonemes;\n }\n\n private string RestressPhonemes(string phonemes)\n {\n var chars = phonemes.ToCharArray();\n var charPositions = new List<(int Position, char Char)>();\n\n for ( var i = 0; i < chars.Length; i++ )\n {\n charPositions.Add((i, chars[i]));\n }\n\n var stressPositions = new Dictionary();\n for ( var i = 0; i < charPositions.Count; i++ )\n {\n if ( PhonemizerConstants.Stresses.Contains(charPositions[i].Char) )\n {\n // Find the next vowel\n var vowelPos = -1;\n for ( var j = i + 1; j < charPositions.Count; j++ )\n {\n if ( PhonemizerConstants.Vowels.Contains(charPositions[j].Char) )\n {\n vowelPos = j;\n\n break;\n }\n }\n\n if ( vowelPos != -1 )\n {\n stressPositions[charPositions[i].Position] = charPositions[vowelPos].Position;\n charPositions[i] = ((int)(vowelPos - 0.5), charPositions[i].Char);\n }\n }\n }\n\n charPositions.Sort((a, b) => a.Position.CompareTo(b.Position));\n\n return new string(charPositions.Select(cp => cp.Char).ToArray());\n }\n\n private List MergeRetokenizedTokens(List retokenizedTokens)\n {\n var result = new List();\n\n foreach ( var item in retokenizedTokens )\n {\n if ( item is Token token )\n {\n result.Add(token);\n }\n else if ( item is List tokens )\n {\n result.Add(Token.MergeTokens(tokens, _unk));\n }\n }\n\n return result;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/AvatarApp.cs", "using Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.UI;\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.GUI;\nusing PersonaEngine.Lib.UI.Spout;\n\nusing Silk.NET.Input;\nusing Silk.NET.Maths;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.Core;\n\npublic class AvatarApp : IDisposable\n{\n private readonly IOptions _config;\n\n private readonly IConversationOrchestrator _conversationOrchestrator;\n\n private readonly IReadOnlyList _regularComponents;\n\n private readonly Dictionary> _spoutComponents = new();\n\n private readonly IReadOnlyList _startupTasks;\n\n private readonly IWindow _window;\n\n private readonly WindowConfiguration _windowConfig;\n\n private readonly WindowManager _windowManager;\n\n private GL _gl;\n\n private ImGuiController _imGui;\n\n private IInputContext _inputContext;\n \n private SpoutRegistry _spoutRegistry;\n\n public AvatarApp(IOptions config, IEnumerable renderComponents, IEnumerable startupTasks, IConversationOrchestrator conversationOrchestrator)\n {\n _config = config;\n _conversationOrchestrator = conversationOrchestrator;\n\n var allComponents = renderComponents.OrderByDescending(x => x.Priority).ToList();\n\n // Group components by spout target\n _regularComponents = allComponents.Where(x => !x.UseSpout).ToList();\n\n // Group spout components by their target\n foreach ( var component in allComponents.Where(x => x.UseSpout) )\n {\n if ( !_spoutComponents.TryGetValue(component.SpoutTarget, out var componentList) )\n {\n componentList = new List();\n _spoutComponents[component.SpoutTarget] = componentList;\n }\n\n componentList.Add(component);\n }\n\n _windowConfig = _config.Value.Window;\n _windowManager = new WindowManager(new Vector2D(_windowConfig.Width, _windowConfig.Height), _windowConfig.Title);\n _window = _windowManager.MainWindow;\n\n _windowManager.Load += OnLoad;\n _windowManager.Update += OnUpdate;\n _windowManager.RenderFrame += OnRender;\n _windowManager.Resize += OnResize;\n _windowManager.Close += OnClose;\n\n _startupTasks = startupTasks.ToList();\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n\n return;\n\n _spoutRegistry?.Dispose();\n _imGui.Dispose();\n }\n\n private void OnLoad()\n {\n // Set up keyboard input.\n _inputContext = _window.CreateInput();\n foreach ( var keyboard in _inputContext.Keyboards )\n {\n keyboard.KeyDown += OnKeyDown;\n }\n\n _gl = _windowManager.GL;\n\n foreach ( var task in _startupTasks )\n {\n task.Execute(_gl);\n }\n\n _spoutRegistry = new SpoutRegistry(_gl, _config.Value.SpoutConfigs);\n\n _imGui = new ImGuiController(_gl, _window, _inputContext, Path.Combine(@\"Resources\\Fonts\", @\"Montserrat-Medium.ttf\"), Path.Combine(@\"Resources\\Fonts\", @\"seguiemj.ttf\"));\n\n InitializeComponents(_regularComponents);\n\n foreach ( var componentGroup in _spoutComponents.Values )\n {\n InitializeComponents(componentGroup);\n }\n\n _ = _conversationOrchestrator.StartNewSessionAsync();\n }\n\n private void InitializeComponents(IEnumerable components)\n {\n foreach ( var component in components )\n {\n component.Initialize(_gl, _window, _inputContext);\n }\n }\n\n private void OnUpdate(double deltaTime)\n {\n // Update all components\n UpdateComponents(_regularComponents, (float)deltaTime);\n\n foreach ( var componentGroup in _spoutComponents.Values )\n {\n UpdateComponents(componentGroup, (float)deltaTime);\n }\n }\n\n private void UpdateComponents(IEnumerable components, float deltaTime)\n {\n foreach ( var component in components )\n {\n component.Update(deltaTime);\n }\n }\n\n private void OnRender(double deltaTime)\n {\n _imGui.Update((float)deltaTime);\n _gl.Viewport(0, 0, (uint)_windowConfig.Width, (uint)_windowConfig.Height);\n _gl.Clear((uint)ClearBufferMask.ColorBufferBit);\n\n // Render regular components to the screen\n foreach ( var component in _regularComponents )\n {\n component.Render((float)deltaTime);\n }\n\n _imGui.Render();\n\n // Render components to their respective Spout outputs\n foreach ( var spoutGroup in _spoutComponents )\n {\n var spoutTarget = spoutGroup.Key;\n var components = spoutGroup.Value;\n\n // Begin frame for this spout target\n _spoutRegistry.BeginFrame(spoutTarget);\n\n // Render all components for this spout target\n foreach ( var component in components )\n {\n component.Render((float)deltaTime);\n }\n\n _spoutRegistry.SendFrame(spoutTarget);\n }\n }\n\n private void OnResize(Vector2D size)\n {\n // Resize all components\n ResizeComponents(_regularComponents);\n }\n\n private void ResizeComponents(IEnumerable components)\n {\n foreach ( var component in components )\n {\n component.Resize();\n }\n }\n\n private void OnClose() { }\n\n private void OnKeyDown(IKeyboard keyboard, Key key, int scancode)\n {\n switch ( key )\n {\n case Key.Escape:\n _window.Close();\n\n break;\n }\n }\n\n public void Run() { _windowManager.Run(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleLine.cs", "namespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Represents a single line of processed subtitles containing multiple words.\n/// \npublic class SubtitleLine\n{\n public SubtitleLine(int segmentIndex, int lineIndexInSegment)\n {\n SegmentIndex = segmentIndex;\n LineIndexInSegment = lineIndexInSegment;\n }\n\n public List Words { get; } = new();\n\n public float TotalWidth { get; set; }\n\n public float BaselineY { get; set; }\n\n public int SegmentIndex { get; }\n\n public int LineIndexInSegment { get; }\n\n public void AddWord(SubtitleWordInfo word)\n {\n Words.Add(word);\n TotalWidth += word.Size.X;\n }\n\n public void Clear()\n {\n Words.Clear();\n TotalWidth = 0;\n BaselineY = 0;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCFilter.cs", "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCFilter : IAudioFilter, IDisposable\n{\n private const int ProcessingSampleRate = 16000;\n\n private const int OutputSampleRate = 32000;\n\n private const int FinalSampleRate = 24000;\n\n private const int MaxInputDuration = 30; // seconds\n\n private readonly SemaphoreSlim _initLock = new(1, 1);\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly IDisposable? _optionsChangeRegistration;\n\n private readonly IOptionsMonitor _optionsMonitor;\n\n private readonly IRVCVoiceProvider _rvcVoiceProvider;\n\n private RVCFilterOptions _currentOptions;\n\n private bool _disposed;\n\n private IF0Predictor? _f0Predictor;\n\n private OnnxRVC? _rvcModel;\n\n public RVCFilter(\n IOptionsMonitor optionsMonitor,\n IModelProvider modelProvider,\n IRVCVoiceProvider rvcVoiceProvider,\n ILogger logger)\n {\n _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));\n _modelProvider = modelProvider;\n _rvcVoiceProvider = rvcVoiceProvider;\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _currentOptions = optionsMonitor.CurrentValue;\n\n _ = InitializeAsync(_currentOptions);\n\n // Register for options changes\n _optionsChangeRegistration = _optionsMonitor.OnChange(OnOptionsChanged);\n }\n\n public void Process(AudioSegment audioSegment)\n {\n if ( _disposed )\n {\n throw new ObjectDisposedException(nameof(RVCFilter));\n }\n\n if ( _rvcModel == null || _f0Predictor == null ||\n audioSegment?.AudioData == null || audioSegment.AudioData.Length == 0 )\n {\n return;\n }\n\n // Get the latest options for processing\n var options = _currentOptions;\n var originalSampleRate = audioSegment.SampleRate;\n\n if ( !options.Enabled )\n {\n return;\n }\n\n // Start timing\n var stopwatch = Stopwatch.StartNew();\n\n // Step 1: Resample input to processing sample rate\n var resampleRatioToProcessing = (int)Math.Ceiling((double)ProcessingSampleRate / originalSampleRate);\n var resampledInputSize = audioSegment.AudioData.Length * resampleRatioToProcessing;\n\n var resampledInput = ArrayPool.Shared.Rent(resampledInputSize);\n try\n {\n var inputSampleCount = AudioConverter.ResampleFloat(\n audioSegment.AudioData,\n resampledInput,\n 1,\n (uint)originalSampleRate,\n ProcessingSampleRate);\n\n // Step 2: Process with RVC model\n var maxInputSamples = OutputSampleRate * MaxInputDuration;\n var outputBufferSize = maxInputSamples + 2 * options.HopSize;\n\n var processingBuffer = ArrayPool.Shared.Rent(outputBufferSize);\n try\n {\n var processedSampleCount = _rvcModel.ProcessAudio(\n resampledInput.AsMemory(0, inputSampleCount),\n processingBuffer,\n _f0Predictor,\n options.SpeakerId,\n options.F0UpKey);\n\n // Step 3: Resample to original sample rate\n var resampleRatioToOutput = (int)Math.Ceiling((double)originalSampleRate / OutputSampleRate);\n var finalOutputSize = processedSampleCount * resampleRatioToOutput;\n\n var resampledOutput = ArrayPool.Shared.Rent(finalOutputSize);\n try\n {\n var finalSampleCount = AudioConverter.ResampleFloat(\n processingBuffer.AsMemory(0, processedSampleCount),\n resampledOutput,\n 1,\n OutputSampleRate,\n (uint)originalSampleRate);\n\n // Need one allocation for the final output buffer since AudioSegment keeps this reference\n var finalBuffer = new float[finalSampleCount];\n Array.Copy(resampledOutput, finalBuffer, finalSampleCount);\n\n audioSegment.AudioData = finalBuffer.AsMemory();\n audioSegment.SampleRate = FinalSampleRate;\n }\n finally\n {\n ArrayPool.Shared.Return(resampledOutput);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(processingBuffer);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(resampledInput);\n }\n\n // Stop timing after processing is complete\n stopwatch.Stop();\n var processingTime = stopwatch.Elapsed.TotalSeconds;\n\n // Calculate final audio duration (based on the processed audio)\n var finalAudioDuration = audioSegment.AudioData.Length / (double)FinalSampleRate;\n\n // Calculate real-time factor\n var realTimeFactor = finalAudioDuration / processingTime;\n\n // Log the results using ILogger\n _logger.LogInformation(\"Generated {AudioDuration:F2}s audio in {ProcessingTime:F2}s (x{RealTimeFactor:F2} real-time)\",\n finalAudioDuration, processingTime, realTimeFactor);\n }\n\n public int Priority => 100;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( disposing )\n {\n _optionsChangeRegistration?.Dispose();\n DisposeResources();\n }\n\n _disposed = true;\n }\n\n private async void OnOptionsChanged(RVCFilterOptions newOptions)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( ShouldReinitialize(newOptions) )\n {\n DisposeResources();\n await InitializeAsync(newOptions);\n }\n\n _currentOptions = newOptions;\n }\n\n private bool ShouldReinitialize(RVCFilterOptions newOptions)\n {\n return _currentOptions.DefaultVoice != newOptions.DefaultVoice ||\n _currentOptions.HopSize != newOptions.HopSize;\n }\n\n private async ValueTask InitializeAsync(RVCFilterOptions options)\n {\n await _initLock.WaitAsync();\n try\n {\n var crepeModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCCrepeTiny);\n var hubertModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCHubert);\n var rvcModel = await _rvcVoiceProvider.GetVoiceAsync(options.DefaultVoice);\n\n // _f0Predictor = new CrepeOnnx(crepeModel.Path);\n _f0Predictor = new CrepeOnnxSimd(crepeModel.Path);\n // _f0Predictor = new ACFMethod(512, 16000);\n\n _rvcModel = new OnnxRVC(\n rvcModel,\n options.HopSize,\n hubertModel.Path);\n }\n finally\n {\n _initLock.Release();\n }\n }\n\n private void DisposeResources()\n {\n _rvcModel?.Dispose();\n _rvcModel = null;\n\n _f0Predictor?.Dispose();\n _f0Predictor = null;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/DefaultAudioBufferManager.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Default implementation of IAudioBufferManager.\n/// \npublic class DefaultAudioBufferManager : IAudioBufferManager\n{\n private readonly BlockingCollection<(Memory Data, AudioSegment Segment)> _audioQueue;\n\n private readonly ILogger _logger;\n\n private readonly int _maxBufferCount;\n\n private bool _disposed;\n\n public DefaultAudioBufferManager(int maxBufferCount = 32, ILogger? logger = null)\n {\n _maxBufferCount = maxBufferCount > 0\n ? maxBufferCount\n : throw new ArgumentException(\"Max buffer count must be positive\", nameof(maxBufferCount));\n\n _logger = logger ?? NullLogger.Instance;\n _audioQueue = new BlockingCollection<(Memory, AudioSegment)>(_maxBufferCount);\n }\n\n public int BufferCount => _audioQueue.Count;\n\n public bool ProducerCompleted { get; private set; }\n\n public async Task EnqueueSegmentsAsync(\n IAsyncEnumerable audioSegments,\n CancellationToken cancellationToken)\n {\n try\n {\n ProducerCompleted = false;\n\n await foreach ( var segment in audioSegments.WithCancellation(cancellationToken) )\n {\n if ( segment.AudioData.Length <= 0 || cancellationToken.IsCancellationRequested )\n {\n continue;\n }\n\n try\n {\n // Add to bounded collection - will block if queue is full (applying backpressure)\n _audioQueue.Add((segment.AudioData, segment), cancellationToken);\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n // Expected when cancellation is requested\n break;\n }\n catch (InvalidOperationException) when (_audioQueue.IsAddingCompleted)\n {\n // Queue was completed during processing\n break;\n }\n }\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n _logger.LogInformation(\"Audio enqueuing cancelled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error while enqueuing audio segments\");\n\n throw;\n }\n finally\n {\n ProducerCompleted = true;\n }\n }\n\n public bool TryGetNextBuffer(\n out (Memory Data, AudioSegment Segment) buffer,\n int timeoutMs,\n CancellationToken cancellationToken)\n {\n return _audioQueue.TryTake(out buffer, timeoutMs, cancellationToken);\n }\n\n public void Clear()\n {\n while ( _audioQueue.TryTake(out _) ) { }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n\n try\n {\n _audioQueue.Dispose();\n await Task.CompletedTask; // For async consistency\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing audio buffer manager\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OnnxAudioSynthesizer.cs", "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of audio synthesis using ONNX models\n/// \npublic class OnnxAudioSynthesizer : IAudioSynthesizer\n{\n private readonly ITtsCache _cache;\n\n private readonly SemaphoreSlim _inferenceThrottle;\n\n private readonly IModelProvider _ittsModelProvider;\n\n private readonly ILogger _logger;\n\n private readonly IOptionsMonitor _options;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private bool _disposed;\n\n private IReadOnlyDictionary? _phonemeToIdMap;\n\n private InferenceSession? _synthesisSession;\n\n public OnnxAudioSynthesizer(\n IModelProvider ittsModelProvider,\n IKokoroVoiceProvider voiceProvider,\n ITtsCache cache,\n IOptionsMonitor options,\n ILogger logger)\n {\n _ittsModelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _voiceProvider = voiceProvider ?? throw new ArgumentNullException(nameof(voiceProvider));\n _cache = cache ?? throw new ArgumentNullException(nameof(cache));\n _options = options ?? throw new ArgumentNullException(nameof(options));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n // Create throttle to limit concurrent inference operations\n _inferenceThrottle = new SemaphoreSlim(\n Math.Max(1, Environment.ProcessorCount / 2), // Use half of available cores for inference\n Environment.ProcessorCount);\n\n _logger.LogInformation(\"Initialized ONNX audio synthesizer\");\n }\n\n /// \n /// Synthesizes audio from phonemes\n /// \n public async Task SynthesizeAsync(\n string phonemes,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(phonemes) )\n {\n return new AudioData(Array.Empty(), Array.Empty());\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n // Initialize lazily on first use\n await EnsureInitializedAsync(cancellationToken);\n\n // Get current options (to ensure we have the latest values)\n var currentOptions = options ?? _options.CurrentValue;\n\n // Validate phoneme length\n if ( phonemes.Length > currentOptions.MaxPhonemeLength )\n {\n _logger.LogWarning(\"Truncating phonemes to maximum length {MaxLength}\", currentOptions.MaxPhonemeLength);\n phonemes = phonemes.Substring(0, currentOptions.MaxPhonemeLength);\n }\n\n // Convert phonemes to tokens\n var tokens = ConvertPhonemesToTokens(phonemes);\n if ( tokens.Count == 0 )\n {\n _logger.LogWarning(\"No valid tokens generated from phonemes\");\n\n return new AudioData(Array.Empty(), Array.Empty());\n }\n\n // Get voice data\n var voice = await _voiceProvider.GetVoiceAsync(currentOptions.DefaultVoice, cancellationToken);\n\n // Create audio with throttling for inference\n await _inferenceThrottle.WaitAsync(cancellationToken);\n\n try\n {\n // Measure performance\n var timer = Stopwatch.StartNew();\n\n // Perform inference\n var (audioData, phonemeTimings) = await RunInferenceAsync(tokens, voice, options, cancellationToken);\n\n // Log performance metrics\n timer.Stop();\n LogPerformanceMetrics(timer.Elapsed, audioData.Length, phonemes.Length, options);\n\n return new AudioData(audioData, phonemeTimings);\n }\n finally\n {\n _inferenceThrottle.Release();\n }\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"Audio synthesis was canceled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during audio synthesis\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _synthesisSession?.Dispose();\n _synthesisSession = null;\n\n _phonemeToIdMap = null;\n _inferenceThrottle.Dispose();\n\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Ensures the model and resources are initialized\n /// \n private async Task EnsureInitializedAsync(CancellationToken cancellationToken)\n {\n if ( _synthesisSession != null && _phonemeToIdMap != null )\n {\n return;\n }\n\n // Load model and resources\n await InitializeSessionAsync(cancellationToken);\n await LoadPhonemeMapAsync(cancellationToken);\n }\n\n /// \n /// Initializes the ONNX inference session\n /// \n private async Task InitializeSessionAsync(CancellationToken cancellationToken)\n {\n if ( _synthesisSession != null )\n {\n return;\n }\n\n _logger.LogInformation(\"Initializing synthesis model\");\n\n // Create optimized session options\n var sessionOptions = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Math.Max(1, Environment.ProcessorCount / 2),\n IntraOpNumThreads = Math.Max(1, Environment.ProcessorCount / 2),\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n try\n {\n sessionOptions.AppendExecutionProvider_CUDA();\n _logger.LogInformation(\"CUDA execution provider added successfully\");\n }\n catch (Exception ex)\n {\n _logger.LogWarning(\"CUDA execution provider not available: {Message}. Using CPU.\", ex.Message);\n }\n\n // Get model with retry mechanism\n var maxRetries = 3;\n Exception? lastException = null;\n\n for ( var attempt = 0; attempt < maxRetries; attempt++ )\n {\n try\n {\n var model = await _ittsModelProvider.GetModelAsync(ModelType.KokoroSynthesis, cancellationToken);\n var modelData = await model.GetDataAsync();\n\n _synthesisSession = new InferenceSession(modelData, sessionOptions);\n _logger.LogInformation(\"Synthesis model initialized successfully\");\n\n return;\n }\n catch (Exception ex)\n {\n lastException = ex;\n _logger.LogWarning(ex, \"Error initializing ONNX session (attempt {Attempt} of {MaxRetries}). Retrying...\",\n attempt + 1, maxRetries);\n\n if ( attempt < maxRetries - 1 )\n {\n // Exponential backoff\n await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)), cancellationToken);\n }\n }\n }\n\n // If we get here, all attempts failed\n throw new InvalidOperationException(\n $\"Failed to initialize ONNX session after {maxRetries} attempts\", lastException);\n }\n\n /// \n /// Loads the phoneme-to-ID mapping\n /// \n private async Task LoadPhonemeMapAsync(CancellationToken cancellationToken)\n {\n if ( _phonemeToIdMap != null )\n {\n return;\n }\n\n _logger.LogInformation(\"Loading phoneme mapping\");\n\n try\n {\n // Use cache for phoneme map to avoid repeated loading\n _phonemeToIdMap = await _cache.GetOrAddAsync(\"phoneme_map\", async ct =>\n {\n var model = await _ittsModelProvider.GetModelAsync(ModelType.KokoroPhonemeMappings, ct);\n var mapPath = model.Path;\n\n _logger.LogDebug(\"Loading phoneme mapping from {Path}\", mapPath);\n\n var lines = await File.ReadAllLinesAsync(mapPath, ct);\n\n // Initialize with capacity for better performance\n var mapping = new Dictionary(lines.Length);\n\n foreach ( var line in lines )\n {\n if ( string.IsNullOrWhiteSpace(line) || line.Length < 3 )\n {\n continue;\n }\n\n mapping[line[0]] = long.Parse(line[2..]);\n }\n\n _logger.LogInformation(\"Loaded {Count} phoneme mappings\", mapping.Count);\n\n return mapping;\n }, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n /* Ignored */\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading phoneme mapping\");\n\n throw;\n }\n }\n\n /// \n /// Converts phoneme characters to token IDs\n /// \n private List ConvertPhonemesToTokens(string phonemes)\n {\n // If no mapping loaded, can't convert\n if ( _phonemeToIdMap == null )\n {\n throw new InvalidOperationException(\"Phoneme map not initialized\");\n }\n\n // Pre-allocate with expected capacity\n var tokens = new List(phonemes.Length);\n\n foreach ( var phoneme in phonemes )\n {\n if ( _phonemeToIdMap.TryGetValue(phoneme, out var id) )\n {\n tokens.Add(id);\n }\n }\n\n return tokens;\n }\n\n /// \n /// Runs model inference to generate audio\n /// \n private async Task<(Memory AudioData, Memory PhonemeTimings)> RunInferenceAsync(\n List tokens,\n VoiceData voice,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default)\n {\n // Make sure session is initialized\n if ( _synthesisSession == null )\n {\n throw new InvalidOperationException(\"Synthesis session not initialized\");\n }\n\n // Get current options (to ensure we have the latest values)\n var currentOptions = options ?? _options.CurrentValue;\n\n // Create model inputs\n var modelInputs = CreateModelInputs(tokens, voice, currentOptions.DefaultSpeed);\n\n // Run inference\n using var results = _synthesisSession.Run(modelInputs);\n\n // Extract results\n var waveformTensor = results[0].AsTensor();\n var durationTensor = results[1].AsTensor();\n\n // Extract result data\n var waveformLength = waveformTensor.Dimensions.Length > 0 ? waveformTensor.Dimensions[0] : 0;\n\n var waveform = new float[waveformLength];\n var durations = new long[durationTensor.Length];\n\n // Copy data to results\n Buffer.BlockCopy(waveformTensor.ToArray(), 0, waveform, 0, waveformLength * sizeof(float));\n Buffer.BlockCopy(durationTensor.ToArray(), 0, durations, 0, durations.Length * sizeof(long));\n\n // Apply audio processing if needed\n if ( currentOptions.TrimSilence )\n {\n waveform = TrimSilence(waveform);\n }\n\n return (waveform, durations);\n }\n\n /// \n /// Creates input tensors for the synthesis model\n /// \n private List CreateModelInputs(List tokens, VoiceData voice, float speed)\n {\n // Add boundary tokens (BOS/EOS)\n var tokenArray = ArrayPool.Shared.Rent(tokens.Count + 2);\n\n try\n {\n // BOS token\n tokenArray[0] = 0;\n\n // Copy tokens\n tokens.CopyTo(tokenArray, 1);\n\n // EOS token\n tokenArray[tokens.Count + 1] = 0;\n\n // Create tensors\n var inputTokens = new DenseTensor(\n tokenArray.AsMemory(0, tokens.Count + 2),\n new[] { 1, tokens.Count + 2 });\n\n var styleInput = voice.GetEmbedding(inputTokens.Dimensions).ToArray();\n var voiceEmbedding = new DenseTensor(styleInput, new[] { 1, styleInput.Length });\n\n var speedTensor = new DenseTensor(\n new[] { speed },\n new[] { 1 });\n\n // Return named tensors\n return new List { NamedOnnxValue.CreateFromTensor(\"input_ids\", inputTokens), NamedOnnxValue.CreateFromTensor(\"style\", voiceEmbedding), NamedOnnxValue.CreateFromTensor(\"speed\", speedTensor) };\n }\n finally\n {\n // Always return the rented array\n ArrayPool.Shared.Return(tokenArray);\n }\n }\n\n /// \n /// Trims silence from the beginning and end of audio data\n /// \n private float[] TrimSilence(float[] audioData, float threshold = 0.01f, int minSamples = 512)\n {\n if ( audioData.Length <= minSamples * 2 )\n {\n return audioData;\n }\n\n // Find start (first sample above threshold)\n var startIndex = 0;\n for ( var i = 0; i < audioData.Length - minSamples; i++ )\n {\n if ( Math.Abs(audioData[i]) > threshold )\n {\n startIndex = Math.Max(0, i - minSamples);\n\n break;\n }\n }\n\n // Find end (last sample above threshold)\n var endIndex = audioData.Length - 1;\n for ( var i = audioData.Length - 1; i >= minSamples; i-- )\n {\n if ( Math.Abs(audioData[i]) > threshold )\n {\n endIndex = Math.Min(audioData.Length - 1, i + minSamples);\n\n break;\n }\n }\n\n // If no significant audio found, return original\n if ( startIndex >= endIndex )\n {\n return audioData;\n }\n\n // Create trimmed array\n var newLength = endIndex - startIndex + 1;\n var result = new float[newLength];\n Array.Copy(audioData, startIndex, result, 0, newLength);\n\n return result;\n }\n\n /// \n /// Logs performance metrics for inference\n /// \n private void LogPerformanceMetrics(TimeSpan elapsed, int audioLength, int phonemeCount, KokoroVoiceOptions? options = null)\n {\n // Get current options to ensure we have the latest sample rate\n var currentOptions = options ?? _options.CurrentValue;\n\n var audioDuration = audioLength / (float)currentOptions.SampleRate;\n var elapsedSeconds = elapsed.TotalSeconds;\n var speedup = elapsedSeconds > 0 ? audioDuration / elapsedSeconds : 0;\n\n _logger.LogInformation(\n \"Generated {AudioDuration:F2}s audio for {PhonemeCount} phonemes in {Elapsed:F2}s (x{Speedup:F2} real-time)\",\n audioDuration, phonemeCount, elapsedSeconds, speedup);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ImGuiController.cs", "using System.Diagnostics;\nusing System.Drawing;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Utilities;\nusing Hexa.NET.ImNodes;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.Input;\nusing Silk.NET.Input.Extensions;\nusing Silk.NET.Maths;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class ImGuiController : IDisposable\n{\n [FixedAddressValueType] private static SetClipboardDelegate setClipboardFn;\n\n [FixedAddressValueType] private static GetClipboardDelegate getClipboardFn;\n\n private readonly List _pressedChars = new();\n\n private int _attribLocationProjMtx;\n\n private int _attribLocationTex;\n\n private int _attribLocationVtxColor;\n\n private int _attribLocationVtxPos;\n\n private int _attribLocationVtxUV;\n\n private IntPtr _clipboardTextPtr = IntPtr.Zero;\n\n private bool _ctrlVProcessed = false;\n\n private uint _elementsHandle;\n\n private Texture _fontTexture;\n\n private bool _frameBegun;\n\n private GL _gl;\n\n private IInputContext _input;\n\n private IKeyboard _keyboard;\n\n private ImGuiPlatformIOPtr _platform;\n\n private Shader _shader;\n\n private uint _vboHandle;\n\n private uint _vertexArrayObject;\n\n private IView _view;\n\n private bool _wasCtrlVPressed = false;\n\n private int _windowHeight;\n\n private int _windowWidth;\n\n public ImGuiContextPtr Context;\n\n /// \n /// Constructs a new ImGuiController.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input) : this(gl, view, input, null, null) { }\n\n /// \n /// Constructs a new ImGuiController with font configuration.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input, string primaryFontPath, string emojiFontPath) : this(gl, view, input, primaryFontPath, emojiFontPath, null) { }\n\n /// \n /// Constructs a new ImGuiController with an onConfigureIO Action.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input, Action? onConfigureIO) : this(gl, view, input, null, null, onConfigureIO) { }\n\n /// \n /// Constructs a new ImGuiController with font configuration and onConfigure Action.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input, string? primaryFontPath = null, string? emojiFontPath = null, Action? onConfigureIO = null)\n {\n Init(gl, view, input);\n\n var io = ImGui.GetIO();\n var fontBuilder = new ImGuiFontBuilder();\n\n if ( primaryFontPath != null )\n {\n \n fontBuilder.AddFontFromFileTTF(primaryFontPath, 18f, [0x1, 0x1FFFF]);\n \n }\n else\n {\n fontBuilder.AddDefaultFont();\n }\n\n if ( emojiFontPath != null )\n {\n fontBuilder.SetOption(config =>\n {\n config.FontBuilderFlags |= (uint)ImGuiFreeTypeBuilderFlags.LoadColor;\n config.MergeMode = true;\n config.PixelSnapH = true;\n });\n\n fontBuilder.AddFontFromFileTTF(emojiFontPath, 14f, [0x1, 0x1FFFF]);\n }\n\n _ = fontBuilder.Build();\n io.Fonts.Build();\n\n io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset;\n io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;\n io.ConfigViewportsNoAutoMerge = false;\n io.ConfigViewportsNoTaskBarIcon = false;\n\n CreateDeviceResources();\n\n SetPerFrameImGuiData(1f / 60f);\n\n // Initialize ImNodes as you're already doing\n ImNodes.SetImGuiContext(Context);\n ImNodes.SetCurrentContext(ImNodes.CreateContext());\n ImNodes.StyleColorsDark(ImNodes.GetStyle());\n\n BeginFrame();\n }\n\n /// \n /// Frees all graphics resources used by the renderer.\n /// \n public void Dispose()\n {\n _view.Resize -= WindowResized;\n _keyboard.KeyChar -= OnKeyChar;\n\n _gl.DeleteBuffer(_vboHandle);\n _gl.DeleteBuffer(_elementsHandle);\n _gl.DeleteVertexArray(_vertexArrayObject);\n\n _fontTexture.Dispose();\n _shader.Dispose();\n\n ImGui.DestroyContext(Context);\n }\n\n public void MakeCurrent() { ImGui.SetCurrentContext(Context); }\n\n private unsafe void Init(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _view = view;\n _input = input;\n _windowWidth = view.Size.X;\n _windowHeight = view.Size.Y;\n\n Context = ImGui.CreateContext();\n ImGui.SetCurrentContext(Context);\n ImGui.StyleColorsDark();\n\n _platform = ImGui.GetPlatformIO();\n var io = ImGui.GetIO();\n\n setClipboardFn = SetClipboard;\n getClipboardFn = GetClipboard;\n\n // Register clipboard handlers with both IO and PlatformIO\n _platform.PlatformSetClipboardTextFn = (void*)Marshal.GetFunctionPointerForDelegate(setClipboardFn);\n _platform.PlatformGetClipboardTextFn = (void*)Marshal.GetFunctionPointerForDelegate(getClipboardFn);\n }\n\n private void SetClipboard(IntPtr data)\n {\n Debug.WriteLine(\"SetClipboard called\");\n\n if ( data == IntPtr.Zero )\n {\n return;\n }\n\n var text = Marshal.PtrToStringUTF8(data) ?? string.Empty;\n try\n {\n // Try the Silk.NET method first\n if ( _keyboard != null )\n {\n _keyboard.ClipboardText = text;\n }\n else\n {\n Debug.WriteLine(\"Keyboard reference is null when setting clipboard text\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to set clipboard text via Silk.NET: {ex.Message}\");\n }\n }\n\n private IntPtr GetClipboard()\n {\n Debug.WriteLine(\"GetClipboard called\");\n\n if ( _clipboardTextPtr != IntPtr.Zero )\n {\n Marshal.FreeHGlobal(_clipboardTextPtr);\n _clipboardTextPtr = IntPtr.Zero;\n }\n\n var text = string.Empty;\n var success = false;\n\n // Try primary method\n if ( _keyboard != null )\n {\n try\n {\n text = _keyboard.ClipboardText ?? string.Empty;\n success = true;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to get clipboard text via Silk.NET: {ex.Message}\");\n }\n }\n\n // Convert to UTF-8 and allocate memory\n try\n {\n // Ensure null termination for C strings\n var bytes = Encoding.UTF8.GetBytes(text + '\\0');\n _clipboardTextPtr = Marshal.AllocHGlobal(bytes.Length);\n Marshal.Copy(bytes, 0, _clipboardTextPtr, bytes.Length);\n\n return _clipboardTextPtr;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to allocate memory for clipboard text: {ex.Message}\");\n\n return IntPtr.Zero;\n }\n }\n\n private void BeginFrame()\n {\n ImGui.NewFrame();\n _frameBegun = true;\n _keyboard = _input.Keyboards[0];\n _view.Resize += WindowResized;\n _keyboard.KeyDown += OnKeyDown;\n _keyboard.KeyUp += OnKeyUp;\n _keyboard.KeyChar += OnKeyChar;\n }\n\n private static void OnKeyDown(IKeyboard keyboard, Key keycode, int scancode) { OnKeyEvent(keyboard, keycode, scancode, true); }\n\n private static void OnKeyUp(IKeyboard keyboard, Key keycode, int scancode) { OnKeyEvent(keyboard, keycode, scancode, false); }\n\n private static void OnKeyEvent(IKeyboard keyboard, Key keycode, int scancode, bool down)\n {\n var io = ImGui.GetIO();\n var imGuiKey = TranslateInputKeyToImGuiKey(keycode);\n io.AddKeyEvent(imGuiKey, down);\n io.SetKeyEventNativeData(imGuiKey, (int)keycode, scancode);\n }\n\n private void OnKeyChar(IKeyboard arg1, char arg2) { _pressedChars.Add(arg2); }\n\n private void WindowResized(Vector2D size)\n {\n _windowWidth = size.X;\n _windowHeight = size.Y;\n }\n\n /// \n /// Renders the ImGui draw list data.\n /// This method requires a because it may create new DeviceBuffers if the size of vertex\n /// or index data has increased beyond the capacity of the existing buffers.\n /// A is needed to submit drawing and resource update commands.\n /// \n public void Render()\n {\n if ( _frameBegun )\n {\n ImGui.End();\n\n var oldCtx = ImGui.GetCurrentContext();\n\n if ( oldCtx != Context )\n {\n ImGui.SetCurrentContext(Context);\n }\n\n _frameBegun = false;\n ImGui.Render();\n RenderImDrawData(ImGui.GetDrawData());\n\n if ( oldCtx != Context )\n {\n ImGui.SetCurrentContext(oldCtx);\n }\n }\n }\n\n /// \n /// Updates ImGui input and IO configuration state.\n /// \n public void Update(float deltaSeconds)\n {\n var oldCtx = ImGui.GetCurrentContext();\n\n if ( oldCtx != Context )\n {\n ImGui.SetCurrentContext(Context);\n }\n\n if ( _frameBegun )\n {\n ImGui.Render();\n }\n\n SetPerFrameImGuiData(deltaSeconds);\n UpdateImGuiInput();\n SetDocking();\n\n _frameBegun = true;\n }\n\n private void SetDocking()\n {\n ImGui.NewFrame();\n var viewport = ImGui.GetMainViewport();\n\n var windowFlags = ImGuiWindowFlags.NoTitleBar |\n ImGuiWindowFlags.NoResize |\n ImGuiWindowFlags.NoMove |\n ImGuiWindowFlags.NoBringToFrontOnFocus |\n ImGuiWindowFlags.NoNavFocus;\n\n ImGui.SetNextWindowPos(viewport.Pos);\n ImGui.SetNextWindowSize(viewport.Size);\n ImGui.SetNextWindowViewport(viewport.ID);\n ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0.0f);\n ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0.0f);\n ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0));\n\n ImGui.Begin(\"DockSpace\", windowFlags);\n ImGui.PopStyleVar(3);\n var dockspaceId = ImGui.GetID(\"MyDockSpace\");\n ImGui.DockSpace(dockspaceId, new Vector2(0.0f, 0.0f), ImGuiDockNodeFlags.AutoHideTabBar);\n }\n\n /// \n /// Sets per-frame data based on the associated window.\n /// This is called by Update(float).\n /// \n private void SetPerFrameImGuiData(float deltaSeconds)\n {\n var io = ImGui.GetIO();\n io.DisplaySize = new Vector2(_windowWidth, _windowHeight);\n\n if ( _windowWidth > 0 && _windowHeight > 0 )\n {\n io.DisplayFramebufferScale = new Vector2(_view.FramebufferSize.X / _windowWidth,\n _view.FramebufferSize.Y / _windowHeight);\n }\n\n io.DeltaTime = deltaSeconds; // DeltaTime is in seconds.\n }\n\n private void UpdateImGuiInput()\n {\n var io = ImGui.GetIO();\n\n using var mouseState = _input.Mice[0].CaptureState();\n\n io.MouseDown[0] = mouseState.IsButtonPressed(MouseButton.Left);\n io.MouseDown[1] = mouseState.IsButtonPressed(MouseButton.Right);\n io.MouseDown[2] = mouseState.IsButtonPressed(MouseButton.Middle);\n\n var point = new Point((int)mouseState.Position.X, (int)mouseState.Position.Y);\n io.MousePos = new Vector2(point.X, point.Y);\n\n var wheel = mouseState.GetScrollWheels()[0];\n io.MouseWheel = wheel.Y;\n io.MouseWheelH = wheel.X;\n\n foreach ( var c in _pressedChars )\n {\n io.AddInputCharacter(c);\n }\n\n _pressedChars.Clear();\n\n io.KeyCtrl = _keyboard.IsKeyPressed(Key.ControlLeft) || _keyboard.IsKeyPressed(Key.ControlRight);\n io.KeyAlt = _keyboard.IsKeyPressed(Key.AltLeft) || _keyboard.IsKeyPressed(Key.AltRight);\n io.KeyShift = _keyboard.IsKeyPressed(Key.ShiftLeft) || _keyboard.IsKeyPressed(Key.ShiftRight);\n io.KeySuper = _keyboard.IsKeyPressed(Key.SuperLeft) || _keyboard.IsKeyPressed(Key.SuperRight);\n\n if ( io.KeyCtrl && _keyboard.IsKeyPressed(Key.C) )\n {\n io.AddKeyEvent(ImGuiKey.C, true);\n io.AddKeyEvent(ImGuiKey.LeftCtrl, true);\n\n Debug.WriteLine(\"Adding Ctrl+C event to ImGui\");\n }\n\n var isCtrlVPressed = io.KeyCtrl && _keyboard.IsKeyPressed(Key.V);\n\n if ( isCtrlVPressed && !_wasCtrlVPressed )\n {\n _ctrlVProcessed = false;\n }\n\n if ( isCtrlVPressed && !_ctrlVProcessed )\n {\n io.AddKeyEvent(ImGuiKey.V, true);\n io.AddKeyEvent(ImGuiKey.LeftCtrl, true);\n\n var clipboardText = ImGui.GetClipboardTextS();\n if ( ImGui.IsAnyItemActive() )\n {\n foreach ( var c in clipboardText )\n {\n io.AddInputCharacter(c);\n }\n }\n\n io.AddKeyEvent(ImGuiKey.V, false);\n io.AddKeyEvent(ImGuiKey.LeftCtrl, false);\n\n _ctrlVProcessed = true;\n }\n\n _wasCtrlVPressed = isCtrlVPressed;\n }\n\n internal void PressChar(char keyChar) { _pressedChars.Add(keyChar); }\n\n /// \n /// Translates a Silk.NET.Input.Key to an ImGuiKey.\n /// \n /// The Silk.NET.Input.Key to translate.\n /// The corresponding ImGuiKey.\n /// When the key has not been implemented yet.\n private static ImGuiKey TranslateInputKeyToImGuiKey(Key key)\n {\n return key switch {\n Key.Tab => ImGuiKey.Tab,\n Key.Left => ImGuiKey.LeftArrow,\n Key.Right => ImGuiKey.RightArrow,\n Key.Up => ImGuiKey.UpArrow,\n Key.Down => ImGuiKey.DownArrow,\n Key.PageUp => ImGuiKey.PageUp,\n Key.PageDown => ImGuiKey.PageDown,\n Key.Home => ImGuiKey.Home,\n Key.End => ImGuiKey.End,\n Key.Insert => ImGuiKey.Insert,\n Key.Delete => ImGuiKey.Delete,\n Key.Backspace => ImGuiKey.Backspace,\n Key.Space => ImGuiKey.Space,\n Key.Enter => ImGuiKey.Enter,\n Key.Escape => ImGuiKey.Escape,\n Key.Apostrophe => ImGuiKey.Apostrophe,\n Key.Comma => ImGuiKey.Comma,\n Key.Minus => ImGuiKey.Minus,\n Key.Period => ImGuiKey.Period,\n Key.Slash => ImGuiKey.Slash,\n Key.Semicolon => ImGuiKey.Semicolon,\n Key.Equal => ImGuiKey.Equal,\n Key.LeftBracket => ImGuiKey.LeftBracket,\n Key.BackSlash => ImGuiKey.Backslash,\n Key.RightBracket => ImGuiKey.RightBracket,\n Key.GraveAccent => ImGuiKey.GraveAccent,\n Key.CapsLock => ImGuiKey.CapsLock,\n Key.ScrollLock => ImGuiKey.ScrollLock,\n Key.NumLock => ImGuiKey.NumLock,\n Key.PrintScreen => ImGuiKey.PrintScreen,\n Key.Pause => ImGuiKey.Pause,\n Key.Keypad0 => ImGuiKey.Keypad0,\n Key.Keypad1 => ImGuiKey.Keypad1,\n Key.Keypad2 => ImGuiKey.Keypad2,\n Key.Keypad3 => ImGuiKey.Keypad3,\n Key.Keypad4 => ImGuiKey.Keypad4,\n Key.Keypad5 => ImGuiKey.Keypad5,\n Key.Keypad6 => ImGuiKey.Keypad6,\n Key.Keypad7 => ImGuiKey.Keypad7,\n Key.Keypad8 => ImGuiKey.Keypad8,\n Key.Keypad9 => ImGuiKey.Keypad9,\n Key.KeypadDecimal => ImGuiKey.KeypadDecimal,\n Key.KeypadDivide => ImGuiKey.KeypadDivide,\n Key.KeypadMultiply => ImGuiKey.KeypadMultiply,\n Key.KeypadSubtract => ImGuiKey.KeypadSubtract,\n Key.KeypadAdd => ImGuiKey.KeypadAdd,\n Key.KeypadEnter => ImGuiKey.KeypadEnter,\n Key.KeypadEqual => ImGuiKey.KeypadEqual,\n Key.ShiftLeft => ImGuiKey.LeftShift,\n Key.ControlLeft => ImGuiKey.LeftCtrl,\n Key.AltLeft => ImGuiKey.LeftAlt,\n Key.SuperLeft => ImGuiKey.LeftSuper,\n Key.ShiftRight => ImGuiKey.RightShift,\n Key.ControlRight => ImGuiKey.RightCtrl,\n Key.AltRight => ImGuiKey.RightAlt,\n Key.SuperRight => ImGuiKey.RightSuper,\n Key.Menu => ImGuiKey.Menu,\n Key.Number0 => ImGuiKey.Key0,\n Key.Number1 => ImGuiKey.Key1,\n Key.Number2 => ImGuiKey.Key2,\n Key.Number3 => ImGuiKey.Key3,\n Key.Number4 => ImGuiKey.Key4,\n Key.Number5 => ImGuiKey.Key5,\n Key.Number6 => ImGuiKey.Key6,\n Key.Number7 => ImGuiKey.Key7,\n Key.Number8 => ImGuiKey.Key8,\n Key.Number9 => ImGuiKey.Key9,\n Key.A => ImGuiKey.A,\n Key.B => ImGuiKey.B,\n Key.C => ImGuiKey.C,\n Key.D => ImGuiKey.D,\n Key.E => ImGuiKey.E,\n Key.F => ImGuiKey.F,\n Key.G => ImGuiKey.G,\n Key.H => ImGuiKey.H,\n Key.I => ImGuiKey.I,\n Key.J => ImGuiKey.J,\n Key.K => ImGuiKey.K,\n Key.L => ImGuiKey.L,\n Key.M => ImGuiKey.M,\n Key.N => ImGuiKey.N,\n Key.O => ImGuiKey.O,\n Key.P => ImGuiKey.P,\n Key.Q => ImGuiKey.Q,\n Key.R => ImGuiKey.R,\n Key.S => ImGuiKey.S,\n Key.T => ImGuiKey.T,\n Key.U => ImGuiKey.U,\n Key.V => ImGuiKey.V,\n Key.W => ImGuiKey.W,\n Key.X => ImGuiKey.X,\n Key.Y => ImGuiKey.Y,\n Key.Z => ImGuiKey.Z,\n Key.F1 => ImGuiKey.F1,\n Key.F2 => ImGuiKey.F2,\n Key.F3 => ImGuiKey.F3,\n Key.F4 => ImGuiKey.F4,\n Key.F5 => ImGuiKey.F5,\n Key.F6 => ImGuiKey.F6,\n Key.F7 => ImGuiKey.F7,\n Key.F8 => ImGuiKey.F8,\n Key.F9 => ImGuiKey.F9,\n Key.F10 => ImGuiKey.F10,\n Key.F11 => ImGuiKey.F11,\n Key.F12 => ImGuiKey.F12,\n Key.F13 => ImGuiKey.F13,\n Key.F14 => ImGuiKey.F14,\n Key.F15 => ImGuiKey.F15,\n Key.F16 => ImGuiKey.F16,\n Key.F17 => ImGuiKey.F17,\n Key.F18 => ImGuiKey.F18,\n Key.F19 => ImGuiKey.F19,\n Key.F20 => ImGuiKey.F20,\n Key.F21 => ImGuiKey.F21,\n Key.F22 => ImGuiKey.F22,\n Key.F23 => ImGuiKey.F23,\n Key.F24 => ImGuiKey.F24,\n _ => ImGuiKey.None\n };\n }\n\n private unsafe void SetupRenderState(ImDrawDataPtr drawDataPtr, int framebufferWidth, int framebufferHeight)\n {\n // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill\n _gl.Enable(GLEnum.Blend);\n _gl.BlendEquation(GLEnum.FuncAdd);\n _gl.BlendFuncSeparate(GLEnum.SrcAlpha, GLEnum.OneMinusSrcAlpha, GLEnum.One, GLEnum.OneMinusSrcAlpha);\n _gl.Disable(GLEnum.CullFace);\n _gl.Disable(GLEnum.DepthTest);\n _gl.Disable(GLEnum.StencilTest);\n _gl.Enable(GLEnum.ScissorTest);\n#if !GLES && !LEGACY\n _gl.Disable(GLEnum.PrimitiveRestart);\n _gl.PolygonMode(GLEnum.FrontAndBack, GLEnum.Fill);\n#endif\n\n var L = drawDataPtr.DisplayPos.X;\n var R = drawDataPtr.DisplayPos.X + drawDataPtr.DisplaySize.X;\n var T = drawDataPtr.DisplayPos.Y;\n var B = drawDataPtr.DisplayPos.Y + drawDataPtr.DisplaySize.Y;\n\n Span orthoProjection = stackalloc float[] { 2.0f / (R - L), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (T - B), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, (R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f };\n\n _shader.Use();\n _gl.Uniform1(_attribLocationTex, 0);\n _gl.UniformMatrix4(_attribLocationProjMtx, 1, false, orthoProjection);\n _gl.CheckError(\"Projection\");\n\n _gl.BindSampler(0, 0);\n\n // Setup desired GL state\n // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)\n // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.\n _vertexArrayObject = _gl.GenVertexArray();\n _gl.BindVertexArray(_vertexArrayObject);\n _gl.CheckError(\"VAO\");\n\n // Bind vertex/index buffers and setup attributes for ImDrawVert\n _gl.BindBuffer(GLEnum.ArrayBuffer, _vboHandle);\n _gl.BindBuffer(GLEnum.ElementArrayBuffer, _elementsHandle);\n _gl.EnableVertexAttribArray((uint)_attribLocationVtxPos);\n _gl.EnableVertexAttribArray((uint)_attribLocationVtxUV);\n _gl.EnableVertexAttribArray((uint)_attribLocationVtxColor);\n _gl.VertexAttribPointer((uint)_attribLocationVtxPos, 2, GLEnum.Float, false, (uint)sizeof(ImDrawVert), (void*)0);\n _gl.VertexAttribPointer((uint)_attribLocationVtxUV, 2, GLEnum.Float, false, (uint)sizeof(ImDrawVert), (void*)8);\n _gl.VertexAttribPointer((uint)_attribLocationVtxColor, 4, GLEnum.UnsignedByte, true, (uint)sizeof(ImDrawVert), (void*)16);\n }\n\n private unsafe void RenderImDrawData(ImDrawDataPtr drawDataPtr)\n {\n var framebufferWidth = (int)(drawDataPtr.DisplaySize.X * drawDataPtr.FramebufferScale.X);\n var framebufferHeight = (int)(drawDataPtr.DisplaySize.Y * drawDataPtr.FramebufferScale.Y);\n if ( framebufferWidth <= 0 || framebufferHeight <= 0 )\n {\n return;\n }\n\n // Backup GL state\n _gl.GetInteger(GLEnum.ActiveTexture, out var lastActiveTexture);\n _gl.ActiveTexture(GLEnum.Texture0);\n\n _gl.GetInteger(GLEnum.CurrentProgram, out var lastProgram);\n _gl.GetInteger(GLEnum.TextureBinding2D, out var lastTexture);\n\n _gl.GetInteger(GLEnum.SamplerBinding, out var lastSampler);\n\n _gl.GetInteger(GLEnum.ArrayBufferBinding, out var lastArrayBuffer);\n _gl.GetInteger(GLEnum.VertexArrayBinding, out var lastVertexArrayObject);\n\n#if !GLES\n Span lastPolygonMode = stackalloc int[2];\n _gl.GetInteger(GLEnum.PolygonMode, lastPolygonMode);\n#endif\n\n Span lastScissorBox = stackalloc int[4];\n _gl.GetInteger(GLEnum.ScissorBox, lastScissorBox);\n\n _gl.GetInteger(GLEnum.BlendSrcRgb, out var lastBlendSrcRgb);\n _gl.GetInteger(GLEnum.BlendDstRgb, out var lastBlendDstRgb);\n\n _gl.GetInteger(GLEnum.BlendSrcAlpha, out var lastBlendSrcAlpha);\n _gl.GetInteger(GLEnum.BlendDstAlpha, out var lastBlendDstAlpha);\n\n _gl.GetInteger(GLEnum.BlendEquationRgb, out var lastBlendEquationRgb);\n _gl.GetInteger(GLEnum.BlendEquationAlpha, out var lastBlendEquationAlpha);\n\n var lastEnableBlend = _gl.IsEnabled(GLEnum.Blend);\n var lastEnableCullFace = _gl.IsEnabled(GLEnum.CullFace);\n var lastEnableDepthTest = _gl.IsEnabled(GLEnum.DepthTest);\n var lastEnableStencilTest = _gl.IsEnabled(GLEnum.StencilTest);\n var lastEnableScissorTest = _gl.IsEnabled(GLEnum.ScissorTest);\n\n#if !GLES && !LEGACY\n var lastEnablePrimitiveRestart = _gl.IsEnabled(GLEnum.PrimitiveRestart);\n#endif\n\n SetupRenderState(drawDataPtr, framebufferWidth, framebufferHeight);\n\n // Will project scissor/clipping rectangles into framebuffer space\n var clipOff = drawDataPtr.DisplayPos; // (0,0) unless using multi-viewports\n var clipScale = drawDataPtr.FramebufferScale; // (1,1) unless using retina display which are often (2,2)\n\n // Render command lists\n for ( var n = 0; n < drawDataPtr.CmdListsCount; n++ )\n {\n var cmdListPtr = drawDataPtr.CmdLists[n];\n\n // Upload vertex/index buffers\n\n _gl.BufferData(GLEnum.ArrayBuffer, (nuint)(cmdListPtr.VtxBuffer.Size * sizeof(ImDrawVert)), cmdListPtr.VtxBuffer.Data, GLEnum.StreamDraw);\n _gl.CheckError($\"Data Vert {n}\");\n _gl.BufferData(GLEnum.ElementArrayBuffer, (nuint)(cmdListPtr.IdxBuffer.Size * sizeof(ushort)), cmdListPtr.IdxBuffer.Data, GLEnum.StreamDraw);\n _gl.CheckError($\"Data Idx {n}\");\n\n for ( var cmd_i = 0; cmd_i < cmdListPtr.CmdBuffer.Size; cmd_i++ )\n {\n var cmdPtr = cmdListPtr.CmdBuffer[cmd_i];\n\n if ( cmdPtr.UserCallback != null )\n {\n throw new NotImplementedException();\n }\n\n Vector4 clipRect;\n clipRect.X = (cmdPtr.ClipRect.X - clipOff.X) * clipScale.X;\n clipRect.Y = (cmdPtr.ClipRect.Y - clipOff.Y) * clipScale.Y;\n clipRect.Z = (cmdPtr.ClipRect.Z - clipOff.X) * clipScale.X;\n clipRect.W = (cmdPtr.ClipRect.W - clipOff.Y) * clipScale.Y;\n\n if ( clipRect.X < framebufferWidth && clipRect.Y < framebufferHeight && clipRect.Z >= 0.0f && clipRect.W >= 0.0f )\n {\n // Apply scissor/clipping rectangle\n _gl.Scissor((int)clipRect.X, (int)(framebufferHeight - clipRect.W), (uint)(clipRect.Z - clipRect.X), (uint)(clipRect.W - clipRect.Y));\n _gl.CheckError(\"Scissor\");\n\n // Bind texture, Draw\n _gl.BindTexture(GLEnum.Texture2D, (uint)cmdPtr.TextureId.Handle);\n _gl.CheckError(\"Texture\");\n\n _gl.DrawElementsBaseVertex(GLEnum.Triangles, cmdPtr.ElemCount, GLEnum.UnsignedShort, (void*)(cmdPtr.IdxOffset * sizeof(ushort)), (int)cmdPtr.VtxOffset);\n _gl.CheckError(\"Draw\");\n }\n }\n }\n\n // Destroy the temporary VAO\n _gl.DeleteVertexArray(_vertexArrayObject);\n _vertexArrayObject = 0;\n\n // Restore modified GL state\n _gl.UseProgram((uint)lastProgram);\n _gl.BindTexture(GLEnum.Texture2D, (uint)lastTexture);\n\n _gl.BindSampler(0, (uint)lastSampler);\n\n _gl.ActiveTexture((GLEnum)lastActiveTexture);\n\n _gl.BindVertexArray((uint)lastVertexArrayObject);\n\n _gl.BindBuffer(GLEnum.ArrayBuffer, (uint)lastArrayBuffer);\n _gl.BlendEquationSeparate((GLEnum)lastBlendEquationRgb, (GLEnum)lastBlendEquationAlpha);\n _gl.BlendFuncSeparate((GLEnum)lastBlendSrcRgb, (GLEnum)lastBlendDstRgb, (GLEnum)lastBlendSrcAlpha, (GLEnum)lastBlendDstAlpha);\n\n if ( lastEnableBlend )\n {\n _gl.Enable(GLEnum.Blend);\n }\n else\n {\n _gl.Disable(GLEnum.Blend);\n }\n\n if ( lastEnableCullFace )\n {\n _gl.Enable(GLEnum.CullFace);\n }\n else\n {\n _gl.Disable(GLEnum.CullFace);\n }\n\n if ( lastEnableDepthTest )\n {\n _gl.Enable(GLEnum.DepthTest);\n }\n else\n {\n _gl.Disable(GLEnum.DepthTest);\n }\n\n if ( lastEnableStencilTest )\n {\n _gl.Enable(GLEnum.StencilTest);\n }\n else\n {\n _gl.Disable(GLEnum.StencilTest);\n }\n\n if ( lastEnableScissorTest )\n {\n _gl.Enable(GLEnum.ScissorTest);\n }\n else\n {\n _gl.Disable(GLEnum.ScissorTest);\n }\n\n#if !GLES && !LEGACY\n if ( lastEnablePrimitiveRestart )\n {\n _gl.Enable(GLEnum.PrimitiveRestart);\n }\n else\n {\n _gl.Disable(GLEnum.PrimitiveRestart);\n }\n\n _gl.PolygonMode(GLEnum.FrontAndBack, (GLEnum)lastPolygonMode[0]);\n#endif\n\n _gl.Scissor(lastScissorBox[0], lastScissorBox[1], (uint)lastScissorBox[2], (uint)lastScissorBox[3]);\n }\n\n private void CreateDeviceResources()\n {\n // Backup GL state\n\n _gl.GetInteger(GLEnum.TextureBinding2D, out var lastTexture);\n _gl.GetInteger(GLEnum.ArrayBufferBinding, out var lastArrayBuffer);\n _gl.GetInteger(GLEnum.VertexArrayBinding, out var lastVertexArray);\n\n var vertexSource =\n @\"#version 330\n layout (location = 0) in vec2 Position;\n layout (location = 1) in vec2 UV;\n layout (location = 2) in vec4 Color;\n uniform mat4 ProjMtx;\n out vec2 Frag_UV;\n out vec4 Frag_Color;\n void main()\n {\n Frag_UV = UV;\n Frag_Color = Color;\n gl_Position = ProjMtx * vec4(Position.xy,0,1);\n }\";\n\n var fragmentSource =\n @\"#version 330\n in vec2 Frag_UV;\n in vec4 Frag_Color;\n uniform sampler2D Texture;\n layout (location = 0) out vec4 Out_Color;\n void main()\n {\n Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n }\";\n\n _shader = new Shader(_gl, vertexSource, fragmentSource);\n\n _attribLocationTex = _shader.GetUniformLocation(\"Texture\");\n _attribLocationProjMtx = _shader.GetUniformLocation(\"ProjMtx\");\n _attribLocationVtxPos = _shader.GetAttribLocation(\"Position\");\n _attribLocationVtxUV = _shader.GetAttribLocation(\"UV\");\n _attribLocationVtxColor = _shader.GetAttribLocation(\"Color\");\n\n _vboHandle = _gl.GenBuffer();\n _elementsHandle = _gl.GenBuffer();\n\n RecreateFontDeviceTexture();\n\n // Restore modified GL state\n _gl.BindTexture(GLEnum.Texture2D, (uint)lastTexture);\n _gl.BindBuffer(GLEnum.ArrayBuffer, (uint)lastArrayBuffer);\n\n _gl.BindVertexArray((uint)lastVertexArray);\n\n _gl.CheckError(\"End of ImGui setup\");\n }\n\n /// \n /// Creates the texture used to render text.\n /// \n private unsafe void RecreateFontDeviceTexture()\n {\n // Build texture atlas\n var io = ImGui.GetIO();\n byte* pixels = null;\n var width = 0;\n var height = 0;\n var bytesPerPixel = 0;\n io.Fonts.GetTexDataAsRGBA32(ref pixels, ref width, ref height, ref bytesPerPixel); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.\n\n // Upload texture to graphics system\n _gl.GetInteger(GLEnum.TextureBinding2D, out var lastTexture);\n\n _fontTexture = new Texture(_gl, width, height, new IntPtr(pixels));\n _fontTexture.Bind();\n _fontTexture.SetMagFilter(TextureMagFilter.Linear);\n _fontTexture.SetMinFilter(TextureMinFilter.Linear);\n\n // Store our identifier\n io.Fonts.SetTexID(new ImTextureID(_fontTexture.GlTexture));\n\n // Restore state\n _gl.BindTexture(GLEnum.Texture2D, (uint)lastTexture);\n }\n\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n private delegate void SetClipboardDelegate(IntPtr data);\n\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n private delegate IntPtr GetClipboardDelegate();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/PcmResampler.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic class PcmResampler\n{\n // Constants for audio format\n private const int BYTES_PER_SAMPLE = 2;\n\n private const int MAX_FRAME_SIZE = 1920;\n\n private readonly float[] _filterCoefficients;\n\n private readonly int _filterDelay;\n\n // Filter configuration\n private readonly int _filterTaps;\n\n private readonly float[] _floatHistory;\n\n private readonly short[] _history;\n\n // Sample rate configuration\n\n // Pre-allocated working buffers\n private readonly short[] _inputSamples;\n\n private int _historyLength;\n\n // State tracking\n private float _position = 0.0f;\n\n public PcmResampler(int inputSampleRate = 48000, int outputSampleRate = 16000)\n {\n if ( inputSampleRate <= 0 || outputSampleRate <= 0 )\n {\n throw new ArgumentException(\"Sample rates must be positive values\");\n }\n\n InputSampleRate = inputSampleRate;\n OutputSampleRate = outputSampleRate;\n ResampleRatio = (float)InputSampleRate / OutputSampleRate;\n\n _filterTaps = DetermineOptimalFilterTaps(ResampleRatio);\n _filterDelay = _filterTaps / 2;\n\n var cutoffFrequency = Math.Min(0.45f * OutputSampleRate, 0.9f * OutputSampleRate / 2) / InputSampleRate;\n _filterCoefficients = GenerateLowPassFilter(_filterTaps, cutoffFrequency);\n\n _history = new short[_filterTaps + 10];\n _floatHistory = new float[_filterTaps + 10];\n _historyLength = 0;\n\n _inputSamples = new short[MAX_FRAME_SIZE];\n }\n\n public float ResampleRatio { get; }\n\n public int InputSampleRate { get; }\n\n public int OutputSampleRate { get; }\n\n private int DetermineOptimalFilterTaps(float ratio)\n {\n if ( Math.Abs(ratio - Math.Round(ratio)) < 0.01f )\n {\n return Math.Max(24, (int)(12 * ratio));\n }\n\n return Math.Max(36, (int)(18 * ratio));\n }\n\n private float[] GenerateLowPassFilter(int taps, float cutoff)\n {\n var coefficients = new float[taps];\n var center = taps / 2;\n\n var sum = 0.0;\n for ( var i = 0; i < taps; i++ )\n {\n if ( i == center )\n {\n coefficients[i] = (float)(2.0 * Math.PI * cutoff);\n }\n else\n {\n var x = 2.0 * Math.PI * cutoff * (i - center);\n coefficients[i] = (float)(Math.Sin(x) / x);\n }\n\n var window = 0.42 - 0.5 * Math.Cos(2.0 * Math.PI * i / (taps - 1))\n + 0.08 * Math.Cos(4.0 * Math.PI * i / (taps - 1));\n\n coefficients[i] *= (float)window;\n\n sum += coefficients[i];\n }\n\n for ( var i = 0; i < taps; i++ )\n {\n coefficients[i] /= (float)sum;\n }\n\n return coefficients;\n }\n\n public int Process(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length / BYTES_PER_SAMPLE;\n ConvertToShorts(input, _inputSamples, inputSampleCount);\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples * BYTES_PER_SAMPLE )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetSampleWithHistory(sampleIndex, _inputSamples, inputSampleCount);\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n if ( outputIndex < maxOutputSamples )\n {\n BinaryPrimitives.WriteInt16LittleEndian(\n output.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateHistory(_inputSamples, inputSampleCount);\n _position -= inputSampleCount;\n\n return outputIndex * BYTES_PER_SAMPLE;\n }\n\n public int Process(Stream input, Memory output)\n {\n var buffer = new byte[MAX_FRAME_SIZE * BYTES_PER_SAMPLE];\n var bytesRead = input.Read(buffer, 0, buffer.Length);\n\n return Process(buffer.AsSpan(0, bytesRead), output.Span);\n }\n\n public int ProcessInPlace(Span buffer)\n {\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length / BYTES_PER_SAMPLE;\n\n // Make a copy of the input for processing\n Span inputCopy = stackalloc short[inputSampleCount];\n for ( var i = 0; i < inputSampleCount; i++ )\n {\n inputCopy[i] = BinaryPrimitives.ReadInt16LittleEndian(buffer.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // Calculate positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n short sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _history[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n BinaryPrimitives.WriteInt16LittleEndian(\n buffer.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n // We need to keep the input history despite having processed in-place\n UpdateHistory(inputCopy.ToArray(), inputSampleCount);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount * BYTES_PER_SAMPLE;\n }\n\n public int ProcessFloat(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length;\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetFloatSampleWithHistory(sampleIndex, input);\n sum += sample * _filterCoefficients[tap];\n }\n\n if ( outputIndex < maxOutputSamples )\n {\n output[outputIndex] = sum;\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateFloatHistory(input);\n _position -= inputSampleCount;\n\n return outputIndex;\n }\n\n public int ProcessFloatInPlace(Span buffer)\n {\n // For in-place, we must work backward to avoid overwriting unprocessed input\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length;\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // First, store the full input for history and reference\n var inputCopy = new float[inputSampleCount];\n buffer.CopyTo(inputCopy);\n\n // Calculate sample positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n float sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _floatHistory[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0f;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n buffer[outputIndex] = sum;\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n UpdateFloatHistory(inputCopy);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount;\n }\n\n private short GetSampleWithHistory(int index, short[] inputSamples, int inputSampleCount)\n {\n if ( index >= 0 && index < inputSampleCount )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _history[_historyLength + index];\n }\n\n return 0;\n }\n\n private float GetFloatSampleWithHistory(int index, ReadOnlySpan inputSamples)\n {\n if ( index >= 0 && index < inputSamples.Length )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _floatHistory[_historyLength + index];\n }\n\n return 0f;\n }\n\n private void UpdateHistory(short[] currentFrame, int frameLength)\n {\n var samplesToKeep = Math.Min(frameLength, _history.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _history.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_history, _historyLength - unusedHistorySamples, _history, 0, unusedHistorySamples);\n }\n\n Array.Copy(currentFrame, frameLength - samplesToKeep, _history, unusedHistorySamples, samplesToKeep);\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _history.Length);\n }\n\n private void UpdateFloatHistory(ReadOnlySpan currentFrame)\n {\n var samplesToKeep = Math.Min(currentFrame.Length, _floatHistory.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _floatHistory.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_floatHistory, _historyLength - unusedHistorySamples, _floatHistory, 0, unusedHistorySamples);\n }\n\n for ( var i = 0; i < samplesToKeep; i++ )\n {\n _floatHistory[unusedHistorySamples + i] = currentFrame[currentFrame.Length - samplesToKeep + i];\n }\n\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _floatHistory.Length);\n }\n\n private void ConvertToShorts(ReadOnlySpan input, short[] output, int sampleCount)\n {\n for ( var i = 0; i < sampleCount; i++ )\n {\n output[i] = BinaryPrimitives.ReadInt16LittleEndian(input.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n }\n\n public void Reset()\n {\n _position = 0;\n _historyLength = 0;\n Array.Clear(_history, 0, _history.Length);\n Array.Clear(_floatHistory, 0, _floatHistory.Length);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Adapters/IOutputAdapter.cs", "using System.Threading.Channels;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\n\npublic interface IOutputAdapter : IAsyncDisposable\n{\n Guid AdapterId { get; }\n\n ValueTask InitializeAsync(Guid sessionId, CancellationToken cancellationToken);\n\n ValueTask StartAsync(CancellationToken cancellationToken);\n\n ValueTask StopAsync(CancellationToken cancellationToken);\n}\n\npublic interface IAudioOutputAdapter : IOutputAdapter\n{\n Task SendAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n CancellationToken cancellationToken = default);\n}\n\npublic interface ITextOutputAdapter : IOutputAdapter\n{\n Task SendAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/IdleBlinkingAnimationService.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour;\n\n/// \n/// Manages Live2D model idle animations and custom automatic blinking.\n/// Ensures a random idle animation from the 'Idle' group is playing if available\n/// and handles periodic blinking by directly manipulating eye parameters.\n/// Blinking operates independently of the main animation system.\n/// \npublic sealed class IdleBlinkingAnimationService : ILive2DAnimationService\n{\n private const string IDLE_MOTION_GROUP = \"Idle\";\n\n private const MotionPriority IDLE_MOTION_PRIORITY = MotionPriority.PriorityIdle;\n\n private const string PARAM_EYE_L_OPEN = \"ParamEyeLOpen\";\n\n private const string PARAM_EYE_R_OPEN = \"ParamEyeROpen\";\n\n private const float BLINK_INTERVAL_MIN_SECONDS = 1.5f;\n\n private const float BLINK_INTERVAL_MAX_SECONDS = 6.0f;\n\n private const float BLINK_CLOSING_DURATION = 0.06f;\n\n private const float BLINK_CLOSED_DURATION = 0.05f;\n\n private const float BLINK_OPENING_DURATION = 0.10f;\n\n private const float EYE_OPEN_VALUE = 1.0f;\n\n private const float EYE_CLOSED_VALUE = 0.0f;\n\n private readonly ILogger _logger;\n\n private readonly Random _random = new();\n\n private float _blinkPhaseTimer = 0.0f;\n\n private BlinkState _currentBlinkState = BlinkState.Idle;\n\n private CubismMotionQueueEntry? _currentIdleMotionEntry;\n\n private bool _disposed = false;\n\n private bool _eyeParamsValid = false;\n\n private bool _isBlinking = false;\n\n private bool _isIdleAnimationAvailable = false;\n\n private bool _isStarted = false;\n\n private LAppModel? _model;\n\n private float _timeUntilNextBlink = 0.0f;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logger instance for logging messages.\n public IdleBlinkingAnimationService(ILogger logger)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n SetNextBlinkInterval();\n }\n\n #region Asset Validation\n\n /// \n /// Checks if the required assets (idle motion group, eye parameters) are available in the model.\n /// Sets the internal flags `_isIdleAnimationAvailable` and `_eyeParamsValid`.\n /// \n private void ValidateModelAssets()\n {\n if ( _model == null )\n {\n return;\n }\n\n _logger.LogDebug(\"Validating configured idle/blinking mappings against model assets...\");\n\n _isIdleAnimationAvailable = false;\n foreach ( var motionKey in _model.Motions )\n {\n var groupName = LAppModel.GetMotionGroupName(motionKey);\n if ( groupName == IDLE_MOTION_GROUP )\n {\n _isIdleAnimationAvailable = true;\n }\n }\n\n if ( _isIdleAnimationAvailable )\n {\n _logger.LogDebug(\"Idle motion group '{IdleGroup}' is configured and available in the model.\", IDLE_MOTION_GROUP);\n }\n else\n {\n _logger.LogWarning(\"Configured IDLE_MOTION_GROUP ('{IdleGroup}') not found in model! Idle animations disabled.\", IDLE_MOTION_GROUP);\n }\n\n _eyeParamsValid = false;\n\n try\n {\n // An invalid index (usually -1) means the parameter doesn't exist.\n var leftEyeIndex = _model.Model.GetParameterIndex(PARAM_EYE_L_OPEN);\n var rightEyeIndex = _model.Model.GetParameterIndex(PARAM_EYE_R_OPEN);\n\n if ( leftEyeIndex >= 0 && rightEyeIndex >= 0 )\n {\n _eyeParamsValid = true;\n _logger.LogDebug(\"Required eye parameters found: '{ParamL}' (Index: {IndexL}), '{ParamR}' (Index: {IndexR}).\",\n PARAM_EYE_L_OPEN, leftEyeIndex, PARAM_EYE_R_OPEN, rightEyeIndex);\n }\n else\n {\n if ( leftEyeIndex < 0 )\n {\n _logger.LogWarning(\"Eye parameter '{ParamL}' not found in the model.\", PARAM_EYE_L_OPEN);\n }\n\n if ( rightEyeIndex < 0 )\n {\n _logger.LogWarning(\"Eye parameter '{ParamR}' not found in the model.\", PARAM_EYE_R_OPEN);\n }\n\n _logger.LogWarning(\"Automatic blinking disabled because one or both eye parameters are missing.\");\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error occurred while validating eye parameters. Blinking disabled.\");\n _eyeParamsValid = false;\n }\n }\n\n #endregion\n\n private enum BlinkState\n {\n Idle,\n\n Closing,\n\n Closed,\n\n Opening\n }\n\n #region ILive2DAnimationService Implementation\n\n /// \n /// Starts the service with the specified Live2D model.\n /// Validates required assets (idle motion group, eye parameters) and initializes state.\n /// \n /// The Live2D model instance to animate.\n /// Thrown if model is null.\n /// Thrown if the service has been disposed.\n public void Start(LAppModel model)\n {\n ObjectDisposedException.ThrowIf(_disposed, typeof(IdleBlinkingAnimationService));\n\n if ( _isStarted )\n {\n _logger.LogWarning(\"Service already started. Call Stop() first if reconfiguration is needed.\");\n\n return;\n }\n\n _model = model ?? throw new ArgumentNullException(nameof(model));\n\n ValidateModelAssets();\n\n SetNextBlinkInterval();\n _currentBlinkState = BlinkState.Idle;\n _isBlinking = false;\n _blinkPhaseTimer = 0f;\n ResetEyesToOpenState();\n\n _currentIdleMotionEntry = null;\n\n _isStarted = true;\n _logger.LogInformation(\"IdleBlinkingAnimationService started. Idle animations: {IdleStatus}, Blinking: {BlinkStatus}.\",\n _isIdleAnimationAvailable ? \"Enabled\" : \"Disabled\",\n _eyeParamsValid ? \"Enabled\" : \"Disabled\");\n\n if ( _isIdleAnimationAvailable && _currentIdleMotionEntry == null )\n {\n TryStartIdleMotion();\n }\n }\n\n /// \n /// Stops the service, resetting blinking and clearing the tracked idle motion.\n /// Attempts to leave the eyes in an open state.\n /// \n public void Stop()\n {\n if ( !_isStarted || _disposed )\n {\n return;\n }\n\n _isStarted = false;\n\n ResetEyesToOpenState();\n\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n _blinkPhaseTimer = 0f;\n\n _currentIdleMotionEntry = null;\n // Note: The motion itself isn't forcibly stopped here; Instead we\n // rely on the model's lifecycle management to handle it.\n\n _logger.LogInformation(\"IdleBlinkingAnimationService stopped.\");\n }\n\n /// \n /// Updates the idle animation and blinking state based on elapsed time.\n /// Should be called once per frame.\n /// \n /// The time elapsed since the last update call, in seconds.\n public void Update(float deltaTime)\n {\n if ( !_isStarted || _model?.Model == null || _disposed || deltaTime <= 0.0f )\n {\n return;\n }\n\n UpdateIdleMotion();\n\n if ( _eyeParamsValid )\n {\n UpdateBlinking(deltaTime);\n }\n }\n\n #endregion\n\n #region Core Logic: Idle\n\n private void UpdateIdleMotion()\n {\n if ( _currentIdleMotionEntry is { Finished: true } )\n {\n _logger.LogTrace(\"Tracked idle motion finished.\");\n _currentIdleMotionEntry = null;\n }\n\n if ( _isIdleAnimationAvailable && _currentIdleMotionEntry == null )\n {\n TryStartIdleMotion();\n }\n }\n\n private void TryStartIdleMotion()\n {\n if ( _model == null )\n {\n return;\n }\n\n _logger.LogTrace(\"Attempting to start a new idle motion for group '{IdleGroup}'.\", IDLE_MOTION_GROUP);\n\n try\n {\n var newEntry = _model.StartRandomMotion(IDLE_MOTION_GROUP, IDLE_MOTION_PRIORITY);\n\n _currentIdleMotionEntry = newEntry;\n\n if ( _currentIdleMotionEntry != null )\n {\n _logger.LogDebug(\"Successfully started idle motion.\");\n }\n // _logger.LogWarning(\"Failed to start idle motion for group '{IdleGroup}'. The group might be empty or invalid.\", IDLE_MOTION_GROUP);\n // Optionally disable idle animations if it fails consistently?\n // We don't because sometimes this occurs when another animation with the same or higher priority is also playing.\n // _isIdleAnimationAvailable = false;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Exception occurred while trying to start idle motion for group '{IdleGroup}'. Disabling idle animations.\", IDLE_MOTION_GROUP);\n _isIdleAnimationAvailable = false;\n _currentIdleMotionEntry = null;\n }\n }\n\n #endregion\n\n #region Core Logic: Blinking\n\n private void UpdateBlinking(float deltaTime)\n {\n try\n {\n if ( _isBlinking )\n {\n _blinkPhaseTimer += deltaTime;\n float eyeValue;\n\n switch ( _currentBlinkState )\n {\n case BlinkState.Closing:\n // Calculate progress towards closed state (1.0 -> 0.0)\n eyeValue = Math.Max(EYE_CLOSED_VALUE, EYE_OPEN_VALUE - _blinkPhaseTimer / BLINK_CLOSING_DURATION);\n if ( _blinkPhaseTimer >= BLINK_CLOSING_DURATION )\n {\n _currentBlinkState = BlinkState.Closed;\n _blinkPhaseTimer = 0f;\n eyeValue = EYE_CLOSED_VALUE;\n _logger.LogTrace(\"Blink phase: Closed\");\n }\n\n break;\n\n case BlinkState.Closed:\n eyeValue = EYE_CLOSED_VALUE;\n if ( _blinkPhaseTimer >= BLINK_CLOSED_DURATION )\n {\n _currentBlinkState = BlinkState.Opening;\n _blinkPhaseTimer = 0f;\n _logger.LogTrace(\"Blink phase: Opening\");\n }\n\n break;\n\n case BlinkState.Opening:\n // Calculate progress towards open state (0.0 -> 1.0)\n eyeValue = Math.Min(EYE_OPEN_VALUE, EYE_CLOSED_VALUE + _blinkPhaseTimer / BLINK_OPENING_DURATION);\n if ( _blinkPhaseTimer >= BLINK_OPENING_DURATION )\n {\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n SetNextBlinkInterval();\n eyeValue = EYE_OPEN_VALUE;\n _logger.LogTrace(\"Blink finished. Next blink in {Interval:F2}s\", _timeUntilNextBlink);\n SetEyeParameters(eyeValue);\n\n return; // Exit early as state is reset\n }\n\n break;\n\n case BlinkState.Idle:\n default:\n _logger.LogWarning(\"Invalid blink state detected while _isBlinking was true. Resetting blink state.\");\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n SetNextBlinkInterval();\n ResetEyesToOpenState();\n\n return; // Exit early\n }\n\n SetEyeParameters(eyeValue);\n }\n else\n {\n _timeUntilNextBlink -= deltaTime;\n if ( _timeUntilNextBlink <= 0f )\n {\n // Start a new blink cycle\n _isBlinking = true;\n _currentBlinkState = BlinkState.Closing;\n _blinkPhaseTimer = 0f;\n _logger.LogTrace(\"Starting blink.\");\n // Set initial closing value immediately? Or wait for next frame?\n // Current logic waits for the next frame's update. This is usually fine.\n }\n // IMPORTANT: Do not call SetEyeParameters here when idle.\n // Other animations (like facial expressions) might be controlling the eyes.\n // We only take control during the blink itself.\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during blinking update. Disabling blinking for safety.\");\n _eyeParamsValid = false; // Prevent further blinking attempts\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n ResetEyesToOpenState();\n }\n }\n\n /// \n /// Sets the values for the left and right eye openness parameters.\n /// Includes error handling to disable blinking if parameters become invalid.\n /// \n /// The value to set (typically between 0.0 and 1.0).\n private void SetEyeParameters(float value)\n {\n // Redundant checks, but safe:\n if ( _model?.Model == null || !_eyeParamsValid )\n {\n return;\n }\n\n try\n {\n _model.Model.SetParameterValue(PARAM_EYE_L_OPEN, value);\n _model.Model.SetParameterValue(PARAM_EYE_R_OPEN, value);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to set eye parameters (L:'{ParamL}', R:'{ParamR}') to value {Value}. Disabling blinking.\",\n PARAM_EYE_L_OPEN, PARAM_EYE_R_OPEN, value);\n\n _eyeParamsValid = false;\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n // Don't try to reset eyes here, as the SetParameterValue call itself failed.\n }\n }\n\n private void ResetEyesToOpenState()\n {\n if ( _model?.Model != null && _eyeParamsValid )\n {\n _logger.LogTrace(\"Attempting to reset eyes to open state.\");\n SetEyeParameters(EYE_OPEN_VALUE);\n }\n else\n {\n _logger.LogTrace(\"Skipping reset eyes to open state (Model null or eye params invalid).\");\n }\n }\n\n /// \n /// Calculates and sets the random time interval until the next blink should start.\n /// \n private void SetNextBlinkInterval()\n {\n _timeUntilNextBlink = (float)(_random.NextDouble() *\n (BLINK_INTERVAL_MAX_SECONDS - BLINK_INTERVAL_MIN_SECONDS) +\n BLINK_INTERVAL_MIN_SECONDS);\n }\n\n #endregion\n\n #region IDisposable Implementation\n\n public void Dispose() { Dispose(true); }\n\n private void Dispose(bool disposing)\n {\n if ( !_disposed )\n {\n if ( disposing )\n {\n _logger.LogDebug(\"Disposing IdleBlinkingAnimationService...\");\n Stop();\n _model = null;\n _logger.LogInformation(\"IdleBlinkingAnimationService disposed.\");\n }\n\n _disposed = true;\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/WhisperNetSpeechTranscriptor.cs", "using System.Globalization;\nusing System.Runtime.CompilerServices;\n\nusing PersonaEngine.Lib.Audio;\n\nusing Whisper.net;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\ninternal class WhisperNetSpeechTranscriptor(WhisperProcessor whisperProcessor) : ISpeechTranscriptor\n{\n public async IAsyncEnumerable TranscribeAsync(IAudioSource source, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n if ( source.ChannelCount != 1 )\n {\n throw new NotSupportedException(\"Only mono-channel audio is supported. Consider one channel aggregation on the audio source.\");\n }\n\n if ( source.SampleRate != 16000 )\n {\n throw new NotSupportedException(\"Only 16 kHz audio is supported. Consider resampling before calling this transcriptor.\");\n }\n\n var samples = await source.GetSamplesAsync(0, cancellationToken: cancellationToken);\n\n await foreach ( var segment in whisperProcessor.ProcessAsync(samples, cancellationToken) )\n {\n yield return new TranscriptSegment {\n Metadata = source.Metadata,\n StartTime = segment.Start,\n Duration = segment.End - segment.Start,\n ConfidenceLevel = segment.Probability,\n Language = new CultureInfo(segment.Language),\n Text = segment.Text,\n Tokens = segment?.Tokens.Select(t => new TranscriptToken {\n Id = t.Id,\n Text = t.Text,\n Confidence = t.Probability,\n ConfidenceLog = t.ProbabilityLog,\n StartTime = TimeSpan.FromMilliseconds(t.Start),\n Duration = TimeSpan.FromMilliseconds(t.End - t.Start),\n DtwTimestamp = t.DtwTimestamp,\n TimestampConfidence = t.TimestampProbability,\n TimestampConfidenceSum = t.TimestampProbabilitySum\n }).ToList()\n };\n }\n }\n\n public async ValueTask DisposeAsync() { await whisperProcessor.DisposeAsync(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/TtsEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic record TtsStreamStartEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent { }\n\npublic record TtsChunkEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, AudioSegment Chunk) : IOutputEvent { }\n\npublic record TtsStreamEndEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, CompletionReason FinishReason) : IOutputEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppModel.cs", "using System.Text.Json;\n\nusing PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Effect;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\npublic class LAppModel : CubismUserModel\n{\n /// \n /// 読み込まれている表情のリスト\n /// \n private readonly Dictionary _expressions = [];\n\n /// \n /// モデルに設定されたまばたき機能用パラメータID\n /// \n private readonly List _eyeBlinkIds = [];\n\n private readonly LAppDelegate _lapp;\n\n /// \n /// モデルに設定されたリップシンク機能用パラメータID\n /// \n private readonly List _lipSyncIds = [];\n\n /// \n /// モデルセッティングが置かれたディレクトリ\n /// \n private readonly string _modelHomeDir;\n\n /// \n /// モデルセッティング情報\n /// \n private readonly ModelSettingObj _modelSetting;\n\n /// \n /// 読み込まれているモーションのリスト\n /// \n private readonly Dictionary _motions = [];\n\n private readonly Random _random = new();\n\n /// \n /// wavファイルハンドラ\n /// \n public LAppWavFileHandler _wavFileHandler = new();\n\n public static string GetMotionGroupName(string motionName)\n {\n var underscoreIndex = motionName.LastIndexOf('_');\n if ( underscoreIndex > 0 && int.TryParse(motionName.AsSpan(underscoreIndex + 1), out _) )\n {\n return motionName[..underscoreIndex];\n }\n\n return motionName; // Treat whole name as group if no \"_Number\" suffix\n }\n \n public Action? ValueUpdate;\n\n public LAppModel(LAppDelegate lapp, string dir, string fileName)\n {\n _lapp = lapp;\n\n if ( LAppDefine.MocConsistencyValidationEnable )\n {\n _mocConsistency = true;\n }\n\n IdParamAngleX = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamAngleX);\n\n IdParamAngleY = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamAngleY);\n\n IdParamAngleZ = CubismFramework.CubismIdManager.GetId(CubismDefaultParameterId.ParamAngleZ);\n IdParamBodyAngleX = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamBodyAngleX);\n\n IdParamEyeBallX = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamEyeBallX);\n\n IdParamEyeBallY = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamEyeBallY);\n\n _modelHomeDir = dir;\n\n CubismLog.Debug($\"[Live2D]load model setting: {fileName}\");\n\n using var stream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n\n _modelSetting = JsonSerializer.Deserialize(stream, ModelSettingObjContext.Default.ModelSettingObj)\n ?? throw new Exception(\"model3.json error\");\n\n Updating = true;\n Initialized = false;\n\n //Cubism Model\n var path = _modelSetting.FileReferences?.Moc;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( !File.Exists(path) )\n {\n throw new Exception(\"model is null\");\n }\n\n CubismLog.Debug($\"[Live2D]create model: {path}\");\n\n LoadModel(File.ReadAllBytes(path), _mocConsistency);\n }\n\n //Expression\n if ( _modelSetting.FileReferences?.Expressions?.Count > 0 )\n {\n for ( var i = 0; i < _modelSetting.FileReferences.Expressions.Count; i++ )\n {\n var item = _modelSetting.FileReferences.Expressions[i];\n var name = item.Name;\n path = item.File;\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( !File.Exists(path) )\n {\n continue;\n }\n\n var motion = new CubismExpressionMotion(path);\n\n if ( _expressions.ContainsKey(name) )\n {\n _expressions[name] = motion;\n }\n else\n {\n _expressions.Add(name, motion);\n }\n }\n }\n\n //Physics\n path = _modelSetting.FileReferences?.Physics;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( File.Exists(path) )\n {\n LoadPhysics(path);\n }\n }\n\n //Pose\n path = _modelSetting.FileReferences?.Pose;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( File.Exists(path) )\n {\n LoadPose(path);\n }\n }\n\n //EyeBlink\n if ( _modelSetting.IsExistEyeBlinkParameters() )\n {\n _eyeBlink = new CubismEyeBlink(_modelSetting);\n }\n\n LoadBreath();\n\n //UserData\n path = _modelSetting.FileReferences?.UserData;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( File.Exists(path) )\n {\n LoadUserData(path);\n }\n }\n\n // EyeBlinkIds\n if ( _eyeBlink != null )\n {\n _eyeBlinkIds.AddRange(_eyeBlink.ParameterIds);\n }\n\n // LipSyncIds\n if ( _modelSetting.IsExistLipSyncParameters() )\n {\n foreach ( var item in _modelSetting.Groups )\n {\n if ( item.Name == CubismModelSettingJson.LipSync )\n {\n _lipSyncIds.AddRange(item.Ids);\n }\n }\n }\n\n //Layout\n Dictionary layout = [];\n _modelSetting.GetLayoutMap(layout);\n ModelMatrix.SetupFromLayout(layout);\n\n Model.SaveParameters();\n\n if ( _modelSetting.FileReferences?.Motions?.Count > 0 )\n {\n foreach ( var item in _modelSetting.FileReferences.Motions )\n {\n PreloadMotionGroup(item.Key);\n }\n }\n\n _motionManager.StopAllMotions();\n\n Updating = false;\n Initialized = true;\n\n CreateRenderer(new CubismRenderer_OpenGLES2(_lapp.GL, Model));\n\n SetupTextures();\n }\n\n public List Motions => new(_motions.Keys);\n\n public List Expressions => new(_expressions.Keys);\n\n public List<(string, int, float)> Parts\n {\n get\n {\n var list = new List<(string, int, float)>();\n var count = Model.GetPartCount();\n for ( var a = 0; a < count; a++ )\n {\n list.Add((Model.GetPartId(a),\n a, Model.GetPartOpacity(a)));\n }\n\n return list;\n }\n }\n\n public List Parameters => new(Model.ParameterIds);\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n public float UserTimeSeconds { get; set; }\n\n public bool RandomMotion { get; set; } = true;\n\n public bool CustomValueUpdate { get; set; }\n\n /// \n /// パラメータID: ParamAngleX\n /// \n public string IdParamAngleX { get; set; }\n\n /// \n /// パラメータID: ParamAngleY\n /// \n public string IdParamAngleY { get; set; }\n\n /// \n /// パラメータID: ParamAngleZ\n /// \n public string IdParamAngleZ { get; set; }\n\n /// \n /// パラメータID: ParamBodyAngleX\n /// \n public string IdParamBodyAngleX { get; set; }\n\n /// \n /// パラメータID: ParamEyeBallX\n /// \n public string IdParamEyeBallX { get; set; }\n\n /// \n /// パラメータID: ParamEyeBallXY\n /// \n public string IdParamEyeBallY { get; set; }\n\n public string IdParamBreath { get; set; } = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamBreath);\n\n public event Action? Motion;\n\n public new void Dispose()\n {\n base.Dispose();\n\n _motions.Clear();\n _expressions.Clear();\n\n if ( _modelSetting.FileReferences?.Motions.Count > 0 )\n {\n foreach ( var item in _modelSetting.FileReferences.Motions )\n {\n ReleaseMotionGroup(item.Key);\n }\n }\n }\n\n public void LoadBreath()\n {\n //Breath\n _breath = new CubismBreath {\n Parameters = [\n new BreathParameterData {\n ParameterId = IdParamAngleX,\n Offset = 0.0f,\n Peak = 15.0f,\n Cycle = 6.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamAngleY,\n Offset = 0.0f,\n Peak = 8.0f,\n Cycle = 3.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamAngleZ,\n Offset = 0.0f,\n Peak = 10.0f,\n Cycle = 5.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamBodyAngleX,\n Offset = 0.0f,\n Peak = 4.0f,\n Cycle = 15.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamBreath,\n Offset = 0.5f,\n Peak = 0.5f,\n Cycle = 3.2345f,\n Weight = 0.5f\n }\n ]\n };\n }\n\n /// \n /// レンダラを再構築する\n /// \n public void ReloadRenderer()\n {\n DeleteRenderer();\n\n CreateRenderer(new CubismRenderer_OpenGLES2(_lapp.GL, Model));\n\n SetupTextures();\n }\n\n /// \n /// モデルの更新処理。モデルのパラメータから描画状態を決定する。\n /// \n public void Update()\n {\n var deltaTimeSeconds = LAppPal.DeltaTime;\n UserTimeSeconds += deltaTimeSeconds;\n\n _dragManager.Update(deltaTimeSeconds);\n _dragX = _dragManager.FaceX;\n _dragY = _dragManager.FaceY;\n\n // モーションによるパラメータ更新の有無\n var motionUpdated = false;\n\n //-----------------------------------------------------------------\n Model.LoadParameters(); // 前回セーブされた状態をロード\n if ( _motionManager.IsFinished() && RandomMotion )\n {\n // モーションの再生がない場合、待機モーションの中からランダムで再生する\n StartRandomMotion(LAppDefine.MotionGroupIdle, MotionPriority.PriorityIdle);\n }\n else\n {\n motionUpdated = _motionManager.UpdateMotion(Model, deltaTimeSeconds); // モーションを更新\n }\n\n Model.SaveParameters(); // 状態を保存\n\n //-----------------------------------------------------------------\n\n // 不透明度\n Opacity = Model.GetModelOpacity();\n\n // まばたき\n if ( !motionUpdated )\n {\n // メインモーションの更新がないとき\n // _eyeBlink?.UpdateParameters(Model, deltaTimeSeconds); // 目パチ\n }\n\n _expressionManager?.UpdateMotion(Model, deltaTimeSeconds); // 表情でパラメータ更新(相対変化)\n\n if ( CustomValueUpdate )\n {\n ValueUpdate?.Invoke(this);\n }\n else\n {\n //ドラッグによる変化\n //ドラッグによる顔の向きの調整\n Model.AddParameterValue(IdParamAngleX, _dragX * 30); // -30から30の値を加える\n Model.AddParameterValue(IdParamAngleY, _dragY * 30);\n Model.AddParameterValue(IdParamAngleZ, _dragX * _dragY * -30);\n\n //ドラッグによる体の向きの調整\n Model.AddParameterValue(IdParamBodyAngleX, _dragX * 10); // -10から10の値を加える\n\n //ドラッグによる目の向きの調整\n Model.AddParameterValue(IdParamEyeBallX, _dragX); // -1から1の値を加える\n Model.AddParameterValue(IdParamEyeBallY, _dragY);\n }\n\n // 呼吸など\n // _breath?.UpdateParameters(Model, deltaTimeSeconds);\n\n // 物理演算の設定\n _physics?.Evaluate(Model, deltaTimeSeconds);\n\n // リップシンクの設定\n // if ( _lipSync )\n // {\n // // リアルタイムでリップシンクを行う場合、システムから音量を取得して0〜1の範囲で値を入力します。\n // var value = 0.0f;\n //\n // // 状態更新/RMS値取得\n // _wavFileHandler.Update(deltaTimeSeconds);\n // value = (float)_wavFileHandler.GetRms();\n //\n // var weight = 3f; // Configure it as needed.\n //\n // for ( var i = 0; i < _lipSyncIds.Count; ++i )\n // {\n // Model.SetParameterValue(_lipSyncIds[i], value * weight);\n // }\n // }\n\n // ポーズの設定\n _pose?.UpdateParameters(Model, deltaTimeSeconds);\n\n Model.Update();\n }\n\n /// \n /// モデルを描画する処理。モデルを描画する空間のView-Projection行列を渡す。\n /// \n /// View-Projection行列\n public void Draw(CubismMatrix44 matrix)\n {\n if ( Model == null )\n {\n return;\n }\n\n matrix.MultiplyByMatrix(ModelMatrix);\n if ( Renderer is CubismRenderer_OpenGLES2 ren )\n {\n ren.ClearColor = _lapp.BGColor;\n ren.SetMvpMatrix(matrix);\n }\n\n DoDraw();\n }\n\n /// \n /// Starts playing the motion specified by the argument.\n /// \n /// Motion Group Name\n /// Number in group\n /// Priority\n /// The callback function that is called when the motion playback ends. If NULL, it will not be called.\n /// Returns the identification number of the started motion. Used as an argument for IsFinished() to determine whether an individual motion has finished. Returns \"-1\" if the motion cannot be started.\n public CubismMotionQueueEntry? StartMotion(string name, MotionPriority priority, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n var temp = name.Split(\"_\");\n if ( temp.Length != 2 )\n {\n throw new Exception(\"motion name error\");\n }\n\n return StartMotion(temp[0], int.Parse(temp[1]), priority, onFinishedMotionHandler);\n }\n\n public CubismMotionQueueEntry? StartMotion(string group, int no, MotionPriority priority, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n if ( priority == MotionPriority.PriorityForce )\n {\n _motionManager.ReservePriority = priority;\n }\n else if ( !_motionManager.ReserveMotion(priority) )\n {\n CubismLog.Debug(\"[Live2D]can't start motion.\");\n\n return null;\n }\n\n var item = _modelSetting.FileReferences.Motions[group][no];\n\n //ex) idle_0\n var name = $\"{group}_{no}\";\n\n CubismMotion motion;\n if ( !_motions.TryGetValue(name, out var value) )\n {\n var path = item.File;\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( !File.Exists(path) )\n {\n return null;\n }\n\n motion = new CubismMotion(path, onFinishedMotionHandler);\n var fadeTime = item.FadeInTime;\n if ( fadeTime >= 0.0f )\n {\n motion.FadeInSeconds = fadeTime;\n }\n\n fadeTime = item.FadeOutTime;\n if ( fadeTime >= 0.0f )\n {\n motion.FadeOutSeconds = fadeTime;\n }\n\n motion.SetEffectIds(_eyeBlinkIds, _lipSyncIds);\n }\n else\n {\n motion = (value as CubismMotion)!;\n motion.OnFinishedMotion = onFinishedMotionHandler;\n }\n\n //voice\n var voice = item.Sound;\n if ( !string.IsNullOrWhiteSpace(voice) )\n {\n var path = voice;\n path = _modelHomeDir + path;\n _wavFileHandler.Start(path);\n }\n\n CubismLog.Debug($\"[Live2D]start motion: [{group}_{no}]\");\n\n return _motionManager.StartMotionPriority(motion, priority);\n }\n\n /// \n /// Starts playing a randomly selected motion.\n /// \n /// Motion Group Name\n /// Priority\n /// A callback function that is called when the priority motion playback ends. If NULL, it will not be called.\n /// Returns the identification number of the started motion. Used as an argument for IsFinished() to determine whether an individual motion has finished. Returns \"-1\" if the motion cannot be started.\n public CubismMotionQueueEntry? StartRandomMotion(string group, MotionPriority priority, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n if ( _modelSetting.FileReferences?.Motions?.ContainsKey(group) == true )\n {\n var no = _random.Next() % _modelSetting.FileReferences.Motions[group].Count;\n\n return StartMotion(group, no, priority, onFinishedMotionHandler);\n }\n\n return null;\n }\n \n public bool IsMotionFinished(CubismMotionQueueEntry entry)\n {\n return _motionManager.IsFinished(entry);\n }\n\n /// \n /// Sets the facial motion specified by the argument.\n /// \n /// Facial expression motion ID\n public void SetExpression(string expressionID)\n {\n var motion = _expressions[expressionID];\n CubismLog.Debug($\"[Live2D]expression: [{expressionID}]\");\n\n if ( motion != null )\n {\n _expressionManager.StartMotionPriority(motion, MotionPriority.PriorityForce);\n }\n else\n {\n CubismLog.Debug($\"[Live2D]expression[{expressionID}] is null \");\n }\n }\n\n /// \n /// Set a randomly selected facial expression motion\n /// \n public void SetRandomExpression()\n {\n if ( _expressions.Count == 0 )\n {\n return;\n }\n\n var no = _random.Next() % _expressions.Count;\n var i = 0;\n foreach ( var item in _expressions )\n {\n if ( i == no )\n {\n SetExpression(item.Key);\n\n return;\n }\n\n i++;\n }\n }\n\n /// \n /// イベントの発火を受け取る\n /// \n /// \n protected override void MotionEventFired(string eventValue)\n {\n CubismLog.Debug($\"[Live2D]{eventValue} is fired on LAppModel!!\");\n Motion?.Invoke(this, eventValue);\n }\n\n /// \n /// 当たり判定テスト。\n /// 指定IDの頂点リストから矩形を計算し、座標が矩形範囲内か判定する。\n /// \n /// 当たり判定をテストする対象のID\n /// 判定を行うX座標\n /// 判定を行うY座標\n /// \n public bool HitTest(string hitAreaName, float x, float y)\n {\n // 透明時は当たり判定なし。\n if ( Opacity < 1 )\n {\n return false;\n }\n\n if ( _modelSetting.HitAreas?.Count > 0 )\n {\n for ( var i = 0; i < _modelSetting.HitAreas?.Count; i++ )\n {\n if ( _modelSetting.HitAreas[i].Name == hitAreaName )\n {\n var id = CubismFramework.CubismIdManager.GetId(_modelSetting.HitAreas[i].Id);\n\n return IsHit(id, x, y);\n }\n }\n }\n\n return false; // 存在しない場合はfalse\n }\n\n /// \n /// モデルを描画する処理。モデルを描画する空間のView-Projection行列を渡す。\n /// \n protected void DoDraw()\n {\n if ( Model == null )\n {\n return;\n }\n\n (Renderer as CubismRenderer_OpenGLES2)?.DrawModel();\n }\n\n /// \n /// モーションデータをグループ名から一括で解放する。\n /// モーションデータの名前は内部でModelSettingから取得する。\n /// \n /// モーションデータのグループ名\n private void ReleaseMotionGroup(string group)\n {\n var list = _modelSetting.FileReferences.Motions[group];\n for ( var i = 0; i < list.Count; i++ )\n {\n var voice = list[i].Sound;\n }\n }\n\n /// \n /// OpenGLのテクスチャユニットにテクスチャをロードする\n /// \n private void SetupTextures()\n {\n if ( _modelSetting.FileReferences?.Textures?.Count > 0 )\n {\n for ( var modelTextureNumber = 0; modelTextureNumber < _modelSetting.FileReferences.Textures.Count; modelTextureNumber++ )\n {\n //OpenGLのテクスチャユニットにテクスチャをロードする\n var texturePath = _modelSetting.FileReferences.Textures[modelTextureNumber];\n if ( string.IsNullOrWhiteSpace(texturePath) )\n {\n continue;\n }\n\n texturePath = Path.GetFullPath(_modelHomeDir + texturePath);\n\n var texture = _lapp.TextureManager.CreateTextureFromPngFile(texturePath);\n var glTextueNumber = texture.ID;\n\n //OpenGL\n (Renderer as CubismRenderer_OpenGLES2)?.BindTexture(modelTextureNumber, glTextueNumber);\n }\n }\n }\n\n /// \n /// モーションデータをグループ名から一括でロードする。\n /// モーションデータの名前は内部でModelSettingから取得する。\n /// \n /// モーションデータのグループ名\n private void PreloadMotionGroup(string group)\n {\n // グループに登録されているモーション数を取得\n var list = _modelSetting.FileReferences.Motions[group];\n\n for ( var i = 0; i < list.Count; i++ )\n {\n var item = list[i];\n //ex) idle_0\n // モーションのファイル名とパスの取得\n var name = $\"{group}_{i}\";\n var path = Path.GetFullPath(_modelHomeDir + item.File);\n\n // モーションデータの読み込み\n var tmpMotion = new CubismMotion(path);\n\n // フェードインの時間を取得\n var fadeTime = item.FadeInTime;\n if ( fadeTime >= 0.0f )\n {\n tmpMotion.FadeInSeconds = fadeTime;\n }\n\n // フェードアウトの時間を取得\n fadeTime = item.FadeOutTime;\n if ( fadeTime >= 0.0f )\n {\n tmpMotion.FadeOutSeconds = fadeTime;\n }\n\n tmpMotion.SetEffectIds(_eyeBlinkIds, _lipSyncIds);\n\n if ( _motions.ContainsKey(name) )\n {\n _motions[name] = tmpMotion;\n }\n else\n {\n _motions.Add(name, tmpMotion);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/AudioEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic interface IAudioProgressEvent : IOutputEvent { }\n\npublic record AudioPlaybackEndedEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, CompletionReason FinishReason) : IOutputEvent { }\n\npublic record AudioPlaybackStartedEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent { }\n\npublic record AudioChunkPlaybackStartedEvent(\n Guid SessionId,\n Guid? TurnId,\n DateTimeOffset Timestamp,\n AudioSegment Chunk\n) : BaseOutputEvent(SessionId, TurnId, Timestamp), IAudioProgressEvent;\n\npublic record AudioChunkPlaybackEndedEvent(\n Guid SessionId,\n Guid? TurnId,\n DateTimeOffset Timestamp,\n AudioSegment Chunk\n) : BaseOutputEvent(SessionId, TurnId, Timestamp), IAudioProgressEvent;\n\npublic record AudioPlaybackProgressEvent(\n Guid SessionId,\n Guid? TurnId,\n DateTimeOffset Timestamp,\n TimeSpan CurrentPlaybackTime\n) : BaseOutputEvent(SessionId, TurnId, Timestamp), IAudioProgressEvent;"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismEyeBlink.cs", "//IDで指定された目のパラメータが、0のときに閉じるなら true 、1の時に閉じるなら false 。\n//#define CloseIfZero\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 自動まばたき機能を提供する。\n/// \npublic class CubismEyeBlink\n{\n private readonly Random _random = new();\n\n /// \n /// 操作対象のパラメータのIDのリスト\n /// \n public readonly List ParameterIds = [];\n\n /// \n /// まばたきの間隔[秒]\n /// \n private float _blinkingIntervalSeconds;\n\n /// \n /// 現在の状態\n /// \n private EyeState _blinkingState;\n\n /// \n /// まぶたを閉じている動作の所要時間[秒]\n /// \n private float _closedSeconds;\n\n /// \n /// まぶたを閉じる動作の所要時間[秒]\n /// \n private float _closingSeconds;\n\n /// \n /// 次のまばたきの時刻[秒]\n /// \n private float _nextBlinkingTime;\n\n /// \n /// まぶたを開く動作の所要時間[秒]\n /// \n private float _openingSeconds;\n\n /// \n /// 現在の状態が開始した時刻[秒]\n /// \n private float _stateStartTimeSeconds;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n private float _userTimeSeconds;\n\n /// \n /// インスタンスを作成する。\n /// \n /// モデルの設定情報\n public CubismEyeBlink(ModelSettingObj modelSetting)\n {\n _blinkingState = EyeState.First;\n _blinkingIntervalSeconds = 4.0f;\n _closingSeconds = 0.1f;\n _closedSeconds = 0.05f;\n _openingSeconds = 0.15f;\n\n foreach ( var item in modelSetting.Groups )\n {\n if ( item.Name == CubismModelSettingJson.EyeBlink )\n {\n foreach ( var item1 in item.Ids )\n {\n if ( item1 == null )\n {\n continue;\n }\n\n var item2 = CubismFramework.CubismIdManager.GetId(item1);\n ParameterIds.Add(item2);\n }\n\n break;\n }\n }\n }\n\n /// \n /// まばたきの間隔を設定する。\n /// \n /// まばたきの間隔の時間[秒]\n public void SetBlinkingInterval(float blinkingInterval) { _blinkingIntervalSeconds = blinkingInterval; }\n\n /// \n /// まばたきのモーションの詳細設定を行う。\n /// \n /// まぶたを閉じる動作の所要時間[秒]\n /// まぶたを閉じている動作の所要時間[秒]\n /// まぶたを開く動作の所要時間[秒]\n public void SetBlinkingSettings(float closing, float closed, float opening)\n {\n _closingSeconds = closing;\n _closedSeconds = closed;\n _openingSeconds = opening;\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n _userTimeSeconds += deltaTimeSeconds;\n float parameterValue;\n float t;\n switch ( _blinkingState )\n {\n case EyeState.Closing:\n t = (_userTimeSeconds - _stateStartTimeSeconds) / _closingSeconds;\n\n if ( t >= 1.0f )\n {\n t = 1.0f;\n _blinkingState = EyeState.Closed;\n _stateStartTimeSeconds = _userTimeSeconds;\n }\n\n parameterValue = 1.0f - t;\n\n break;\n case EyeState.Closed:\n t = (_userTimeSeconds - _stateStartTimeSeconds) / _closedSeconds;\n\n if ( t >= 1.0f )\n {\n _blinkingState = EyeState.Opening;\n _stateStartTimeSeconds = _userTimeSeconds;\n }\n\n parameterValue = 0.0f;\n\n break;\n case EyeState.Opening:\n t = (_userTimeSeconds - _stateStartTimeSeconds) / _openingSeconds;\n\n if ( t >= 1.0f )\n {\n t = 1.0f;\n _blinkingState = EyeState.Interval;\n _nextBlinkingTime = DetermineNextBlinkingTiming();\n }\n\n parameterValue = t;\n\n break;\n case EyeState.Interval:\n if ( _nextBlinkingTime < _userTimeSeconds )\n {\n _blinkingState = EyeState.Closing;\n _stateStartTimeSeconds = _userTimeSeconds;\n }\n\n parameterValue = 1.0f;\n\n break;\n case EyeState.First:\n default:\n _blinkingState = EyeState.Interval;\n _nextBlinkingTime = DetermineNextBlinkingTiming();\n\n parameterValue = 1.0f;\n\n break;\n }\n#if CloseIfZero\n parameterValue = -parameterValue;\n#endif\n\n foreach ( var item in ParameterIds )\n {\n model.SetParameterValue(item, parameterValue);\n }\n }\n\n /// \n /// 次のまばたきのタイミングを決定する。\n /// \n /// 次のまばたきを行う時刻[秒]\n private float DetermineNextBlinkingTiming()\n {\n float r = _random.Next() / int.MaxValue;\n\n return _userTimeSeconds + r * (2.0f * _blinkingIntervalSeconds - 1.0f);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismPose.cs", "using System.Text.Json.Nodes;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// パーツの不透明度の管理と設定を行う。\n/// \npublic class CubismPose\n{\n public const float Epsilon = 0.001f;\n\n public const float DefaultFadeInSeconds = 0.5f;\n\n // Pose.jsonのタグ\n public const string FadeIn = \"FadeInTime\";\n\n public const string Link = \"Link\";\n\n public const string Groups = \"Groups\";\n\n public const string Id = \"Id\";\n\n /// \n /// フェード時間[秒]\n /// \n private readonly float _fadeTimeSeconds = DefaultFadeInSeconds;\n\n /// \n /// それぞれのパーツグループの個数\n /// \n private readonly List _partGroupCounts = [];\n\n /// \n /// パーツグループ\n /// \n private readonly List _partGroups = [];\n\n /// \n /// 前回操作したモデル\n /// \n private CubismModel? _lastModel;\n\n /// \n /// インスタンスを作成する。\n /// \n /// pose3.jsonのデータ\n public CubismPose(string pose3json)\n {\n using var stream = File.Open(pose3json, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var json = JsonNode.Parse(stream)?.AsObject()\n ?? throw new Exception(\"Pose json is error\");\n\n // フェード時間の指定\n if ( json.ContainsKey(FadeIn) )\n {\n var item = json[FadeIn];\n _fadeTimeSeconds = item == null ? DefaultFadeInSeconds : (float)item;\n\n if ( _fadeTimeSeconds < 0.0f )\n {\n _fadeTimeSeconds = DefaultFadeInSeconds;\n }\n }\n\n // パーツグループ\n if ( json[Groups] is not JsonArray poseListInfo )\n {\n return;\n }\n\n foreach ( var item in poseListInfo )\n {\n var idCount = item!.AsArray().Count;\n var groupCount = 0;\n\n for ( var groupIndex = 0; groupIndex < idCount; ++groupIndex )\n {\n var partInfo = item[groupIndex]!;\n PartData partData = new() { PartId = CubismFramework.CubismIdManager.GetId(partInfo[Id]!.ToString()) };\n\n // リンクするパーツの設定\n if ( partInfo[Link] != null )\n {\n var linkListInfo = partInfo[Link]!;\n var linkCount = linkListInfo.AsArray().Count;\n\n for ( var linkIndex = 0; linkIndex < linkCount; ++linkIndex )\n {\n partData.Link.Add(new PartData { PartId = CubismFramework.CubismIdManager.GetId(linkListInfo[linkIndex]!.ToString()) });\n }\n }\n\n _partGroups.Add(partData);\n\n ++groupCount;\n }\n\n _partGroupCounts.Add(groupCount);\n }\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n // 前回のモデルと同じではないときは初期化が必要\n if ( model.Model != _lastModel?.Model )\n {\n // パラメータインデックスの初期化\n Reset(model);\n }\n\n _lastModel = model;\n\n // 設定から時間を変更すると、経過時間がマイナスになることがあるので、経過時間0として対応。\n if ( deltaTimeSeconds < 0.0f )\n {\n deltaTimeSeconds = 0.0f;\n }\n\n var beginIndex = 0;\n\n foreach ( var item in _partGroupCounts )\n {\n DoFade(model, deltaTimeSeconds, beginIndex, item);\n\n beginIndex += item;\n }\n\n CopyPartOpacities(model);\n }\n\n /// \n /// 表示を初期化する。\n /// 不透明度の初期値が0でないパラメータは、不透明度を1に設定する。\n /// \n /// 対象のモデル\n public void Reset(CubismModel model)\n {\n var beginIndex = 0;\n\n foreach ( var item in _partGroupCounts )\n {\n for ( var j = beginIndex; j < beginIndex + item; ++j )\n {\n _partGroups[j].Initialize(model);\n\n var partsIndex = _partGroups[j].PartIndex;\n var paramIndex = _partGroups[j].ParameterIndex;\n\n if ( partsIndex < 0 )\n {\n continue;\n }\n\n model.SetPartOpacity(partsIndex, j == beginIndex ? 1.0f : 0.0f);\n model.SetParameterValue(paramIndex, j == beginIndex ? 1.0f : 0.0f);\n\n for ( var k = 0; k < _partGroups[j].Link.Count; ++k )\n {\n _partGroups[j].Link[k].Initialize(model);\n }\n }\n\n beginIndex += item;\n }\n }\n\n /// \n /// パーツの不透明度をコピーし、リンクしているパーツへ設定する。\n /// \n /// 対象のモデル\n private void CopyPartOpacities(CubismModel model)\n {\n foreach ( var item in _partGroups )\n {\n if ( item.Link.Count == 0 )\n {\n continue; // 連動するパラメータはない\n }\n\n var partIndex = item.PartIndex;\n var opacity = model.GetPartOpacity(partIndex);\n\n foreach ( var item1 in item.Link )\n {\n var linkPartIndex = item1.PartIndex;\n\n if ( linkPartIndex < 0 )\n {\n continue;\n }\n\n model.SetPartOpacity(linkPartIndex, opacity);\n }\n }\n }\n\n /// \n /// パーツのフェード操作を行う。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// フェード操作を行うパーツグループの先頭インデックス\n /// フェード操作を行うパーツグループの個数\n private void DoFade(CubismModel model, float deltaTimeSeconds, int beginIndex, int partGroupCount)\n {\n var visiblePartIndex = -1;\n var newOpacity = 1.0f;\n\n var Phi = 0.5f;\n var BackOpacityThreshold = 0.15f;\n\n // 現在、表示状態になっているパーツを取得\n for ( var i = beginIndex; i < beginIndex + partGroupCount; ++i )\n {\n var partIndex = _partGroups[i].PartIndex;\n var paramIndex = _partGroups[i].ParameterIndex;\n\n if ( model.GetParameterValue(paramIndex) > Epsilon )\n {\n if ( visiblePartIndex >= 0 )\n {\n break;\n }\n\n visiblePartIndex = i;\n newOpacity = model.GetPartOpacity(partIndex);\n\n // 新しい不透明度を計算\n newOpacity += deltaTimeSeconds / _fadeTimeSeconds;\n\n if ( newOpacity > 1.0f )\n {\n newOpacity = 1.0f;\n }\n }\n }\n\n if ( visiblePartIndex < 0 )\n {\n visiblePartIndex = 0;\n newOpacity = 1.0f;\n }\n\n // 表示パーツ、非表示パーツの不透明度を設定する\n for ( var i = beginIndex; i < beginIndex + partGroupCount; ++i )\n {\n var partsIndex = _partGroups[i].PartIndex;\n\n // 表示パーツの設定\n if ( visiblePartIndex == i )\n {\n model.SetPartOpacity(partsIndex, newOpacity); // 先に設定\n }\n // 非表示パーツの設定\n else\n {\n var opacity = model.GetPartOpacity(partsIndex);\n float a1; // 計算によって求められる不透明度\n\n if ( newOpacity < Phi )\n {\n a1 = newOpacity * (Phi - 1) / Phi + 1.0f; // (0,1),(phi,phi)を通る直線式\n }\n else\n {\n a1 = (1 - newOpacity) * Phi / (1.0f - Phi); // (1,0),(phi,phi)を通る直線式\n }\n\n // 背景の見える割合を制限する場合\n var backOpacity = (1.0f - a1) * (1.0f - newOpacity);\n\n if ( backOpacity > BackOpacityThreshold )\n {\n a1 = 1.0f - BackOpacityThreshold / (1.0f - newOpacity);\n }\n\n if ( opacity > a1 )\n {\n opacity = a1; // 計算の不透明度よりも大きければ(濃ければ)不透明度を上げる\n }\n\n model.SetPartOpacity(partsIndex, opacity);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MicrophoneInputPortAudioSource.cs", "using System.Runtime.InteropServices;\nusing System.Text;\n\nusing Microsoft.Extensions.Logging;\n\nusing PortAudioSharp;\n\nusing Stream = PortAudioSharp.Stream;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents a source that captures audio from a microphone.\n/// \npublic sealed class MicrophoneInputPortAudioSource : AwaitableWaveFileSource, IMicrophone\n{\n private readonly int _bitsPerSample;\n\n private readonly int _channels;\n\n private readonly CancellationTokenSource _cts;\n\n private readonly int _deviceNumber;\n\n private readonly uint _framesPerBuffer;\n\n private readonly ILogger _logger;\n\n private readonly int _sampleRate;\n\n private Stream? _audioStream;\n\n private bool _isRecording;\n\n private Dictionary _metadata;\n\n public MicrophoneInputPortAudioSource(\n ILogger logger,\n int deviceNumber = -1,\n int sampleRate = 16000,\n int bitsPerSample = 16,\n int channels = 1,\n uint framesPerBuffer = 0,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : this(new Dictionary(), logger, deviceNumber, sampleRate, bitsPerSample,\n channels, framesPerBuffer, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy) { }\n\n private MicrophoneInputPortAudioSource(\n Dictionary metadata,\n ILogger logger,\n int deviceNumber = -1,\n int sampleRate = 16000,\n int bitsPerSample = 16,\n int channels = 1,\n uint framesPerBuffer = 0,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : base(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy)\n {\n PortAudio.Initialize();\n\n _logger = logger;\n _deviceNumber = deviceNumber == -1 ? PortAudio.DefaultInputDevice : deviceNumber;\n _sampleRate = sampleRate;\n _bitsPerSample = bitsPerSample;\n _channels = channels;\n _framesPerBuffer = framesPerBuffer;\n _cts = new CancellationTokenSource();\n _metadata = metadata;\n\n if ( _deviceNumber == PortAudio.NoDevice )\n {\n var sb = new StringBuilder();\n\n for ( var i = 0; i != PortAudio.DeviceCount; ++i )\n {\n var deviceInfo = PortAudio.GetDeviceInfo(i);\n\n sb.AppendLine($\"[*] Device {i}\");\n sb.AppendLine($\" Name: {deviceInfo.name}\");\n sb.AppendLine($\" Max input channels: {deviceInfo.maxInputChannels}\");\n sb.AppendLine($\" Default sample rate: {deviceInfo.defaultSampleRate}\");\n }\n\n logger.LogWarning(\"Devices available: {Devices}\", sb);\n\n throw new InvalidOperationException(\"No default input device available\");\n }\n\n Initialize(new AudioSourceHeader { BitsPerSample = (ushort)bitsPerSample, Channels = (ushort)channels, SampleRate = (uint)sampleRate });\n\n try\n {\n InitializeAudioStream();\n }\n catch\n {\n PortAudio.Terminate();\n\n throw;\n }\n }\n\n public void StartRecording()\n {\n if ( _isRecording )\n {\n return;\n }\n\n _isRecording = true;\n _audioStream?.Start();\n }\n\n public void StopRecording()\n {\n if ( !_isRecording )\n {\n return;\n }\n\n _isRecording = false;\n _audioStream?.Stop();\n Flush();\n }\n\n public IEnumerable GetAvailableDevices()\n {\n throw new NotImplementedException();\n }\n\n private void InitializeAudioStream()\n {\n var deviceInfo = PortAudio.GetDeviceInfo(_deviceNumber);\n _logger.LogInformation(\"Using input device: {DeviceName}\", deviceInfo.name);\n\n var inputParams = new StreamParameters {\n device = _deviceNumber,\n channelCount = _channels,\n sampleFormat = SampleFormat.Float32,\n suggestedLatency = deviceInfo.defaultLowInputLatency,\n hostApiSpecificStreamInfo = IntPtr.Zero\n };\n\n _audioStream = new Stream(\n inputParams,\n null,\n _sampleRate,\n _framesPerBuffer,\n StreamFlags.ClipOff,\n ProcessAudioCallback,\n IntPtr.Zero);\n }\n\n private StreamCallbackResult ProcessAudioCallback(\n IntPtr input,\n IntPtr output,\n uint frameCount,\n ref StreamCallbackTimeInfo timeInfo,\n StreamCallbackFlags statusFlags,\n IntPtr userData)\n {\n if ( _cts.Token.IsCancellationRequested )\n {\n return StreamCallbackResult.Complete;\n }\n\n try\n {\n var samples = new float[frameCount];\n Marshal.Copy(input, samples, 0, (int)frameCount);\n\n var byteArray = SampleSerializer.Serialize(samples, Header.BitsPerSample);\n\n WriteData(byteArray);\n\n return StreamCallbackResult.Continue;\n }\n catch\n {\n return StreamCallbackResult.Abort;\n }\n }\n\n protected override void Dispose(bool disposing)\n {\n if ( disposing )\n {\n _cts.Cancel();\n StopRecording();\n _audioStream?.Dispose();\n _audioStream = null;\n PortAudio.Terminate();\n }\n\n base.Dispose(disposing);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/LlmEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic record LlmStreamStartEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent { }\n\npublic record LlmChunkEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, string Chunk) : IOutputEvent { }\n\npublic record LlmStreamEndEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, CompletionReason FinishReason) : IOutputEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeEntryConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemeEntryConverter : JsonConverter\n{\n public override PhonemeEntry Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n using var doc = JsonDocument.ParseValue(ref reader);\n\n return PhonemeEntry.FromJsonElement(doc.RootElement);\n }\n\n public override void Write(Utf8JsonWriter writer, PhonemeEntry value, JsonSerializerOptions options)\n {\n switch ( value )\n {\n case SimplePhonemeEntry simple:\n writer.WriteStringValue(simple.Phoneme);\n\n break;\n case ContextualPhonemeEntry contextual:\n writer.WriteStartObject();\n foreach ( var form in contextual.Forms )\n {\n writer.WriteString(form.Key, form.Value);\n }\n\n writer.WriteEndObject();\n\n break;\n default:\n throw new JsonException($\"Unsupported PhonemeEntry type: {value.GetType()}\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismClippingManager.cs", "using System.Numerics;\n\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\nusing PersonaEngine.Lib.Live2D.Framework.Type;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic class CubismClippingManager\n{\n /// \n /// 実験時に1チャンネルの場合は1、RGBだけの場合は3、アルファも含める場合は4\n /// \n public const int ColorChannelCount = 4;\n\n /// \n /// 通常のフレームバッファ1枚あたりのマスク最大数\n /// \n public const int ClippingMaskMaxCountOnDefault = 36;\n\n /// \n /// フレームバッファが2枚以上ある場合のフレームバッファ1枚あたりのマスク最大数\n /// \n public const int ClippingMaskMaxCountOnMultiRenderTexture = 32;\n\n private readonly RenderType _renderType;\n\n protected List ChannelColors = [];\n\n /// \n /// マスクのクリアフラグの配列\n /// \n protected List ClearedMaskBufferFlags = [];\n\n /// \n /// マスク用クリッピングコンテキストのリスト\n /// \n protected List ClippingContextListForMask = [];\n\n /// \n /// オフスクリーンサーフェイスのアドレス\n /// \n protected CubismOffscreenSurface_OpenGLES2 CurrentMaskBuffer;\n\n /// \n /// マスク配置計算用の矩形\n /// \n protected RectF TmpBoundsOnModel = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrix = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrixForDraw = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrixForMask = new();\n\n public CubismClippingManager(RenderType render)\n {\n _renderType = render;\n ClippingMaskBufferSize = new Vector2(256, 256);\n\n ChannelColors.Add(new CubismTextureColor(1.0f, 0f, 0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 1.0f, 0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 0f, 1.0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 0f, 0f, 1.0f));\n }\n\n /// \n /// 描画用クリッピングコンテキストのリスト\n /// \n public List ClippingContextListForDraw { get; init; } = [];\n\n /// \n /// クリッピングマスクのバッファサイズ(初期値:256)\n /// \n public Vector2 ClippingMaskBufferSize { get; private set; }\n\n /// \n /// 生成するレンダーテクスチャの枚数\n /// \n public int RenderTextureCount { get; private set; }\n\n public void Close()\n {\n ClippingContextListForDraw.Clear();\n ClippingContextListForMask.Clear();\n ChannelColors.Clear();\n ClearedMaskBufferFlags.Clear();\n }\n\n /// \n /// マネージャの初期化処理\n /// クリッピングマスクを使う描画オブジェクトの登録を行う\n /// \n /// モデルのインスタンス\n /// バッファの生成数\n public unsafe void Initialize(CubismModel model, int maskBufferCount)\n {\n RenderTextureCount = maskBufferCount;\n\n // レンダーテクスチャのクリアフラグの設定\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n\n //クリッピングマスクを使う描画オブジェクトを全て登録する\n //クリッピングマスクは、通常数個程度に限定して使うものとする\n for ( var i = 0; i < model.GetDrawableCount(); i++ )\n {\n if ( model.GetDrawableMaskCounts()[i] <= 0 )\n {\n //クリッピングマスクが使用されていないアートメッシュ(多くの場合使用しない)\n ClippingContextListForDraw.Add(null);\n\n continue;\n }\n\n // 既にあるClipContextと同じかチェックする\n var cc = FindSameClip(model.GetDrawableMasks()[i], model.GetDrawableMaskCounts()[i]);\n if ( cc == null )\n {\n // 同一のマスクが存在していない場合は生成する\n if ( _renderType == RenderType.OpenGL )\n {\n cc = new CubismClippingContext_OpenGLES2(this, model, model.GetDrawableMasks()[i], model.GetDrawableMaskCounts()[i]);\n }\n else\n {\n throw new Exception(\"Only OpenGL\");\n }\n\n ClippingContextListForMask.Add(cc);\n }\n\n cc.AddClippedDrawable(i);\n\n ClippingContextListForDraw.Add(cc);\n }\n }\n\n /// \n /// 既にマスクを作っているかを確認。\n /// 作っているようであれば該当するクリッピングマスクのインスタンスを返す。\n /// 作っていなければNULLを返す\n /// \n /// 描画オブジェクトをマスクする描画オブジェクトのリスト\n /// 描画オブジェクトをマスクする描画オブジェクトの数\n /// 該当するクリッピングマスクが存在すればインスタンスを返し、なければNULLを返す。\n private unsafe CubismClippingContext? FindSameClip(int* drawableMasks, int drawableMaskCounts)\n {\n // 作成済みClippingContextと一致するか確認\n for ( var i = 0; i < ClippingContextListForMask.Count; i++ )\n {\n var cc = ClippingContextListForMask[i];\n var count = cc.ClippingIdCount;\n if ( count != drawableMaskCounts )\n {\n continue; //個数が違う場合は別物\n }\n\n var samecount = 0;\n\n // 同じIDを持つか確認。配列の数が同じなので、一致した個数が同じなら同じ物を持つとする。\n for ( var j = 0; j < count; j++ )\n {\n var clipId = cc.ClippingIdList[j];\n for ( var k = 0; k < count; k++ )\n {\n if ( drawableMasks[k] == clipId )\n {\n samecount++;\n\n break;\n }\n }\n }\n\n if ( samecount == count )\n {\n return cc;\n }\n }\n\n return null; //見つからなかった\n }\n\n /// \n /// 高精細マスク処理用の行列を計算する\n /// \n /// モデルのインスタンス\n /// 処理が右手系であるか\n public void SetupMatrixForHighPrecision(CubismModel model, bool isRightHanded)\n {\n // 全てのクリッピングを用意する\n // 同じクリップ(複数の場合はまとめて1つのクリップ)を使う場合は1度だけ設定する\n var usingClipCount = 0;\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // 1つのクリッピングマスクに関して\n var cc = ClippingContextListForMask[clipIndex];\n\n // このクリップを利用する描画オブジェクト群全体を囲む矩形を計算\n CalcClippedDrawTotalBounds(model, cc);\n\n if ( cc.IsUsing )\n {\n usingClipCount++; //使用中としてカウント\n }\n }\n\n if ( usingClipCount <= 0 )\n {\n return;\n }\n\n // マスク行列作成処理\n SetupLayoutBounds(0);\n\n // サイズがレンダーテクスチャの枚数と合わない場合は合わせる\n if ( ClearedMaskBufferFlags.Count != RenderTextureCount )\n {\n ClearedMaskBufferFlags.Clear();\n\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n }\n else\n {\n // マスクのクリアフラグを毎フレーム開始時に初期化\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags[i] = false;\n }\n }\n\n // 実際にマスクを生成する\n // 全てのマスクをどの様にレイアウトして描くかを決定し、ClipContext , ClippedDrawContext に記憶する\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // --- 実際に1つのマスクを描く ---\n var clipContext = ClippingContextListForMask[clipIndex];\n var allClippedDrawRect = clipContext.AllClippedDrawRect; //このマスクを使う、全ての描画オブジェクトの論理座標上の囲み矩形\n var layoutBoundsOnTex01 = clipContext.LayoutBounds; //この中にマスクを収める\n var MARGIN = 0.05f;\n float scaleX;\n float scaleY;\n var ppu = model.GetPixelsPerUnit();\n var maskPixelWidth = clipContext.Manager.ClippingMaskBufferSize.X;\n var maskPixelHeight = clipContext.Manager.ClippingMaskBufferSize.Y;\n var physicalMaskWidth = layoutBoundsOnTex01.Width * maskPixelWidth;\n var physicalMaskHeight = layoutBoundsOnTex01.Height * maskPixelHeight;\n\n TmpBoundsOnModel.SetRect(allClippedDrawRect);\n if ( TmpBoundsOnModel.Width * ppu > physicalMaskWidth )\n {\n TmpBoundsOnModel.Expand(allClippedDrawRect.Width * MARGIN, 0.0f);\n scaleX = layoutBoundsOnTex01.Width / TmpBoundsOnModel.Width;\n }\n else\n {\n scaleX = ppu / physicalMaskWidth;\n }\n\n if ( TmpBoundsOnModel.Height * ppu > physicalMaskHeight )\n {\n TmpBoundsOnModel.Expand(0.0f, allClippedDrawRect.Height * MARGIN);\n scaleY = layoutBoundsOnTex01.Height / TmpBoundsOnModel.Height;\n }\n else\n {\n scaleY = ppu / physicalMaskHeight;\n }\n\n // マスク生成時に使う行列を求める\n CreateMatrixForMask(isRightHanded, layoutBoundsOnTex01, scaleX, scaleY);\n\n clipContext.MatrixForMask.SetMatrix(TmpMatrixForMask.Tr);\n clipContext.MatrixForDraw.SetMatrix(TmpMatrixForDraw.Tr);\n }\n }\n\n /// \n /// マスク作成・描画用の行列を作成する。\n /// \n /// 座標を右手系として扱うかを指定\n /// マスクを収める領域\n /// 描画オブジェクトの伸縮率\n /// 描画オブジェクトの伸縮率\n protected void CreateMatrixForMask(bool isRightHanded, RectF layoutBoundsOnTex01, float scaleX, float scaleY)\n {\n TmpMatrix.LoadIdentity();\n {\n // Layout0..1 を -1..1に変換\n TmpMatrix.TranslateRelative(-1.0f, -1.0f);\n TmpMatrix.ScaleRelative(2.0f, 2.0f);\n }\n\n {\n // view to Layout0..1\n TmpMatrix.TranslateRelative(layoutBoundsOnTex01.X, layoutBoundsOnTex01.Y); //new = [translate]\n TmpMatrix.ScaleRelative(scaleX, scaleY); //new = [translate][scale]\n TmpMatrix.TranslateRelative(-TmpBoundsOnModel.X, -TmpBoundsOnModel.Y); //new = [translate][scale][translate]\n }\n\n // tmpMatrixForMask が計算結果\n TmpMatrixForMask.SetMatrix(TmpMatrix.Tr);\n\n TmpMatrix.LoadIdentity();\n {\n TmpMatrix.TranslateRelative(layoutBoundsOnTex01.X, layoutBoundsOnTex01.Y * (isRightHanded ? -1.0f : 1.0f)); //new = [translate]\n TmpMatrix.ScaleRelative(scaleX, scaleY * (isRightHanded ? -1.0f : 1.0f)); //new = [translate][scale]\n TmpMatrix.TranslateRelative(-TmpBoundsOnModel.X, -TmpBoundsOnModel.Y); //new = [translate][scale][translate]\n }\n\n TmpMatrixForDraw.SetMatrix(TmpMatrix.Tr);\n }\n\n /// \n /// クリッピングコンテキストを配置するレイアウト。\n /// ひとつのレンダーテクスチャを極力いっぱいに使ってマスクをレイアウトする。\n /// マスクグループの数が4以下ならRGBA各チャンネルに1つずつマスクを配置し、5以上6以下ならRGBAを2,2,1,1と配置する。\n /// \n /// 配置するクリッピングコンテキストの数\n protected void SetupLayoutBounds(int usingClipCount)\n {\n var useClippingMaskMaxCount = RenderTextureCount <= 1\n ? ClippingMaskMaxCountOnDefault\n : ClippingMaskMaxCountOnMultiRenderTexture * RenderTextureCount;\n\n if ( usingClipCount <= 0 || usingClipCount > useClippingMaskMaxCount )\n {\n if ( usingClipCount > useClippingMaskMaxCount )\n {\n // マスクの制限数の警告を出す\n var count = usingClipCount - useClippingMaskMaxCount;\n CubismLog.Error(\"not supported mask count : %d\\n[Details] render texture count: %d\\n, mask count : %d\"\n , count, RenderTextureCount, usingClipCount);\n }\n\n // この場合は一つのマスクターゲットを毎回クリアして使用する\n for ( var index = 0; index < ClippingContextListForMask.Count; index++ )\n {\n var cc = ClippingContextListForMask[index];\n cc.LayoutChannelIndex = 0; // どうせ毎回消すので固定で良い\n cc.LayoutBounds.X = 0.0f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 1.0f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = 0;\n }\n\n return;\n }\n\n // レンダーテクスチャが1枚なら9分割する(最大36枚)\n var layoutCountMaxValue = RenderTextureCount <= 1 ? 9 : 8;\n\n // ひとつのRenderTextureを極力いっぱいに使ってマスクをレイアウトする\n // マスクグループの数が4以下ならRGBA各チャンネルに1つずつマスクを配置し、5以上6以下ならRGBAを2,2,1,1と配置する\n var countPerSheetDiv = (usingClipCount + RenderTextureCount - 1) / RenderTextureCount; // レンダーテクスチャ1枚あたり何枚割り当てるか(切り上げ)\n var reduceLayoutTextureCount = usingClipCount % RenderTextureCount; // レイアウトの数を1枚減らすレンダーテクスチャの数(この数だけのレンダーテクスチャが対象)\n\n // RGBAを順番に使っていく\n var divCount = countPerSheetDiv / ColorChannelCount; //1チャンネルに配置する基本のマスク個数\n var modCount = countPerSheetDiv % ColorChannelCount; //余り、この番号のチャンネルまでに1つずつ配分する\n\n // RGBAそれぞれのチャンネルを用意していく(0:R , 1:G , 2:B, 3:A, )\n var curClipIndex = 0; //順番に設定していく\n\n for ( var renderTextureIndex = 0; renderTextureIndex < RenderTextureCount; renderTextureIndex++ )\n {\n for ( var channelIndex = 0; channelIndex < ColorChannelCount; channelIndex++ )\n {\n // このチャンネルにレイアウトする数\n // NOTE: レイアウト数 = 1チャンネルに配置する基本のマスク + 余りのマスクを置くチャンネルなら1つ追加\n var layoutCount = divCount + (channelIndex < modCount ? 1 : 0);\n\n // レイアウトの数を1枚減らす場合にそれを行うチャンネルを決定\n // divが0の時は正常なインデックスの範囲内になるように調整\n var checkChannelIndex = modCount + (divCount < 1 ? -1 : 0);\n\n // 今回が対象のチャンネルかつ、レイアウトの数を1枚減らすレンダーテクスチャが存在する場合\n if ( channelIndex == checkChannelIndex && reduceLayoutTextureCount > 0 )\n {\n // 現在のレンダーテクスチャが、対象のレンダーテクスチャであればレイアウトの数を1枚減らす\n layoutCount -= !(renderTextureIndex < reduceLayoutTextureCount) ? 1 : 0;\n }\n\n // 分割方法を決定する\n if ( layoutCount == 0 )\n {\n // 何もしない\n }\n else if ( layoutCount == 1 )\n {\n //全てをそのまま使う\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n cc.LayoutBounds.X = 0.0f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 1.0f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = renderTextureIndex;\n }\n else if ( layoutCount == 2 )\n {\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 2;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos * 0.5f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 0.5f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = renderTextureIndex;\n //UVを2つに分解して使う\n }\n }\n else if ( layoutCount <= 4 )\n {\n //4分割して使う\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 2;\n var ypos = i / 2;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos * 0.5f;\n cc.LayoutBounds.Y = ypos * 0.5f;\n cc.LayoutBounds.Width = 0.5f;\n cc.LayoutBounds.Height = 0.5f;\n cc.BufferIndex = renderTextureIndex;\n }\n }\n else if ( layoutCount <= layoutCountMaxValue )\n {\n //9分割して使う\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 3;\n var ypos = i / 3;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos / 3.0f;\n cc.LayoutBounds.Y = ypos / 3.0f;\n cc.LayoutBounds.Width = 1.0f / 3.0f;\n cc.LayoutBounds.Height = 1.0f / 3.0f;\n cc.BufferIndex = renderTextureIndex;\n }\n }\n // マスクの制限枚数を超えた場合の処理\n else\n {\n var count = usingClipCount - useClippingMaskMaxCount;\n\n // 開発モードの場合は停止させる\n throw new Exception($\"not supported mask count : {count}\\n[Details] render texture count: {RenderTextureCount}\\n, mask count : {usingClipCount}\");\n }\n }\n }\n }\n\n /// \n /// マスクされる描画オブジェクト群全体を囲む矩形(モデル座標系)を計算する\n /// \n /// モデルのインスタンス\n /// クリッピングマスクのコンテキスト\n protected unsafe void CalcClippedDrawTotalBounds(CubismModel model, CubismClippingContext clippingContext)\n {\n // 被クリッピングマスク(マスクされる描画オブジェクト)の全体の矩形\n float clippedDrawTotalMinX = float.MaxValue,\n clippedDrawTotalMinY = float.MaxValue;\n\n float clippedDrawTotalMaxX = float.MinValue,\n clippedDrawTotalMaxY = float.MinValue;\n\n // このマスクが実際に必要か判定する\n // このクリッピングを利用する「描画オブジェクト」がひとつでも使用可能であればマスクを生成する必要がある\n\n var clippedDrawCount = clippingContext.ClippedDrawableIndexList.Count;\n for ( var clippedDrawableIndex = 0; clippedDrawableIndex < clippedDrawCount; clippedDrawableIndex++ )\n {\n // マスクを使用する描画オブジェクトの描画される矩形を求める\n var drawableIndex = clippingContext.ClippedDrawableIndexList[clippedDrawableIndex];\n\n var drawableVertexCount = model.GetDrawableVertexCount(drawableIndex);\n var drawableVertexes = model.GetDrawableVertices(drawableIndex);\n\n float minX = float.MaxValue,\n minY = float.MaxValue;\n\n float maxX = float.MinValue,\n maxY = float.MinValue;\n\n var loop = drawableVertexCount * CubismFramework.VertexStep;\n for ( var pi = CubismFramework.VertexOffset; pi < loop; pi += CubismFramework.VertexStep )\n {\n var x = drawableVertexes[pi];\n var y = drawableVertexes[pi + 1];\n if ( x < minX )\n {\n minX = x;\n }\n\n if ( x > maxX )\n {\n maxX = x;\n }\n\n if ( y < minY )\n {\n minY = y;\n }\n\n if ( y > maxY )\n {\n maxY = y;\n }\n }\n\n //\n if ( minX == float.MaxValue )\n {\n continue; //有効な点がひとつも取れなかったのでスキップする\n }\n\n // 全体の矩形に反映\n if ( minX < clippedDrawTotalMinX )\n {\n clippedDrawTotalMinX = minX;\n }\n\n if ( minY < clippedDrawTotalMinY )\n {\n clippedDrawTotalMinY = minY;\n }\n\n if ( maxX > clippedDrawTotalMaxX )\n {\n clippedDrawTotalMaxX = maxX;\n }\n\n if ( maxY > clippedDrawTotalMaxY )\n {\n clippedDrawTotalMaxY = maxY;\n }\n }\n\n if ( clippedDrawTotalMinX == float.MaxValue )\n {\n clippingContext.AllClippedDrawRect.X = 0.0f;\n clippingContext.AllClippedDrawRect.Y = 0.0f;\n clippingContext.AllClippedDrawRect.Width = 0.0f;\n clippingContext.AllClippedDrawRect.Height = 0.0f;\n clippingContext.IsUsing = false;\n }\n else\n {\n clippingContext.IsUsing = true;\n var w = clippedDrawTotalMaxX - clippedDrawTotalMinX;\n var h = clippedDrawTotalMaxY - clippedDrawTotalMinY;\n clippingContext.AllClippedDrawRect.X = clippedDrawTotalMinX;\n clippingContext.AllClippedDrawRect.Y = clippedDrawTotalMinY;\n clippingContext.AllClippedDrawRect.Width = w;\n clippingContext.AllClippedDrawRect.Height = h;\n }\n }\n\n /// \n /// カラーチャンネル(RGBA)のフラグを取得する\n /// \n /// カラーチャンネル(RGBA)の番号(0:R , 1:G , 2:B, 3:A)\n /// \n public CubismTextureColor GetChannelFlagAsColor(int channelNo) { return ChannelColors[channelNo]; }\n\n /// \n /// クリッピングマスクバッファのサイズを設定する\n /// \n /// クリッピングマスクバッファのサイズ\n /// クリッピングマスクバッファのサイズ\n public void SetClippingMaskBufferSize(float width, float height) { ClippingMaskBufferSize = new Vector2(width, height); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModel.cs", "using System.Numerics;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\npublic class CubismModel : IDisposable\n{\n /// \n /// 存在していないパラメータIDのリスト\n /// \n private readonly Dictionary _notExistParameterId = [];\n\n /// \n /// 存在していないパラメータの値のリスト\n /// \n private readonly Dictionary _notExistParameterValues = [];\n\n /// \n /// 存在していないパーツIDのリスト\n /// \n private readonly Dictionary _notExistPartId = [];\n\n /// \n /// 存在していないパーツの不透明度のリスト\n /// \n private readonly Dictionary _notExistPartOpacities = [];\n\n /// \n /// パラメータの最大値のリスト\n /// \n private readonly unsafe float* _parameterMaximumValues;\n\n /// \n /// パラメータの最小値のリスト\n /// \n private readonly unsafe float* _parameterMinimumValues;\n\n /// \n /// パラメータの値のリスト\n /// \n private readonly unsafe float* _parameterValues;\n\n /// \n /// Partの子DrawableIndexの配列\n /// \n private readonly List[] _partChildDrawables;\n\n /// \n /// パーツの不透明度のリスト\n /// \n private readonly unsafe float* _partOpacities;\n\n /// \n /// 保存されたパラメータ\n /// \n private readonly List _savedParameters = [];\n\n /// \n /// カリング設定の配列\n /// \n private readonly List _userCullings = [];\n\n /// \n /// Drawable スクリーン色の配列\n /// \n private readonly List _userMultiplyColors = [];\n\n /// \n /// Part スクリーン色の配列\n /// \n private readonly List _userPartMultiplyColors = [];\n\n /// \n /// Part 乗算色の配列\n /// \n private readonly List _userPartScreenColors = [];\n\n /// \n /// Drawable 乗算色の配列\n /// \n private readonly List _userScreenColors = [];\n\n public readonly List DrawableIds = [];\n\n public readonly List ParameterIds = [];\n\n public readonly List PartIds = [];\n\n /// \n /// モデルのカリング設定をすべて上書きするか?\n /// \n private bool _isOverwrittenCullings;\n\n /// \n /// 乗算色を全て上書きするか?\n /// \n private bool _isOverwrittenModelMultiplyColors;\n\n /// \n /// スクリーン色を全て上書きするか?\n /// \n private bool _isOverwrittenModelScreenColors;\n\n /// \n /// モデルの不透明度\n /// \n private float _modelOpacity;\n\n public unsafe CubismModel(IntPtr model)\n {\n Model = model;\n _modelOpacity = 1.0f;\n\n _parameterValues = CubismCore.GetParameterValues(Model);\n _partOpacities = CubismCore.GetPartOpacities(Model);\n _parameterMaximumValues = CubismCore.GetParameterMaximumValues(Model);\n _parameterMinimumValues = CubismCore.GetParameterMinimumValues(Model);\n\n {\n var parameterIds = CubismCore.GetParameterIds(Model);\n var parameterCount = CubismCore.GetParameterCount(Model);\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n var str = new string(parameterIds[i]);\n ParameterIds.Add(CubismFramework.CubismIdManager.GetId(str));\n }\n }\n\n var partCount = CubismCore.GetPartCount(Model);\n var partIds = CubismCore.GetPartIds(Model);\n\n _partChildDrawables = new List[partCount];\n for ( var i = 0; i < partCount; ++i )\n {\n var str = new string(partIds[i]);\n PartIds.Add(CubismFramework.CubismIdManager.GetId(str));\n _partChildDrawables[i] = [];\n }\n\n var drawableIds = CubismCore.GetDrawableIds(Model);\n var drawableCount = CubismCore.GetDrawableCount(Model);\n\n // カリング設定\n var userCulling = new DrawableCullingData { IsOverwritten = false, IsCulling = false };\n\n // 乗算色\n var multiplyColor = new CubismTextureColor();\n\n // スクリーン色\n var screenColor = new CubismTextureColor(0, 0, 0, 1.0f);\n\n // Parts\n for ( var i = 0; i < partCount; ++i )\n {\n _userPartMultiplyColors.Add(new PartColorData {\n IsOverwritten = false, Color = multiplyColor // 乗算色\n });\n\n _userPartScreenColors.Add(new PartColorData {\n IsOverwritten = false, Color = screenColor // スクリーン色\n });\n }\n\n // Drawables\n for ( var i = 0; i < drawableCount; ++i )\n {\n var str = new string(drawableIds[i]);\n DrawableIds.Add(CubismFramework.CubismIdManager.GetId(str));\n _userMultiplyColors.Add(new DrawableColorData {\n IsOverwritten = false, Color = multiplyColor // 乗算色\n });\n\n _userScreenColors.Add(new DrawableColorData {\n IsOverwritten = false, Color = screenColor // スクリーン色\n });\n\n _userCullings.Add(userCulling);\n\n var parentIndex = CubismCore.GetDrawableParentPartIndices(Model)[i];\n if ( parentIndex >= 0 )\n {\n _partChildDrawables[parentIndex].Add(i);\n }\n }\n }\n\n /// \n /// モデル\n /// \n public IntPtr Model { get; }\n\n public void Dispose()\n {\n CubismFramework.DeallocateAligned(Model);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// partのOverwriteColor Set関数\n /// \n public void SetPartColor(int partIndex, float r, float g, float b, float a,\n List partColors, List drawableColors)\n {\n partColors[partIndex].Color.R = r;\n partColors[partIndex].Color.G = g;\n partColors[partIndex].Color.B = b;\n partColors[partIndex].Color.A = a;\n\n if ( partColors[partIndex].IsOverwritten )\n {\n for ( var i = 0; i < _partChildDrawables[partIndex].Count; i++ )\n {\n var drawableIndex = _partChildDrawables[partIndex][i];\n drawableColors[drawableIndex].Color.R = r;\n drawableColors[drawableIndex].Color.G = g;\n drawableColors[drawableIndex].Color.B = b;\n drawableColors[drawableIndex].Color.A = a;\n }\n }\n }\n\n /// \n /// partのOverwriteFlag Set関数\n /// \n public void SetOverwriteColorForPartColors(int partIndex, bool value,\n List partColors, List drawableColors)\n {\n partColors[partIndex].IsOverwritten = value;\n\n for ( var i = 0; i < _partChildDrawables[partIndex].Count; i++ )\n {\n var drawableIndex = _partChildDrawables[partIndex][i];\n drawableColors[drawableIndex].IsOverwritten = value;\n if ( value )\n {\n drawableColors[drawableIndex].Color.R = partColors[partIndex].Color.R;\n drawableColors[drawableIndex].Color.G = partColors[partIndex].Color.G;\n drawableColors[drawableIndex].Color.B = partColors[partIndex].Color.B;\n drawableColors[drawableIndex].Color.A = partColors[partIndex].Color.A;\n }\n }\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n public void Update()\n {\n // Update model.\n CubismCore.UpdateModel(Model);\n // Reset dynamic drawable flags.\n CubismCore.ResetDrawableDynamicFlags(Model);\n }\n\n /// \n /// Pixel単位でキャンバスの幅の取得\n /// \n /// キャンバスの幅(pixel)\n public float GetCanvasWidthPixel()\n {\n if ( Model == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out _);\n\n return tmpSizeInPixels.X;\n }\n\n /// \n /// Pixel単位でキャンバスの高さの取得\n /// \n /// キャンバスの高さ(pixel)\n public float GetCanvasHeightPixel()\n {\n if ( new IntPtr(Model) == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out _);\n\n return tmpSizeInPixels.Y;\n }\n\n /// \n /// PixelsPerUnitを取得する。\n /// \n /// PixelsPerUnit\n public float GetPixelsPerUnit()\n {\n if ( new IntPtr(Model) == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out _, out _, out var tmpPixelsPerUnit);\n\n return tmpPixelsPerUnit;\n }\n\n /// \n /// Unit単位でキャンバスの幅の取得\n /// \n /// キャンバスの幅(Unit)\n public float GetCanvasWidth()\n {\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out var tmpPixelsPerUnit);\n\n return tmpSizeInPixels.X / tmpPixelsPerUnit;\n }\n\n /// \n /// Unit単位でキャンバスの高さの取得\n /// \n /// キャンバスの高さ(Unit)\n public float GetCanvasHeight()\n {\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out var tmpPixelsPerUnit);\n\n return tmpSizeInPixels.Y / tmpPixelsPerUnit;\n }\n\n /// \n /// パーツのインデックスを取得する。\n /// \n /// パーツのID\n /// パーツのインデックス\n public int GetPartIndex(string partId)\n {\n var partIndex = PartIds.IndexOf(partId);\n if ( partIndex != -1 )\n {\n return partIndex;\n }\n\n var partCount = CubismCore.GetPartCount(Model);\n\n // モデルに存在していない場合、非存在パーツIDリスト内にあるかを検索し、そのインデックスを返す\n if ( _notExistPartId.TryGetValue(partId, out var item) )\n {\n return item;\n }\n\n // 非存在パーツIDリストにない場合、新しく要素を追加する\n partIndex = partCount + _notExistPartId.Count;\n\n _notExistPartId.TryAdd(partId, partIndex);\n _notExistPartOpacities.Add(partIndex, 0);\n\n return partIndex;\n }\n\n /// \n /// パーツのIDを取得する。\n /// \n /// パーツのIndex\n /// パーツのID\n public string GetPartId(int partIndex)\n {\n if ( 0 <= partIndex && partIndex < PartIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of PartIds size\");\n }\n\n return PartIds[partIndex];\n }\n\n /// \n /// パーツの個数を取得する。\n /// \n /// パーツの個数\n public int GetPartCount() { return CubismCore.GetPartCount(Model); }\n\n /// \n /// パーツの不透明度を設定する。\n /// \n /// パーツのID\n /// 不透明度\n public void SetPartOpacity(string partId, float opacity)\n {\n // 高速化のためにPartIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var index = GetPartIndex(partId);\n\n if ( index < 0 )\n {\n return; // パーツが無いのでスキップ\n }\n\n SetPartOpacity(index, opacity);\n }\n\n /// \n /// パーツの不透明度を設定する。\n /// \n /// パーツのインデックス\n /// パーツの不透明度\n public unsafe void SetPartOpacity(int partIndex, float opacity)\n {\n if ( _notExistPartOpacities.ContainsKey(partIndex) )\n {\n _notExistPartOpacities[partIndex] = opacity;\n\n return;\n }\n\n //インデックスの範囲内検知\n if ( 0 > partIndex || partIndex >= GetPartCount() )\n {\n throw new ArgumentException(\"partIndex out of range\");\n }\n\n _partOpacities[partIndex] = opacity;\n }\n\n /// \n /// パーツの不透明度を取得する。\n /// \n /// パーツのID\n /// パーツの不透明度\n public float GetPartOpacity(string partId)\n {\n // 高速化のためにPartIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var index = GetPartIndex(partId);\n\n if ( index < 0 )\n {\n return 0; //パーツが無いのでスキップ\n }\n\n return GetPartOpacity(index);\n }\n\n /// \n /// パーツの不透明度を取得する。\n /// \n /// パーツのインデックス\n /// パーツの不透明度\n public unsafe float GetPartOpacity(int partIndex)\n {\n if ( _notExistPartOpacities.TryGetValue(partIndex, out var value) )\n {\n // モデルに存在しないパーツIDの場合、非存在パーツリストから不透明度を返す\n return value;\n }\n\n //インデックスの範囲内検知\n if ( 0 > partIndex || partIndex >= GetPartCount() )\n {\n throw new ArgumentException(\"partIndex out of range\");\n }\n\n return _partOpacities[partIndex];\n }\n\n /// \n /// パラメータのインデックスを取得する。\n /// \n /// パラメータID\n /// パラメータのインデックス\n public int GetParameterIndex(string parameterId)\n {\n var parameterIndex = ParameterIds.IndexOf(parameterId);\n if ( parameterIndex != -1 )\n {\n return parameterIndex;\n }\n\n // モデルに存在していない場合、非存在パラメータIDリスト内を検索し、そのインデックスを返す\n if ( _notExistParameterId.TryGetValue(parameterId, out var data) )\n {\n return data;\n }\n\n // 非存在パラメータIDリストにない場合、新しく要素を追加する\n parameterIndex = CubismCore.GetParameterCount(Model) + _notExistParameterId.Count;\n\n _notExistParameterId.TryAdd(parameterId, parameterIndex);\n _notExistParameterValues.Add(parameterIndex, 0);\n\n return parameterIndex;\n }\n\n /// \n /// パラメータの個数を取得する。\n /// \n /// パラメータの個数\n public int GetParameterCount() { return CubismCore.GetParameterCount(Model); }\n\n /// \n /// パラメータの種類を取得する。\n /// \n /// パラメータのインデックス\n /// \n /// csmParameterType_Normal -> 通常のパラメータ\n /// csmParameterType_BlendShape -> ブレンドシェイプパラメータ\n /// \n public unsafe int GetParameterType(int parameterIndex) { return CubismCore.GetParameterTypes(Model)[parameterIndex]; }\n\n /// \n /// パラメータの最大値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの最大値\n public unsafe float GetParameterMaximumValue(int parameterIndex) { return CubismCore.GetParameterMaximumValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータの最小値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの最小値\n public unsafe float GetParameterMinimumValue(int parameterIndex) { return CubismCore.GetParameterMinimumValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータのデフォルト値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータのデフォルト値\n public unsafe float GetParameterDefaultValue(int parameterIndex) { return CubismCore.GetParameterDefaultValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータの値を取得する。\n /// \n /// パラメータID\n /// パラメータの値\n public float GetParameterValue(string parameterId)\n {\n // 高速化のためにParameterIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var parameterIndex = GetParameterIndex(parameterId);\n\n return GetParameterValue(parameterIndex);\n }\n\n /// \n /// パラメータの値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの値\n public unsafe float GetParameterValue(int parameterIndex)\n {\n if ( _notExistParameterValues.TryGetValue(parameterIndex, out var item) )\n {\n return item;\n }\n\n //インデックスの範囲内検知\n if ( 0 > parameterIndex || parameterIndex >= GetParameterCount() )\n {\n throw new ArgumentException(\"parameterIndex out of range\");\n }\n\n return _parameterValues[parameterIndex];\n }\n\n /// \n /// パラメータの値を設定する。\n /// \n /// パラメータID\n /// パラメータの値\n /// 重み\n public void SetParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n SetParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を設定する。\n /// \n /// パラメータのインデックス\n /// パラメータの値\n /// 重み\n public unsafe void SetParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( _notExistParameterValues.TryGetValue(parameterIndex, out var value1) )\n {\n _notExistParameterValues[parameterIndex] = weight == 1\n ? value\n : value1 * (1 - weight) + value * weight;\n\n return;\n }\n\n //インデックスの範囲内検知\n if ( 0 > parameterIndex || parameterIndex >= GetParameterCount() )\n {\n throw new ArgumentException(\"parameterIndex out of range\");\n }\n\n if ( CubismCore.GetParameterMaximumValues(Model)[parameterIndex] < value )\n {\n value = CubismCore.GetParameterMaximumValues(Model)[parameterIndex];\n }\n\n if ( CubismCore.GetParameterMinimumValues(Model)[parameterIndex] > value )\n {\n value = CubismCore.GetParameterMinimumValues(Model)[parameterIndex];\n }\n\n _parameterValues[parameterIndex] = weight == 1\n ? value\n : _parameterValues[parameterIndex] = _parameterValues[parameterIndex] * (1 - weight) + value * weight;\n }\n\n /// \n /// パラメータの値を加算する。\n /// \n /// パラメータID\n /// 加算する値\n /// 重み\n public void AddParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n AddParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を加算する。\n /// \n /// パラメータのインデックス\n /// 加算する値\n /// 重み\n public void AddParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( parameterIndex == -1 )\n {\n return;\n }\n\n SetParameterValue(parameterIndex, GetParameterValue(parameterIndex) + value * weight);\n }\n\n /// \n /// パラメータの値を乗算する。\n /// \n /// パラメータID\n /// 乗算する値\n /// 重み\n public void MultiplyParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n MultiplyParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を乗算する。\n /// \n /// パラメータのインデックス\n /// 乗算する値\n /// 重み\n public void MultiplyParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( parameterIndex == -1 )\n {\n return;\n }\n\n SetParameterValue(parameterIndex, GetParameterValue(parameterIndex) * (1.0f + (value - 1.0f) * weight));\n }\n\n /// \n /// Drawableのインデックスを取得する。\n /// \n /// DrawableのID\n /// Drawableのインデックス\n public int GetDrawableIndex(string drawableId) { return DrawableIds.IndexOf(drawableId); }\n\n /// \n /// Drawableの個数を取得する。\n /// \n /// Drawableの個数\n public int GetDrawableCount() { return CubismCore.GetDrawableCount(Model); }\n\n /// \n /// DrawableのIDを取得する。\n /// \n /// Drawableのインデックス\n /// DrawableのID\n public string GetDrawableId(int drawableIndex)\n {\n if ( 0 <= drawableIndex && drawableIndex < DrawableIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of DrawableIds size\");\n }\n\n return DrawableIds[drawableIndex];\n }\n\n /// \n /// Drawableの描画順リストを取得する。\n /// \n /// Drawableの描画順リスト\n public unsafe int* GetDrawableRenderOrders() { return CubismCore.GetDrawableRenderOrders(Model); }\n\n /// \n /// Drawableのテクスチャインデックスリストの取得\n /// 関数名が誤っていたため、代替となる getDrawableTextureIndex を追加し、この関数は非推奨となりました。\n /// \n /// Drawableのインデックス\n /// Drawableのテクスチャインデックスリスト\n public int GetDrawableTextureIndices(int drawableIndex) { return GetDrawableTextureIndex(drawableIndex); }\n\n /// \n /// Drawableのテクスチャインデックスを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのテクスチャインデックス\n public unsafe int GetDrawableTextureIndex(int drawableIndex)\n {\n var textureIndices = CubismCore.GetDrawableTextureIndices(Model);\n\n return textureIndices[drawableIndex];\n }\n\n /// \n /// Drawableの頂点インデックスの個数を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点インデックスの個数\n public unsafe int GetDrawableVertexIndexCount(int drawableIndex) { return CubismCore.GetDrawableIndexCounts(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点の個数を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点の個数\n public unsafe int GetDrawableVertexCount(int drawableIndex) { return CubismCore.GetDrawableVertexCounts(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点リストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点リスト\n public unsafe float* GetDrawableVertices(int drawableIndex) { return (float*)GetDrawableVertexPositions(drawableIndex); }\n\n /// \n /// Drawableの頂点インデックスリストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点インデックスリスト\n public unsafe ushort* GetDrawableVertexIndices(int drawableIndex) { return CubismCore.GetDrawableIndices(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点リストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点リスト\n public unsafe Vector2* GetDrawableVertexPositions(int drawableIndex) { return CubismCore.GetDrawableVertexPositions(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点のUVリストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点のUVリスト\n public unsafe Vector2* GetDrawableVertexUvs(int drawableIndex) { return CubismCore.GetDrawableVertexUvs(Model)[drawableIndex]; }\n\n /// \n /// Drawableの不透明度を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの不透明度\n public unsafe float GetDrawableOpacity(int drawableIndex) { return CubismCore.GetDrawableOpacities(Model)[drawableIndex]; }\n\n /// \n /// Drawableの乗算色を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの乗算色\n public unsafe Vector4 GetDrawableMultiplyColor(int drawableIndex) { return CubismCore.GetDrawableMultiplyColors(Model)[drawableIndex]; }\n\n /// \n /// Drawableのスクリーン色を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのスクリーン色\n public unsafe Vector4 GetDrawableScreenColor(int drawableIndex) { return CubismCore.GetDrawableScreenColors(Model)[drawableIndex]; }\n\n /// \n /// Drawableの親パーツのインデックスを取得する。\n /// \n /// Drawableのインデックス\n /// drawableの親パーツのインデックス\n public unsafe int GetDrawableParentPartIndex(int drawableIndex) { return CubismCore.GetDrawableParentPartIndices(Model)[drawableIndex]; }\n\n /// \n /// Drawableのブレンドモードを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのブレンドモード\n public unsafe CubismBlendMode GetDrawableBlendMode(int drawableIndex)\n {\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model)[drawableIndex];\n\n return IsBitSet(constantFlags, CsmEnum.CsmBlendAdditive)\n ? CubismBlendMode.Additive\n : IsBitSet(constantFlags, CsmEnum.CsmBlendMultiplicative)\n ? CubismBlendMode.Multiplicative\n : CubismBlendMode.Normal;\n }\n\n /// \n /// Drawableのマスク使用時の反転設定を取得する。\n /// マスクを使用しない場合は無視される\n /// \n /// Drawableのインデックス\n /// Drawableのマスクの反転設定\n public unsafe bool GetDrawableInvertedMask(int drawableIndex)\n {\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model)[drawableIndex];\n\n return IsBitSet(constantFlags, CsmEnum.CsmIsInvertedMask);\n }\n\n /// \n /// Drawableの表示情報を取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableが表示\n /// false Drawableが非表示\n /// \n public unsafe bool GetDrawableDynamicFlagIsVisible(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmIsVisible);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの表示状態が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの表示状態が直近のCubismModel::Update関数で変化した\n /// false Drawableの表示状態が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagVisibilityDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmVisibilityDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの不透明度が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの不透明度が直近のCubismModel::Update関数で変化した\n /// false Drawableの不透明度が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagOpacityDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmOpacityDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableのDrawOrderが変化したかを取得する。\n /// DrawOrderはArtMesh上で指定する0から1000の情報\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの不透明度が直近のCubismModel::Update関数で変化した\n /// false Drawableの不透明度が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagDrawOrderDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmDrawOrderDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの描画の順序が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの描画の順序が直近のCubismModel::Update関数で変化した\n /// false Drawableの描画の順序が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagRenderOrderDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmRenderOrderDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの頂点情報が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの頂点情報が直近のCubismModel::Update関数で変化した\n /// false Drawableの頂点情報が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagVertexPositionsDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmVertexPositionsDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの乗算色・スクリーン色が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの乗算色・スクリーン色が直近のCubismModel::Update関数で変化した\n /// false Drawableの乗算色・スクリーン色が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagBlendColorDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmBlendColorDidChange);\n }\n\n /// \n /// Drawableのクリッピングマスクリストを取得する。\n /// \n /// Drawableのクリッピングマスクリスト\n public unsafe int** GetDrawableMasks() { return CubismCore.GetDrawableMasks(Model); }\n\n /// \n /// Drawableのクリッピングマスクの個数リストを取得する。\n /// \n /// Drawableのクリッピングマスクの個数リスト\n public unsafe int* GetDrawableMaskCounts() { return CubismCore.GetDrawableMaskCounts(Model); }\n\n /// \n /// クリッピングマスクを使用しているかどうか?\n /// \n /// \n /// true クリッピングマスクを使用している\n /// false クリッピングマスクを使用していない\n /// \n public unsafe bool IsUsingMasking()\n {\n for ( var d = 0; d < CubismCore.GetDrawableCount(Model); ++d )\n {\n if ( CubismCore.GetDrawableMaskCounts(Model)[d] <= 0 )\n {\n continue;\n }\n\n return true;\n }\n\n return false;\n }\n\n /// \n /// 保存されたパラメータを読み込む\n /// \n public unsafe void LoadParameters()\n {\n var parameterCount = CubismCore.GetParameterCount(Model);\n var savedParameterCount = _savedParameters.Count;\n\n if ( parameterCount > savedParameterCount )\n {\n parameterCount = savedParameterCount;\n }\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n _parameterValues[i] = _savedParameters[i];\n }\n }\n\n /// \n /// パラメータを保存する。\n /// \n public unsafe void SaveParameters()\n {\n var parameterCount = CubismCore.GetParameterCount(Model);\n var savedParameterCount = _savedParameters.Count;\n\n if ( savedParameterCount != parameterCount )\n {\n _savedParameters.Clear();\n for ( var i = 0; i < parameterCount; ++i )\n {\n _savedParameters.Add(_parameterValues[i]);\n }\n }\n else\n {\n for ( var i = 0; i < parameterCount; ++i )\n {\n _savedParameters[i] = _parameterValues[i];\n }\n }\n }\n\n /// \n /// drawableの乗算色を取得する\n /// \n public CubismTextureColor GetMultiplyColor(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelMultiplyColors() ||\n GetOverwriteFlagForDrawableMultiplyColors(drawableIndex) )\n {\n return _userMultiplyColors[drawableIndex].Color;\n }\n\n var color = GetDrawableMultiplyColor(drawableIndex);\n\n return new CubismTextureColor(color.X, color.Y, color.Z, color.W);\n }\n\n /// \n /// drawableのスクリーン色を取得する\n /// \n public CubismTextureColor GetScreenColor(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelScreenColors() ||\n GetOverwriteFlagForDrawableScreenColors(drawableIndex) )\n {\n return _userScreenColors[drawableIndex].Color;\n }\n\n var color = GetDrawableScreenColor(drawableIndex);\n\n return new CubismTextureColor(color.X, color.Y, color.Z, color.W);\n }\n\n /// \n /// drawableの乗算色を設定する\n /// \n public void SetMultiplyColor(int drawableIndex, CubismTextureColor color) { SetMultiplyColor(drawableIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// drawableの乗算色を設定する\n /// \n public void SetMultiplyColor(int drawableIndex, float r, float g, float b, float a = 1.0f)\n {\n _userMultiplyColors[drawableIndex].Color.R = r;\n _userMultiplyColors[drawableIndex].Color.G = g;\n _userMultiplyColors[drawableIndex].Color.B = b;\n _userMultiplyColors[drawableIndex].Color.A = a;\n }\n\n /// \n /// drawableのスクリーン色を設定する\n /// \n /// \n /// \n public void SetScreenColor(int drawableIndex, CubismTextureColor color) { SetScreenColor(drawableIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// drawableのスクリーン色を設定する\n /// \n public void SetScreenColor(int drawableIndex, float r, float g, float b, float a = 1.0f)\n {\n _userScreenColors[drawableIndex].Color.R = r;\n _userScreenColors[drawableIndex].Color.G = g;\n _userScreenColors[drawableIndex].Color.B = b;\n _userScreenColors[drawableIndex].Color.A = a;\n }\n\n /// \n /// partの乗算色を取得する\n /// \n public CubismTextureColor GetPartMultiplyColor(int partIndex) { return _userPartMultiplyColors[partIndex].Color; }\n\n /// \n /// partの乗算色を取得する\n /// \n public CubismTextureColor GetPartScreenColor(int partIndex) { return _userPartScreenColors[partIndex].Color; }\n\n /// \n /// partのスクリーン色を設定する\n /// \n public void SetPartMultiplyColor(int partIndex, CubismTextureColor color) { SetPartMultiplyColor(partIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// partの乗算色を設定する\n /// \n public void SetPartMultiplyColor(int partIndex, float r, float g, float b, float a = 1.0f) { SetPartColor(partIndex, r, g, b, a, _userPartMultiplyColors, _userMultiplyColors); }\n\n /// \n /// partのスクリーン色を設定する\n /// \n public void SetPartScreenColor(int partIndex, CubismTextureColor color) { SetPartScreenColor(partIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// partのスクリーン色を設定する\n /// \n /// \n public void SetPartScreenColor(int partIndex, float r, float g, float b, float a = 1.0f) { SetPartColor(partIndex, r, g, b, a, _userPartScreenColors, _userScreenColors); }\n\n /// \n /// SDKからモデル全体の乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForModelMultiplyColors() { return _isOverwrittenModelMultiplyColors; }\n\n /// \n /// SDKからモデル全体のスクリーン色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForModelScreenColors() { return _isOverwrittenModelScreenColors; }\n\n /// \n /// SDKからモデル全体の乗算色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForModelMultiplyColors(bool value) { _isOverwrittenModelMultiplyColors = value; }\n\n /// \n /// SDKからモデル全体のスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForModelScreenColors(bool value) { _isOverwrittenModelScreenColors = value; }\n\n /// \n /// SDKからdrawableの乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForDrawableMultiplyColors(int drawableIndex) { return _userMultiplyColors[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableのスクリーン色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForDrawableScreenColors(int drawableIndex) { return _userScreenColors[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableの乗算色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableMultiplyColors(int drawableIndex, bool value) { _userMultiplyColors[drawableIndex].IsOverwritten = value; }\n\n /// \n /// SDKからdrawableのスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableScreenColors(int drawableIndex, bool value) { _userScreenColors[drawableIndex].IsOverwritten = value; }\n\n /// \n /// SDKからpartの乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteColorForPartMultiplyColors(int partIndex) { return _userPartMultiplyColors[partIndex].IsOverwritten; }\n\n /// \n /// SDKからpartのスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public bool GetOverwriteColorForPartScreenColors(int partIndex) { return _userPartScreenColors[partIndex].IsOverwritten; }\n\n /// \n /// Drawableのカリング情報を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのカリング情報\n public unsafe bool GetDrawableCulling(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelCullings() || GetOverwriteFlagForDrawableCullings(drawableIndex) )\n {\n return _userCullings[drawableIndex].IsCulling;\n }\n\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model);\n\n return !IsBitSet(constantFlags[drawableIndex], CsmEnum.CsmIsDoubleSided);\n }\n\n /// \n /// Drawableのカリング情報を設定する\n /// \n public void SetDrawableCulling(int drawableIndex, bool isCulling) { _userCullings[drawableIndex].IsCulling = isCulling; }\n\n /// \n /// SDKからモデル全体のカリング設定を上書きするか。\n /// \n /// \n /// true -> SDK上のカリング設定を使用\n /// false -> モデルのカリング設定を使用\n /// \n public bool GetOverwriteFlagForModelCullings() { return _isOverwrittenCullings; }\n\n /// \n /// SDKからモデル全体のカリング設定を上書きするかをセットする\n /// SDK上のカリング設定を使うならtrue、モデルのカリング設定を使うならfalse\n /// \n public void SetOverwriteFlagForModelCullings(bool value) { _isOverwrittenCullings = value; }\n\n /// \n /// SDKからdrawableのカリング設定を上書きするか。\n /// \n /// \n /// true -> SDK上のカリング設定を使用\n /// false -> モデルのカリング設定を使用\n /// \n public bool GetOverwriteFlagForDrawableCullings(int drawableIndex) { return _userCullings[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableのカリング設定を上書きするかをセットする\n /// SDK上のカリング設定を使うならtrue、モデルのカリング設定を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableCullings(int drawableIndex, bool value) { _userCullings[drawableIndex].IsOverwritten = value; }\n\n /// \n /// モデルの不透明度を取得する\n /// \n /// 不透明度の値\n public float GetModelOpacity() { return _modelOpacity; }\n\n /// \n /// モデルの不透明度を設定する\n /// \n /// 不透明度の値\n public void SetModelOpacity(float value) { _modelOpacity = value; }\n\n private static bool IsBitSet(byte data, byte mask) { return (data & mask) == mask; }\n\n public void SetOverwriteColorForPartMultiplyColors(int partIndex, bool value)\n {\n _userPartMultiplyColors[partIndex].IsOverwritten = value;\n SetOverwriteColorForPartColors(partIndex, value, _userPartMultiplyColors, _userMultiplyColors);\n }\n\n public void SetOverwriteColorForPartScreenColors(int partIndex, bool value)\n {\n _userPartScreenColors[partIndex].IsOverwritten = value;\n SetOverwriteColorForPartColors(partIndex, value, _userPartScreenColors, _userScreenColors);\n }\n\n /// \n /// パラメータのIDを取得する。\n /// \n /// パラメータのIndex\n /// パラメータのID\n public string GetParameterId(int parameterIndex)\n {\n if ( 0 <= parameterIndex && parameterIndex < ParameterIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of ParameterIds size\");\n }\n\n return ParameterIds[parameterIndex];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/ConcatAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that concatenates multiple audio sources\n/// \npublic sealed class ConcatAudioSource : IAudioSource\n{\n private readonly IAudioSource[] sources;\n\n public ConcatAudioSource(IAudioSource[] sources, IReadOnlyDictionary metadata)\n {\n this.sources = sources;\n Metadata = metadata;\n if ( sources.Length == 0 )\n {\n throw new ArgumentException(\"At least one source must be provided.\", nameof(sources));\n }\n\n var duration = TimeSpan.Zero;\n var sampleRate = sources[0].SampleRate;\n var framesCount = 0L;\n var channelCount = sources[0].ChannelCount;\n var bitsPerSample = sources[0].BitsPerSample;\n var totalDuration = TimeSpan.Zero;\n\n for ( var i = 0; i < sources.Length; i++ )\n {\n duration += sources[i].Duration;\n totalDuration += sources[i].TotalDuration;\n framesCount += sources[i].FramesCount;\n if ( channelCount != sources[i].ChannelCount )\n {\n throw new ArgumentException(\"All sources must have the same channel count.\", nameof(sources));\n }\n\n if ( sampleRate != sources[i].SampleRate )\n {\n throw new ArgumentException(\"All sources must have the same sample rate.\", nameof(sources));\n }\n\n if ( bitsPerSample != sources[i].BitsPerSample )\n {\n throw new ArgumentException(\"All sources must have the same bits per sample.\", nameof(sources));\n }\n }\n\n Duration = duration;\n SampleRate = sampleRate;\n FramesCount = framesCount;\n ChannelCount = channelCount;\n BitsPerSample = bitsPerSample;\n TotalDuration = totalDuration;\n }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration { get; }\n\n public TimeSpan TotalDuration { get; }\n\n public uint SampleRate { get; }\n\n public long FramesCount { get; }\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public void Dispose()\n {\n foreach ( var source in sources )\n {\n source.Dispose();\n }\n }\n\n public async Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var slices = await GetMemorySlicesAsync(\n (source, offset, frames, token) => source.GetFramesAsync(offset, frames, token),\n startFrame,\n maxFrames,\n cancellationToken);\n\n return MergeMemorySlices(slices);\n }\n\n public async Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var slices = await GetMemorySlicesAsync(\n (source, offset, frames, token) => source.GetSamplesAsync(offset, frames, token),\n startFrame,\n maxFrames,\n cancellationToken);\n\n return MergeMemorySlices(slices);\n }\n\n public async Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var slices = await GetMemorySlicesAsync(\n (source, offset, frames, token) => source.GetFramesAsync(offset, frames, token),\n startFrame,\n maxFrames,\n cancellationToken);\n\n CopySlices(slices, destination);\n long length = slices.Sum(slice => slice.Length);\n\n return (int)(length / BitsPerSample * 8 / ChannelCount);\n }\n\n private async Task>> GetMemorySlicesAsync(Func>> getMemoryFunc,\n long startFrame,\n int maxFrames,\n CancellationToken cancellationToken)\n {\n var result = new List>();\n var framesToRead = maxFrames;\n var offset = startFrame;\n\n foreach ( var source in sources )\n {\n if ( offset >= source.FramesCount )\n {\n offset -= source.FramesCount;\n\n continue;\n }\n\n var framesFromThisSource = Math.Min(framesToRead, (int)(source.FramesCount - offset));\n var memory = await getMemoryFunc(source, offset, framesFromThisSource, cancellationToken);\n\n result.Add(memory);\n\n framesToRead -= framesFromThisSource;\n offset = 0;\n\n if ( framesToRead <= 0 )\n {\n break;\n }\n }\n\n return result;\n }\n\n private static Memory MergeMemorySlices(List> slices)\n {\n if ( slices.Count == 1 )\n {\n return slices[0]; // If all frames/samples are from a single source, return directly\n }\n\n var totalSize = slices.Sum(slice => slice.Length);\n var merged = new T[totalSize];\n CopySlices(slices, merged);\n\n return merged.AsMemory();\n }\n\n private static void CopySlices(List> slices, Memory destination)\n {\n var position = 0;\n\n foreach ( var slice in slices )\n {\n slice.CopyTo(destination.Slice(position));\n position += slice.Length;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MergedMemoryChunks.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// This is a little helper for using multiple chunks of memory without writing it to auxiliary buffers\n/// \n/// \n/// It is used to consume the data that was appended in multiple calls and couldn't be used previously.\n/// Note: If the requested chunks are not contiguous, the data will be copied to a new buffer.\n/// \npublic class MergedMemoryChunks\n{\n private readonly List> chunks = [];\n\n private int currentChunkIndex;\n\n public MergedMemoryChunks(ReadOnlyMemory initialChunk)\n {\n chunks.Add(initialChunk);\n Length = initialChunk.Length;\n }\n\n public MergedMemoryChunks() { }\n\n /// \n /// The total length of the chunks\n /// \n public long Length { get; private set; }\n\n /// \n /// The current position in the chunks\n /// \n public long Position { get; private set; }\n\n /// \n /// The absolute position of the current chunk\n /// \n public long AbsolutePositionOfCurrentChunk { get; private set; }\n\n public void AddChunk(ReadOnlyMemory newChunk)\n {\n chunks.Add(newChunk);\n Length += newChunk.Length;\n }\n\n /// \n /// Tries to skip the given number of bytes in the chunks, advancing the position.\n /// \n public bool TrySkip(uint count)\n {\n var bytesToSkip = count;\n while ( bytesToSkip > 0 )\n {\n var positionInCurrentChunk = Position - AbsolutePositionOfCurrentChunk;\n var currentChunk = chunks[currentChunkIndex];\n if ( positionInCurrentChunk + bytesToSkip <= currentChunk.Length )\n {\n Position += bytesToSkip;\n\n return true;\n }\n\n if ( currentChunkIndex + 1 == chunks.Count )\n {\n return false;\n }\n\n var remainingInCurrentChunk = (int)(currentChunk.Length - positionInCurrentChunk);\n\n currentChunkIndex++;\n\n Position += remainingInCurrentChunk;\n AbsolutePositionOfCurrentChunk = Position;\n bytesToSkip -= (uint)remainingInCurrentChunk;\n }\n\n return true;\n }\n\n /// \n /// Restarts the reading from the beginning of the chunks\n /// \n public void RestartRead()\n {\n currentChunkIndex = 0;\n AbsolutePositionOfCurrentChunk = 0;\n Position = 0;\n }\n\n /// \n /// Gets a slice of the given size from the chunks\n /// \n /// \n /// If the data will span multiple chunks, it will be copied to a new buffer.\n /// \n public ReadOnlyMemory GetChunk(int size)\n {\n var positionInCurrentChunk = (int)(Position - AbsolutePositionOfCurrentChunk);\n var currentChunk = chunks[currentChunkIndex];\n // First, we try to just slice the current chunk if possible\n if ( currentChunk.Length >= positionInCurrentChunk + size )\n {\n Position += size;\n if ( currentChunk.Length == positionInCurrentChunk + size )\n {\n currentChunkIndex++;\n AbsolutePositionOfCurrentChunk = Position;\n }\n\n return currentChunk.Slice(positionInCurrentChunk, size);\n }\n\n // We cannot slice it, so we need to compose it\n var buffer = new byte[size];\n var bufferIndex = 0;\n var remainingSize = size;\n while ( remainingSize > 0 )\n {\n var currentChunkAddressable = currentChunk.Slice(positionInCurrentChunk, Math.Min(remainingSize, currentChunk.Length - positionInCurrentChunk));\n\n remainingSize -= currentChunkAddressable.Length;\n Position += currentChunkAddressable.Length;\n currentChunkAddressable.CopyTo(buffer.AsMemory(bufferIndex));\n bufferIndex += currentChunkAddressable.Length;\n if ( remainingSize > 0 && currentChunkIndex >= chunks.Count )\n {\n throw new InvalidOperationException($\"Not enough data was available in the chunks to read {size} bytes.\");\n }\n\n if ( remainingSize > 0 )\n {\n positionInCurrentChunk = 0;\n currentChunkIndex++;\n AbsolutePositionOfCurrentChunk = Position;\n currentChunk = chunks[currentChunkIndex];\n }\n }\n\n return buffer.AsMemory();\n }\n\n /// \n /// Reads a 32-bit unsigned integer from the chunks\n /// \n public uint ReadUInt32LittleEndian()\n {\n var chunk = GetChunk(4);\n\n return BinaryPrimitives.ReadUInt32LittleEndian(chunk.Span);\n }\n\n /// \n /// Reads a 16-bit unsigned integer from the chunks\n /// \n public ushort ReadUInt16LittleEndian()\n {\n var chunk = GetChunk(2);\n\n return BinaryPrimitives.ReadUInt16LittleEndian(chunk.Span);\n }\n\n /// \n /// Reads a 8-bit unsigned integer from the chunks\n /// \n /// \n /// \n public byte ReadByte()\n {\n var chunk = GetChunk(1);\n\n return chunk.Span[0];\n }\n\n public short ReadInt16LittleEndian()\n {\n var chunk = GetChunk(2);\n\n return BinaryPrimitives.ReadInt16LittleEndian(chunk.Span);\n }\n\n public int ReadInt24LittleEndian()\n {\n var chunk = GetChunk(3);\n\n return chunk.Span[0] | (chunk.Span[1] << 8) | (chunk.Span[2] << 16);\n }\n\n public int ReadInt32LittleEndian()\n {\n var chunk = GetChunk(4);\n\n return BinaryPrimitives.ReadInt32LittleEndian(chunk.Span);\n }\n\n public long ReadInt64LittleEndian()\n {\n var chunk = GetChunk(8);\n\n return BinaryPrimitives.ReadInt64LittleEndian(chunk.Span);\n }\n\n /// \n /// Copies the content of the current chunks to a single buffer\n /// \n /// \n public byte[] ToArray()\n {\n var buffer = new byte[Length];\n var bufferIndex = 0;\n foreach ( var chunk in chunks )\n {\n chunk.Span.CopyTo(buffer.AsSpan(bufferIndex));\n bufferIndex += chunk.Length;\n }\n\n return buffer;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/LipSync/VBridgerLipSyncService.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.LipSync;\n\n/// \n/// LipSync service for VBridger parameter conventions.\n/// \npublic sealed class VBridgerLipSyncService : ILive2DAnimationService\n{\n public VBridgerLipSyncService(ILogger logger, IAudioProgressNotifier audioProgressNotifier)\n {\n _logger = logger;\n _audioProgressNotifier = audioProgressNotifier;\n _phonemeMap = InitializeMisakiPhonemeMap();\n\n SubscribeToAudioProgressNotifier();\n }\n\n private void InitializeCurrentParameters()\n {\n if ( _model == null )\n {\n return;\n }\n\n var cubismModel = _model.Model;\n\n // Fetch initial values from the model\n _currentParameterValues[ParamMouthOpenY] = cubismModel.GetParameterValue(ParamMouthOpenY);\n _currentParameterValues[ParamJawOpen] = cubismModel.GetParameterValue(ParamJawOpen);\n _currentParameterValues[ParamMouthForm] = cubismModel.GetParameterValue(ParamMouthForm);\n _currentParameterValues[ParamMouthShrug] = cubismModel.GetParameterValue(ParamMouthShrug);\n _currentParameterValues[ParamMouthFunnel] = cubismModel.GetParameterValue(ParamMouthFunnel);\n _currentParameterValues[ParamMouthPuckerWiden] = cubismModel.GetParameterValue(ParamMouthPuckerWiden);\n _currentParameterValues[ParamMouthPressLipOpen] = cubismModel.GetParameterValue(ParamMouthPressLipOpen);\n _currentParameterValues[ParamMouthX] = cubismModel.GetParameterValue(ParamMouthX);\n _currentParameterValues[ParamCheekPuffC] = 0f;\n }\n\n #region Configuration Constants\n\n private const float SMOOTHING_FACTOR = 35.0f; // How quickly parameters move towards target (higher = faster)\n\n private const float NEUTRAL_RETURN_FACTOR = 15.0f; // How quickly parameters return to neutral when idle\n\n private const float CHEEK_PUFF_DECAY_FACTOR = 80.0f; // How quickly CheekPuff returns to 0\n\n private const float NEUTRAL_THRESHOLD = 0.02f; // Threshold for considering a value as neutral\n\n #endregion\n\n #region Parameter Names\n\n private static readonly string ParamMouthOpenY = \"ParamMouthOpenY\";\n\n private static readonly string ParamJawOpen = \"ParamJawOpen\";\n\n private static readonly string ParamMouthForm = \"ParamMouthForm\";\n\n private static readonly string ParamMouthShrug = \"ParamMouthShrug\";\n\n private static readonly string ParamMouthFunnel = \"ParamMouthFunnel\";\n\n private static readonly string ParamMouthPuckerWiden = \"ParamMouthPuckerWiden\";\n\n private static readonly string ParamMouthPressLipOpen = \"ParamMouthPressLipOpen\";\n\n private static readonly string ParamMouthX = \"ParamMouthX\";\n\n private static readonly string ParamCheekPuffC = \"ParamCheekPuffC\";\n\n #endregion\n\n #region Dependencies and State\n\n private LAppModel? _model;\n\n private readonly IAudioProgressNotifier _audioProgressNotifier;\n\n private readonly List _activePhonemes = new();\n\n private int _currentPhonemeIndex = -1;\n\n private bool _isPlaying = false;\n\n private bool _isStarted = false;\n\n private bool _disposed = false;\n\n private PhonemePose _currentTargetPose = PhonemePose.Neutral;\n\n private PhonemePose _nextTargetPose = PhonemePose.Neutral;\n\n private float _interpolationT = 0f;\n\n private readonly Dictionary _currentParameterValues = new();\n\n private readonly Dictionary _phonemeMap;\n\n private readonly HashSet _phonemeShapeIgnoreChars = ['ˈ', 'ˌ', 'ː']; // Ignore stress/length marks\n\n private readonly ILogger _logger;\n\n #endregion\n\n #region ILipSyncService Implementation\n\n private void SubscribeToAudioProgressNotifier()\n {\n ObjectDisposedException.ThrowIf(_disposed, this);\n\n UnsubscribeFromCurrentNotifier();\n\n _audioProgressNotifier.ChunkPlaybackStarted += HandleChunkStarted;\n _audioProgressNotifier.ChunkPlaybackEnded += HandleChunkEnded;\n _audioProgressNotifier.PlaybackProgress += HandleProgress;\n }\n\n private void UnsubscribeFromCurrentNotifier()\n {\n _audioProgressNotifier.ChunkPlaybackStarted -= HandleChunkStarted;\n _audioProgressNotifier.ChunkPlaybackEnded -= HandleChunkEnded;\n _audioProgressNotifier.PlaybackProgress -= HandleProgress;\n\n ResetState();\n }\n\n public void Start(LAppModel model)\n {\n ObjectDisposedException.ThrowIf(_disposed, this);\n\n _model = model;\n\n InitializeCurrentParameters();\n\n _isStarted = true;\n\n _logger.LogInformation(\"Started lip syncing.\");\n }\n\n public void Stop()\n {\n _isStarted = false;\n ResetState();\n _logger.LogInformation(\"Stopped lip syncing.\");\n }\n\n #endregion\n\n #region Update Logic\n\n public void Update(float deltaTime)\n {\n if ( deltaTime <= 0.0f || _disposed || !_isStarted || _model == null )\n {\n return;\n }\n\n if ( !_isPlaying )\n {\n SmoothParametersToNeutral(deltaTime);\n\n return;\n }\n\n var easedT = EaseInOutQuad(_interpolationT);\n var frameTargetPose = PhonemePose.Lerp(_currentTargetPose, _nextTargetPose, easedT);\n SmoothParametersToTarget(frameTargetPose, deltaTime);\n ApplySmoothedParameters();\n }\n\n private void UpdateTargetPoses(float currentTime)\n {\n if ( _model == null || !_isPlaying || _activePhonemes.Count == 0 )\n {\n if ( _currentTargetPose != PhonemePose.Neutral || _nextTargetPose != PhonemePose.Neutral )\n {\n _currentTargetPose = GetPoseFromCurrentValues();\n _nextTargetPose = PhonemePose.Neutral;\n _interpolationT = 0f;\n _logger.LogTrace(\"Targeting Neutral Pose.\");\n }\n\n _currentPhonemeIndex = -1;\n\n return;\n }\n\n var foundIndex = FindPhonemeIndexAtTime(currentTime);\n\n if ( foundIndex != -1 )\n {\n if ( foundIndex != _currentPhonemeIndex )\n {\n _logger.LogTrace(\"Phoneme changed: {PhonemeIndex} -> {FoundIndex} ({Phoneme}) at T={CurrentTime:F3}\", _currentPhonemeIndex, foundIndex, _activePhonemes[foundIndex].Phoneme, currentTime);\n\n if ( _currentPhonemeIndex == -1 )\n {\n _currentTargetPose = GetPoseFromCurrentValues();\n }\n else\n {\n _currentTargetPose = GetPoseForPhoneme(_activePhonemes[_currentPhonemeIndex].Phoneme);\n }\n\n _nextTargetPose = GetPoseForPhoneme(_activePhonemes[foundIndex].Phoneme);\n _currentPhonemeIndex = foundIndex;\n }\n\n var currentPh = _activePhonemes[_currentPhonemeIndex];\n var duration = currentPh.EndTime - currentPh.StartTime;\n _interpolationT = duration > 0.001\n ? (float)Math.Clamp((currentTime - currentPh.StartTime) / duration, 0.0, 1.0)\n : 1.0f;\n }\n else\n {\n if ( _currentTargetPose != PhonemePose.Neutral || _nextTargetPose != PhonemePose.Neutral )\n {\n _currentTargetPose = GetPoseFromCurrentValues();\n _nextTargetPose = PhonemePose.Neutral;\n _interpolationT = 0f;\n _logger.LogTrace(\"Targeting Neutral Pose (Gap/End).\");\n }\n\n if ( _activePhonemes.Count > 0 &&\n (currentTime < _activePhonemes.First().StartTime - 0.1 ||\n currentTime > _activePhonemes.Last().EndTime + 0.1) )\n {\n _currentPhonemeIndex = -1;\n }\n }\n }\n\n private int FindPhonemeIndexAtTime(float currentTime)\n {\n if ( _currentPhonemeIndex >= 0 && _currentPhonemeIndex < _activePhonemes.Count )\n {\n var ph = _activePhonemes[_currentPhonemeIndex];\n if ( currentTime >= ph.StartTime && currentTime < ph.EndTime + 0.001 )\n {\n return _currentPhonemeIndex;\n }\n }\n\n var searchStartIndex = Math.Max(0, _currentPhonemeIndex - 1);\n for ( var i = searchStartIndex; i < _activePhonemes.Count; i++ )\n {\n var ph = _activePhonemes[i];\n if ( currentTime >= ph.StartTime && currentTime < ph.EndTime + 0.001 )\n {\n return i;\n }\n }\n\n if ( _activePhonemes.Count > 0 )\n {\n if ( currentTime < _activePhonemes[0].StartTime )\n {\n return -1;\n }\n\n if ( Math.Abs(currentTime - _activePhonemes.Last().EndTime) < 0.01 )\n {\n return _activePhonemes.Count - 1;\n }\n }\n\n return -1;\n }\n\n private PhonemePose GetPoseFromCurrentValues()\n {\n return new PhonemePose(\n _currentParameterValues[ParamMouthOpenY],\n _currentParameterValues[ParamJawOpen],\n _currentParameterValues[ParamMouthForm],\n _currentParameterValues[ParamMouthShrug],\n _currentParameterValues[ParamMouthFunnel],\n _currentParameterValues[ParamMouthPuckerWiden],\n _currentParameterValues[ParamMouthPressLipOpen],\n _currentParameterValues[ParamMouthX],\n _currentParameterValues[ParamCheekPuffC]\n );\n }\n\n #endregion\n\n #region Parameter Smoothing\n\n private void SmoothParametersToTarget(PhonemePose targetPose, float deltaTime)\n {\n var smoothFactor = SMOOTHING_FACTOR * deltaTime;\n\n _currentParameterValues[ParamMouthOpenY] = Lerp(_currentParameterValues[ParamMouthOpenY], targetPose.MouthOpenY, smoothFactor);\n _currentParameterValues[ParamJawOpen] = Lerp(_currentParameterValues[ParamJawOpen], targetPose.JawOpen, smoothFactor);\n _currentParameterValues[ParamMouthForm] = Lerp(_currentParameterValues[ParamMouthForm], targetPose.MouthForm, smoothFactor);\n _currentParameterValues[ParamMouthShrug] = Lerp(_currentParameterValues[ParamMouthShrug], targetPose.MouthShrug, smoothFactor);\n _currentParameterValues[ParamMouthFunnel] = Lerp(_currentParameterValues[ParamMouthFunnel], targetPose.MouthFunnel, smoothFactor);\n _currentParameterValues[ParamMouthPuckerWiden] = Lerp(_currentParameterValues[ParamMouthPuckerWiden], targetPose.MouthPuckerWiden, smoothFactor);\n _currentParameterValues[ParamMouthPressLipOpen] = Lerp(_currentParameterValues[ParamMouthPressLipOpen], targetPose.MouthPressLipOpen, smoothFactor);\n _currentParameterValues[ParamMouthX] = Lerp(_currentParameterValues[ParamMouthX], targetPose.MouthX, smoothFactor);\n\n if ( targetPose.CheekPuffC > NEUTRAL_THRESHOLD )\n {\n _currentParameterValues[ParamCheekPuffC] = Lerp(_currentParameterValues[ParamCheekPuffC], targetPose.CheekPuffC, smoothFactor);\n }\n else\n {\n var decayFactor = CHEEK_PUFF_DECAY_FACTOR * deltaTime;\n _currentParameterValues[ParamCheekPuffC] = Lerp(_currentParameterValues[ParamCheekPuffC], 0.0f, decayFactor);\n }\n }\n\n private void SmoothParametersToNeutral(float deltaTime)\n {\n var smoothFactor = NEUTRAL_RETURN_FACTOR * deltaTime;\n var neutral = PhonemePose.Neutral;\n\n _currentParameterValues[ParamMouthOpenY] = Lerp(_currentParameterValues[ParamMouthOpenY], neutral.MouthOpenY, smoothFactor);\n _currentParameterValues[ParamJawOpen] = Lerp(_currentParameterValues[ParamJawOpen], neutral.JawOpen, smoothFactor);\n _currentParameterValues[ParamMouthForm] = Lerp(_currentParameterValues[ParamMouthForm], neutral.MouthForm, smoothFactor);\n _currentParameterValues[ParamMouthShrug] = Lerp(_currentParameterValues[ParamMouthShrug], neutral.MouthShrug, smoothFactor);\n _currentParameterValues[ParamMouthFunnel] = Lerp(_currentParameterValues[ParamMouthFunnel], neutral.MouthFunnel, smoothFactor);\n _currentParameterValues[ParamMouthPuckerWiden] = Lerp(_currentParameterValues[ParamMouthPuckerWiden], neutral.MouthPuckerWiden, smoothFactor);\n _currentParameterValues[ParamMouthPressLipOpen] = Lerp(_currentParameterValues[ParamMouthPressLipOpen], neutral.MouthPressLipOpen, smoothFactor);\n _currentParameterValues[ParamMouthX] = Lerp(_currentParameterValues[ParamMouthX], neutral.MouthX, smoothFactor);\n\n var decayFactor = CHEEK_PUFF_DECAY_FACTOR * deltaTime;\n _currentParameterValues[ParamCheekPuffC] = Lerp(_currentParameterValues[ParamCheekPuffC], 0.0f, decayFactor);\n\n ApplySmoothedParameters();\n }\n\n private bool IsApproximatelyNeutral()\n {\n var neutral = PhonemePose.Neutral;\n\n return Math.Abs(_currentParameterValues[ParamMouthOpenY] - neutral.MouthOpenY) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamJawOpen] - neutral.JawOpen) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthForm] - neutral.MouthForm) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthShrug] - neutral.MouthShrug) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthFunnel] - neutral.MouthFunnel) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthPuckerWiden] - neutral.MouthPuckerWiden) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthPressLipOpen] - neutral.MouthPressLipOpen) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthX] - neutral.MouthX) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamCheekPuffC] - neutral.CheekPuffC) < NEUTRAL_THRESHOLD;\n }\n\n private void ApplySmoothedParameters()\n {\n if ( _model == null )\n {\n _logger.LogWarning(\"Attempted to apply parameters but model is null.\");\n\n return;\n }\n\n try\n {\n var cubismModel = _model.Model;\n cubismModel.SetParameterValue(ParamMouthOpenY, _currentParameterValues[ParamMouthOpenY]);\n cubismModel.SetParameterValue(ParamJawOpen, _currentParameterValues[ParamJawOpen]);\n cubismModel.SetParameterValue(ParamMouthForm, _currentParameterValues[ParamMouthForm]);\n cubismModel.SetParameterValue(ParamMouthShrug, _currentParameterValues[ParamMouthShrug]);\n cubismModel.SetParameterValue(ParamMouthFunnel, _currentParameterValues[ParamMouthFunnel]);\n cubismModel.SetParameterValue(ParamMouthPuckerWiden, _currentParameterValues[ParamMouthPuckerWiden]);\n cubismModel.SetParameterValue(ParamMouthPressLipOpen, _currentParameterValues[ParamMouthPressLipOpen]);\n cubismModel.SetParameterValue(ParamMouthX, _currentParameterValues[ParamMouthX]);\n cubismModel.SetParameterValue(ParamCheekPuffC, _currentParameterValues[ParamCheekPuffC]);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error applying Live2D parameters\");\n }\n }\n\n #endregion\n\n #region Event Handlers and State Management\n\n private void HandleChunkStarted(object? sender, AudioChunkPlaybackStartedEvent e)\n {\n if ( !_isStarted )\n {\n return;\n }\n\n _logger.LogTrace(\"Audio Chunk Playback Started.\");\n ProcessAudioSegment(e.Chunk);\n _isPlaying = true;\n _currentPhonemeIndex = -1;\n\n var initialTime = _activePhonemes.Count != 0 ? (float)_activePhonemes.First().StartTime : 0f;\n UpdateTargetPoses(initialTime);\n }\n\n private void HandleChunkEnded(object? sender, AudioChunkPlaybackEndedEvent e)\n {\n if ( !_isStarted )\n {\n return;\n }\n\n _logger.LogTrace(\"Audio Chunk Playback Ended.\");\n _isPlaying = false;\n }\n\n private void HandleProgress(object? sender, AudioPlaybackProgressEvent e)\n {\n if ( !_isStarted || !_isPlaying )\n {\n return;\n }\n\n UpdateTargetPoses((float)e.CurrentPlaybackTime.TotalSeconds);\n }\n\n private void ResetState()\n {\n _activePhonemes.Clear();\n _currentPhonemeIndex = -1;\n _isPlaying = false;\n _currentTargetPose = PhonemePose.Neutral;\n _nextTargetPose = PhonemePose.Neutral;\n _interpolationT = 0f;\n InitializeCurrentParameters();\n _logger.LogTrace(\"LipSync state reset.\");\n }\n\n #endregion\n\n #region Phoneme Processing\n\n private void ProcessAudioSegment(AudioSegment segment)\n {\n _activePhonemes.Clear();\n\n var lastEndTime = 0.0;\n\n foreach ( var token in segment.Tokens )\n {\n if ( string.IsNullOrEmpty(token.Phonemes) || !token.StartTs.HasValue || !token.EndTs.HasValue || token.EndTs.Value <= token.StartTs.Value )\n {\n _logger.LogTrace(\"Skipping invalid token: Phonemes='{Phonemes}', Start={StartTs}, End={EndTs}\", token.Phonemes, token.StartTs, token.EndTs);\n\n continue;\n }\n\n var tokenStartTime = Math.Max(lastEndTime, token.StartTs.Value);\n var tokenEndTime = Math.Max(tokenStartTime + 0.001, token.EndTs.Value);\n\n var phonemeChars = SplitPhonemes(token.Phonemes);\n if ( phonemeChars.Count == 0 )\n {\n _logger.LogTrace(\"No valid phoneme characters found in token: '{Phonemes}'\", token.Phonemes);\n\n continue;\n }\n\n var tokenDuration = tokenEndTime - tokenStartTime;\n var timePerPhoneme = tokenDuration / phonemeChars.Count;\n var currentPhonemeStartTime = tokenStartTime;\n\n foreach ( var phChar in phonemeChars )\n {\n var phonemeEndTime = currentPhonemeStartTime + timePerPhoneme;\n _activePhonemes.Add(new TimedPhoneme { Phoneme = phChar, StartTime = currentPhonemeStartTime, EndTime = phonemeEndTime });\n currentPhonemeStartTime = phonemeEndTime;\n }\n\n lastEndTime = currentPhonemeStartTime;\n }\n\n _activePhonemes.Sort((a, b) => a.StartTime.CompareTo(b.StartTime));\n _logger.LogDebug(\"Processed segment into {Count} timed phonemes.\", _activePhonemes.Count);\n }\n\n private List SplitPhonemes(string phonemeString)\n {\n var result = new List();\n if ( string.IsNullOrEmpty(phonemeString) )\n {\n return result;\n }\n\n foreach ( var c in phonemeString )\n {\n if ( !_phonemeShapeIgnoreChars.Contains(c) )\n {\n result.Add(c.ToString());\n }\n }\n\n return result;\n }\n\n private PhonemePose GetPoseForPhoneme(string phoneme)\n {\n if ( _phonemeMap.TryGetValue(phoneme, out var pose) )\n {\n return pose;\n }\n\n _logger.LogDebug(\"Phoneme '{Phoneme}' not found in map. Returning Neutral.\", phoneme);\n\n return PhonemePose.Neutral;\n }\n\n #endregion\n\n #region Helper Functions\n\n private static float EaseInOutQuad(float t)\n {\n t = Math.Clamp(t, 0.0f, 1.0f);\n\n return t < 0.5f ? 2.0f * t * t : 1.0f - (float)Math.Pow(-2.0 * t + 2.0, 2.0) / 2.0f;\n }\n\n private static float Lerp(float a, float b, float t)\n {\n t = Math.Clamp(t, 0.0f, 1.0f);\n\n return a + (b - a) * t;\n }\n\n #endregion\n\n #region Structs and Maps\n\n public struct PhonemePose : IEquatable\n {\n public float MouthOpenY; // 0-1: How open the mouth is\n\n public float JawOpen; // 0-1: How open the jaw is\n\n public float MouthForm; // -1 (Frown) to +1 (Smile): Vertical lip corner movement\n\n public float MouthShrug; // 0-1: Upward lip shrug/tension\n\n public float MouthFunnel; // 0-1: Funnel shape (lips forward/pursed)\n\n public float MouthPuckerWiden; // -1 (Wide) to +1 (Pucker): Controls mouth width\n\n public float MouthPressLipOpen; // -1 (Pressed Thin) to 0 (Touching) to +1 (Separated/Teeth)\n\n public float MouthX; // -1 to 1: Horizontal mouth shift\n\n public float CheekPuffC; // 0-1: Cheek puff amount\n\n public static PhonemePose Neutral = new();\n\n public PhonemePose(float openY = 0, float jawOpen = 0, float form = 0, float shrug = 0, float funnel = 0, float puckerWiden = 0, float pressLip = 0, float mouthX = 0, float cheekPuff = 0)\n {\n MouthOpenY = openY;\n JawOpen = jawOpen;\n MouthForm = form;\n MouthShrug = shrug;\n MouthFunnel = funnel;\n MouthPuckerWiden = puckerWiden;\n MouthPressLipOpen = pressLip;\n MouthX = mouthX;\n CheekPuffC = cheekPuff;\n }\n\n public static PhonemePose Lerp(PhonemePose a, PhonemePose b, float t)\n {\n t = Math.Clamp(t, 0.0f, 1.0f);\n\n return new PhonemePose(\n VBridgerLipSyncService.Lerp(a.MouthOpenY, b.MouthOpenY, t),\n VBridgerLipSyncService.Lerp(a.JawOpen, b.JawOpen, t),\n VBridgerLipSyncService.Lerp(a.MouthForm, b.MouthForm, t),\n VBridgerLipSyncService.Lerp(a.MouthShrug, b.MouthShrug, t),\n VBridgerLipSyncService.Lerp(a.MouthFunnel, b.MouthFunnel, t),\n VBridgerLipSyncService.Lerp(a.MouthPuckerWiden, b.MouthPuckerWiden, t),\n VBridgerLipSyncService.Lerp(a.MouthPressLipOpen, b.MouthPressLipOpen, t),\n VBridgerLipSyncService.Lerp(a.MouthX, b.MouthX, t),\n VBridgerLipSyncService.Lerp(a.CheekPuffC, b.CheekPuffC, t)\n );\n }\n\n public bool Equals(PhonemePose other)\n {\n const float tolerance = 0.001f;\n\n return Math.Abs(MouthOpenY - other.MouthOpenY) < tolerance &&\n Math.Abs(JawOpen - other.JawOpen) < tolerance &&\n Math.Abs(MouthForm - other.MouthForm) < tolerance &&\n Math.Abs(MouthShrug - other.MouthShrug) < tolerance &&\n Math.Abs(MouthFunnel - other.MouthFunnel) < tolerance &&\n Math.Abs(MouthPuckerWiden - other.MouthPuckerWiden) < tolerance &&\n Math.Abs(MouthPressLipOpen - other.MouthPressLipOpen) < tolerance &&\n Math.Abs(MouthX - other.MouthX) < tolerance &&\n Math.Abs(CheekPuffC - other.CheekPuffC) < tolerance;\n }\n\n public override bool Equals(object? obj) { return obj is PhonemePose other && Equals(other); }\n\n public override int GetHashCode() { return HashCode.Combine(HashCode.Combine(MouthOpenY, JawOpen, MouthForm, MouthShrug, MouthFunnel, MouthPuckerWiden, MouthPressLipOpen, MouthX), CheekPuffC); }\n\n public static bool operator ==(PhonemePose left, PhonemePose right) { return left.Equals(right); }\n\n public static bool operator !=(PhonemePose left, PhonemePose right) { return !(left == right); }\n }\n\n private struct TimedPhoneme\n {\n public string Phoneme;\n\n public double StartTime;\n\n public double EndTime;\n }\n\n private Dictionary InitializeMisakiPhonemeMap()\n {\n // Phoneme to pose mapping based on VBridger parameter definitions:\n // MouthForm: -1 (Frown) to +1 (Smile)\n // MouthPuckerWiden: -1 (Wide) to +1 (Pucker)\n // MouthPressLipOpen: -1 (Pressed Thin) to +1 (Separated/Teeth)\n\n var map = new Dictionary();\n\n // --- Neutral ---\n map.Add(\"SIL\", PhonemePose.Neutral); // Neutral: open=0, jaw=0, form=0, shrug=0, funnel=0, puckerWiden=0, pressLip=0, puff=0\n\n // --- Shared IPA Consonants ---\n // Plosives (b, p, d, t, g, k) - Focus on closure and puff\n map.Add(\"b\", new PhonemePose(pressLip: -1.0f, cheekPuff: 0.6f)); // Pressed lips, puff\n map.Add(\"p\", new PhonemePose(pressLip: -1.0f, cheekPuff: 0.8f)); // Pressed lips, strong puff\n map.Add(\"d\", new PhonemePose(0.05f, 0.05f, pressLip: 0.0f, cheekPuff: 0.2f)); // Slight open, lips touch/nearly touch, slight puff\n map.Add(\"t\", new PhonemePose(0.05f, 0.05f, pressLip: 0.0f, cheekPuff: 0.3f)); // Slight open, lips touch/nearly touch, moderate puff\n map.Add(\"ɡ\", new PhonemePose(0.1f, 0.15f, pressLip: 0.2f, cheekPuff: 0.5f)); // Back sound, slight open, slight separation, puff\n map.Add(\"k\", new PhonemePose(0.1f, 0.15f, pressLip: 0.2f, cheekPuff: 0.4f)); // Back sound, slight open, slight separation, moderate puff\n\n // Fricatives (f, v, s, z, h, ʃ, ʒ, ð, θ) - Focus on partial closure/airflow shapes\n map.Add(\"f\", new PhonemePose(0.05f, pressLip: -0.2f, form: -0.2f, puckerWiden: -0.1f)); // Lower lip near upper teeth: Slight press, slight frown, slightly wide\n map.Add(\"v\", new PhonemePose(0.05f, pressLip: -0.1f, form: -0.2f, puckerWiden: -0.1f)); // Voiced 'f': Less press?\n map.Add(\"s\", new PhonemePose(jawOpen: 0.0f, pressLip: 0.9f, form: 0.3f, puckerWiden: -0.6f)); // Teeth close/showing, slight smile, wide\n map.Add(\"z\", new PhonemePose(jawOpen: 0.0f, pressLip: 0.8f, form: 0.2f, puckerWiden: -0.5f)); // Voiced 's': Slightly less extreme?\n map.Add(\"h\", new PhonemePose(0.2f, 0.2f, pressLip: 0.5f)); // Breathy open, lips separated\n map.Add(\"ʃ\", new PhonemePose(0.1f, funnel: 0.9f, puckerWiden: 0.6f, pressLip: 0.2f)); // 'sh': Funnel, puckered but flatter than 'oo', slight separation\n map.Add(\"ʒ\", new PhonemePose(0.1f, funnel: 0.8f, puckerWiden: 0.5f, pressLip: 0.2f)); // 'zh': Similar to 'sh'\n map.Add(\"ð\", new PhonemePose(0.05f, pressLip: 0.1f, puckerWiden: -0.2f)); // Soft 'th': Tongue tip, lips nearly touching, slightly wide\n map.Add(\"θ\", new PhonemePose(0.05f, pressLip: 0.2f, puckerWiden: -0.3f)); // Hard 'th': More airflow? More separation/width?\n\n // Nasals (m, n, ŋ) - Focus on closure or near-closure\n map.Add(\"m\", new PhonemePose(pressLip: -1.0f)); // Pressed lips\n map.Add(\"n\", new PhonemePose(0.05f, 0.05f, pressLip: 0.0f)); // Like 'd' position, lips touching\n map.Add(\"ŋ\", new PhonemePose(0.15f, 0.2f, pressLip: 0.4f)); // 'ng': Back tongue, mouth open more, lips separated\n\n // Liquids/Glides (l, ɹ, w, j) - Varied shapes\n map.Add(\"l\", new PhonemePose(0.2f, 0.2f, puckerWiden: -0.3f, pressLip: 0.6f)); // Tongue tip visible: Slightly open, slightly wide, lips separated\n map.Add(\"ɹ\", new PhonemePose(0.15f, 0.15f, funnel: 0.4f, puckerWiden: 0.2f, pressLip: 0.3f)); // 'r': Some funneling, slight pucker, separation\n map.Add(\"w\", new PhonemePose(0.1f, 0.1f, funnel: 1.0f, puckerWiden: 0.9f, pressLip: -0.3f)); // Like 'u': Strong funnel, strong pucker, lips maybe slightly pressed\n map.Add(\"j\", new PhonemePose(0.1f, 0.1f, 0.6f, 0.3f, puckerWiden: -0.8f, pressLip: 0.8f)); // 'y': Like 'i', smile, shrug, wide, teeth showing\n\n // --- Shared Consonant Clusters ---\n map.Add(\"ʤ\", new PhonemePose(0.1f, funnel: 0.8f, puckerWiden: 0.5f, pressLip: 0.2f, cheekPuff: 0.3f)); // 'j'/'dg': Target 'ʒ' shape + puff\n map.Add(\"ʧ\", new PhonemePose(0.1f, funnel: 0.9f, puckerWiden: 0.6f, pressLip: 0.2f, cheekPuff: 0.4f)); // 'ch': Target 'ʃ' shape + puff\n\n // --- Shared IPA Vowels ---\n map.Add(\"ə\", new PhonemePose(0.3f, 0.3f, pressLip: 0.5f)); // Schwa: Neutral open, lips separated\n map.Add(\"i\", new PhonemePose(0.1f, 0.1f, 0.7f, 0.4f, puckerWiden: -0.9f, pressLip: 0.9f)); // 'ee': Smile, shrug, wide, teeth showing\n map.Add(\"u\", new PhonemePose(0.15f, 0.15f, funnel: 1.0f, puckerWiden: 1.0f, pressLip: -0.2f)); // 'oo': Funnel, puckered, slight press\n map.Add(\"ɑ\", new PhonemePose(0.9f, 1.0f, pressLip: 0.8f)); // 'aa': Very open, lips separated\n map.Add(\"ɔ\", new PhonemePose(0.6f, 0.7f, funnel: 0.5f, puckerWiden: 0.3f, pressLip: 0.7f)); // 'aw': Open, some funnel, slight pucker, separated\n map.Add(\"ɛ\", new PhonemePose(0.5f, 0.5f, puckerWiden: -0.5f, pressLip: 0.7f)); // 'eh': Mid open, somewhat wide, separated\n map.Add(\"ɜ\", new PhonemePose(0.4f, 0.4f, pressLip: 0.6f)); // 'er': Mid open, neutral width, separated (blend with 'ɹ')\n map.Add(\"ɪ\", new PhonemePose(0.2f, 0.2f, 0.2f, puckerWiden: -0.6f, pressLip: 0.8f)); // 'ih': Slight open, slight smile, wide, separated\n map.Add(\"ʊ\", new PhonemePose(0.2f, 0.2f, funnel: 0.8f, puckerWiden: 0.7f, pressLip: 0.1f)); // 'uu': Slight open, funnel, pucker, near touch\n map.Add(\"ʌ\", new PhonemePose(0.6f, 0.6f, pressLip: 0.7f)); // 'uh': Mid open, neutral width, separated\n\n // --- Shared Diphthong Vowels (Targeting the end-shape's characteristics) ---\n map.Add(\"A\", new PhonemePose(0.3f, 0.3f, 0.4f, puckerWiden: -0.7f, pressLip: 0.8f)); // 'ay' (ends like ɪ/i): Mid-close, smile, wide, separated\n map.Add(\"I\", new PhonemePose(0.4f, 0.4f, 0.3f, puckerWiden: -0.6f, pressLip: 0.8f)); // 'eye' (ends like ɪ/i): Mid-open, smile, wide, separated\n map.Add(\"W\", new PhonemePose(0.3f, 0.3f, funnel: 0.9f, puckerWiden: 0.8f, pressLip: 0.0f)); // 'ow' (ends like ʊ/u): Mid-close, funnel, pucker, touching\n map.Add(\"Y\", new PhonemePose(0.3f, 0.3f, 0.2f, puckerWiden: -0.5f, pressLip: 0.8f)); // 'oy' (ends like ɪ/i): Mid-close, smile, wide, separated\n\n // --- Shared Custom Vowel ---\n map.Add(\"ᵊ\", new PhonemePose(0.1f, 0.1f, pressLip: 0.2f)); // Small schwa: Minimal open, slight separation\n\n // --- American-only ---\n map.Add(\"æ\", new PhonemePose(0.7f, 0.7f, 0.3f, puckerWiden: -0.8f, pressLip: 0.9f)); // 'ae': Open, slight smile, wide, teeth showing\n map.Add(\"O\", new PhonemePose(0.3f, 0.3f, funnel: 0.8f, puckerWiden: 0.6f, pressLip: 0.1f)); // US 'oh' (ends like ʊ/u): Mid-close, funnel, pucker, near touch\n map.Add(\"ᵻ\", new PhonemePose(0.15f, 0.15f, puckerWiden: -0.2f, pressLip: 0.6f)); // Between ə/ɪ: Slightly open, neutral-wide, separated\n map.Add(\"ɾ\", new PhonemePose(0.05f, 0.05f, pressLip: 0.3f)); // Flap 't': Very quick, slight separation\n\n // --- British-only ---\n map.Add(\"a\", new PhonemePose(0.7f, 0.7f, puckerWiden: -0.4f, pressLip: 0.8f)); // UK 'ash': Open, less wide than US 'æ', separated\n map.Add(\"Q\", new PhonemePose(0.3f, 0.3f, funnel: 0.7f, puckerWiden: 0.5f, pressLip: 0.1f)); // UK 'oh' (ends like ʊ/u): Mid-close, funnel, pucker, near touch\n map.Add(\"ɒ\", new PhonemePose(0.8f, 0.9f, funnel: 0.2f, puckerWiden: 0.1f, pressLip: 0.8f)); // 'on': Open, slight funnel, slight pucker, separated\n\n return map;\n }\n\n #endregion\n\n #region IDisposable Implementation\n\n public void Dispose() { Dispose(true); }\n\n private void Dispose(bool disposing)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( disposing )\n {\n _logger.LogDebug(\"Disposing...\");\n Stop();\n UnsubscribeFromCurrentNotifier();\n _activePhonemes.Clear();\n _currentParameterValues.Clear();\n }\n\n _disposed = true;\n _logger.LogInformation(\"Disposed\");\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioConverter.cs", "using System.Buffers.Binary;\nusing System.Runtime.CompilerServices;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Provides functionality for converting audio between different formats.\n/// \npublic static class AudioConverter\n{\n /// \n /// Calculates the required size for a buffer to hold the converted audio.\n /// \n /// The source audio buffer.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The size in bytes needed for the target buffer.\n public static int CalculateTargetBufferSize(\n ReadOnlyMemory sourceBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var framesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // If resampling is needed, adjust the frame count\n if ( sourceFormat.SampleRate != targetFormat.SampleRate )\n {\n framesCount = CalculateResampledFrameCount(framesCount, sourceFormat.SampleRate, targetFormat.SampleRate);\n }\n\n // Calculate the expected size of the target buffer\n return framesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Calculates the number of frames after resampling.\n /// \n /// Number of frames in the source buffer.\n /// Sample rate of the source audio.\n /// Target sample rate.\n /// The number of frames after resampling.\n public static int CalculateResampledFrameCount(\n int sourceFrameCount,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n return (int)Math.Ceiling(sourceFrameCount * ((double)targetSampleRate / sourceSampleRate));\n }\n\n /// \n /// Converts audio data between different formats.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the converted data to.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The number of bytes written to the target buffer.\n /// Thrown if the target buffer is too small.\n public static int Convert(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var sourceFramesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // Check if resampling is needed\n var needsResampling = sourceFormat.SampleRate != targetFormat.SampleRate;\n\n // Calculate the expected number of frames in the target buffer\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceFormat.SampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate the expected size of the target buffer\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Fast path for same format conversion with no resampling\n if ( !needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n sourceBuffer.CopyTo(targetBuffer);\n\n return sourceBuffer.Length;\n }\n\n // If only resampling is needed (same format otherwise)\n if ( needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n return ResampleDirect(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // For mono-to-stereo int16 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 32 && targetFormat.BitsPerSample == 16 )\n {\n ConvertMonoFloat32ToStereoInt16Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For stereo-to-mono conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 2 && targetFormat.Channels == 1 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertStereoInt16ToMonoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For mono-int16 to stereo-float32 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertMonoInt16ToStereoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // General case: convert through intermediate float format\n return ConvertGeneral(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount,\n needsResampling);\n }\n\n /// \n /// Specialized fast path to convert 48kHz stereo float32 audio to 16kHz mono int16 audio.\n /// This optimized method combines resampling, channel conversion, and bit depth conversion in one pass.\n /// \n /// The 48kHz stereo float32 audio buffer.\n /// The target buffer to receive the 16kHz mono int16 data.\n /// The number of bytes written to the target buffer.\n public static int ConvertStereoFloat32_48kTo_MonoInt16_16k(\n ReadOnlyMemory stereoFloat32Buffer,\n Memory targetBuffer)\n {\n var sourceFormat = new AudioFormat(2, 32, 48000);\n var targetFormat = new AudioFormat(1, 16, 16000);\n\n // Calculate number of source and target frames\n var sourceFramesCount = stereoFloat32Buffer.Length / sourceFormat.BytesPerFrame;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, 48000, 16000);\n\n // Calculate expected target size and verify buffer is large enough\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Process the conversion directly\n ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n stereoFloat32Buffer.Span,\n targetBuffer.Span,\n sourceFramesCount,\n targetFramesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Direct conversion implementation for 48kHz stereo float32 to 16kHz mono int16.\n /// Combines downsampling (48kHz to 16kHz - 3:1 ratio), stereo to mono mixing, and float32 to int16 conversion.\n /// \n private static void ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n ReadOnlySpan source,\n Span target,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // The resampling ratio is exactly 3:1 (48000/16000)\n const int resampleRatio = 3;\n\n // For optimal quality, we'll use a simple low-pass filter when downsampling\n // by averaging 3 consecutive frames before picking every 3rd one\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source frame index (center of 3-frame window)\n var sourceFrameBase = targetFrame * resampleRatio;\n\n // Initialize accumulator for filtered sample\n var monoSampleAccumulator = 0f;\n var sampleCount = 0;\n\n // Apply a simple averaging filter over a window of frames\n for ( var offset = -1; offset <= 1; offset++ )\n {\n var sourceFrameIndex = sourceFrameBase + offset;\n\n // Skip samples outside buffer boundary\n if ( sourceFrameIndex < 0 || sourceFrameIndex >= sourceFramesCount )\n {\n continue;\n }\n\n // Read left and right float32 samples and average them to mono\n var sourceByteIndex = sourceFrameIndex * 8; // 8 bytes per stereo float32 frame\n var leftSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex, 4));\n var rightSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex + 4, 4));\n\n // Average stereo to mono\n var monoSample = (leftSample + rightSample) * 0.5f;\n\n // Accumulate filtered sample\n monoSampleAccumulator += monoSample;\n sampleCount++;\n }\n\n // Average samples if we have any\n var filteredSample = sampleCount > 0 ? monoSampleAccumulator / sampleCount : 0f;\n\n // Convert float32 to int16 (with scaling and clamping)\n var int16Sample = ClampToInt16(filteredSample * 32767f);\n\n // Write to target buffer\n var targetByteIndex = targetFrame * 2; // 2 bytes per mono int16 frame\n BinaryPrimitives.WriteInt16LittleEndian(target.Slice(targetByteIndex, 2), int16Sample);\n }\n }\n\n /// \n /// Resamples audio using a higher quality filter.\n /// Uses a sinc filter for better frequency response.\n /// \n private static void ResampleWithFilter(float[] source, float[] target, uint sourceRate, uint targetRate)\n {\n // For 48kHz to 16kHz, we have a 3:1 ratio\n var ratio = (double)sourceRate / targetRate;\n\n // Use a simple windowed-sinc filter with 8 taps for anti-aliasing\n var filterSize = 8;\n\n for ( var targetIndex = 0; targetIndex < target.Length; targetIndex++ )\n {\n // Calculate the corresponding position in the source\n var sourcePos = targetIndex * ratio;\n var sourceCenterIndex = (int)sourcePos;\n\n // Apply the filter\n var sum = 0f;\n var totalWeight = 0f;\n\n for ( var tap = -filterSize / 2; tap < filterSize / 2; tap++ )\n {\n var sourceIndex = sourceCenterIndex + tap;\n\n // Skip samples outside buffer boundary\n if ( sourceIndex < 0 || sourceIndex >= source.Length )\n {\n continue;\n }\n\n // Calculate the sinc weight\n var x = sourcePos - sourceIndex;\n var weight = x == 0 ? 1.0f : (float)(Math.Sin(Math.PI * x) / (Math.PI * x));\n\n // Apply a Hann window to reduce ringing\n weight *= 0.5f * (1 + (float)Math.Cos(2 * Math.PI * (tap + filterSize / 2) / filterSize));\n\n sum += source[sourceIndex] * weight;\n totalWeight += weight;\n }\n\n // Normalize the output\n target[targetIndex] = totalWeight > 0 ? sum / totalWeight : 0f;\n }\n }\n\n /// \n /// Resamples audio data to a different sample rate.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the resampled data to.\n /// The format of the source audio.\n /// The target sample rate.\n /// The number of bytes written to the target buffer.\n public static int Resample(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n uint targetSampleRate)\n {\n // Create target format with the new sample rate but same other parameters\n var targetFormat = new AudioFormat(\n sourceFormat.Channels,\n sourceFormat.BitsPerSample,\n targetSampleRate);\n\n return Convert(sourceBuffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Resamples floating-point audio samples directly.\n /// \n /// The source float samples.\n /// The target buffer to write the resampled samples to.\n /// Number of channels in the audio.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ResampleFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort channels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n // Fast path for same sample rate\n if ( sourceSampleRate == targetSampleRate )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceSamples.Length / channels;\n }\n\n var sourceFramesCount = sourceSamples.Length / channels;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate);\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * channels )\n {\n throw new ArgumentException(\"Target buffer is too small for the resampled audio.\");\n }\n\n // Perform the resampling\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n channels,\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Converts float samples to a different format (channels, sample rate) and outputs as byte array.\n /// \n /// The source float samples.\n /// The target buffer to write the converted data to.\n /// Number of channels in the source.\n /// Source sample rate.\n /// The desired output format.\n /// The number of bytes written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetBuffer,\n ushort sourceChannels,\n uint sourceSampleRate,\n AudioFormat targetFormat)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetFormat.SampleRate;\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate expected target buffer size\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Handle resampling if needed\n ReadOnlyMemory resampledSamples;\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceChannels];\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n }\n else\n {\n resampledSamples = sourceSamples;\n }\n\n // Handle channel conversion if needed\n ReadOnlyMemory convertedSamples;\n if ( sourceChannels != targetFormat.Channels )\n {\n var convertedBuffer = new float[targetFramesCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceChannels,\n targetFormat.Channels,\n targetFramesCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return expectedTargetSize;\n }\n\n /// \n /// Converts audio format with direct access to float samples.\n /// \n /// The source float samples.\n /// The target buffer to write the converted samples to.\n /// Number of channels in the source.\n /// Number of channels for the output.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort sourceChannels,\n ushort targetChannels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetSampleRate;\n var needsChannelConversion = sourceChannels != targetChannels;\n\n // If no conversion needed, just copy\n if ( !needsResampling && !needsChannelConversion )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceFramesCount;\n }\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate)\n : sourceFramesCount;\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * targetChannels )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Optimize the common path where only channel conversion or only resampling is needed\n if ( needsResampling && !needsChannelConversion )\n {\n // Only resample\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels, // same as targetChannels in this case\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n if ( !needsResampling && needsChannelConversion )\n {\n // Only convert channels\n ConvertChannels(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n sourceFramesCount);\n\n return sourceFramesCount;\n }\n\n // If we need both resampling and channel conversion\n // First resample, then convert channels\n var resampledBuffer = needsResampling ? new float[targetFramesCount * sourceChannels] : null;\n\n if ( needsResampling )\n {\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // Then convert channels\n ConvertChannels(\n needsResampling ? resampledBuffer.AsSpan() : sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Direct resampling of audio data without format conversion.\n /// \n private static int ResampleDirect(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Convert to float for processing\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Resample the float samples\n var resampledBuffer = new float[targetFramesCount * targetFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n // Serialize back to the target format\n SampleSerializer.Serialize(resampledBuffer, targetBuffer, targetFormat.BitsPerSample);\n\n return targetFramesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Resamples floating-point audio samples.\n /// \n private static void ResampleFloatBuffer(\n ReadOnlySpan sourceBuffer,\n Span targetBuffer,\n ushort channels,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Calculate the step size for linear interpolation\n var step = (double)(sourceFramesCount - 1) / (targetFramesCount - 1);\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source position (as a floating point value)\n var sourcePos = targetFrame * step;\n\n // Get indices of the two source frames to interpolate between\n var sourceFrameLow = (int)sourcePos;\n var sourceFrameHigh = Math.Min(sourceFrameLow + 1, sourceFramesCount - 1);\n\n // Calculate interpolation factor\n var fraction = (float)(sourcePos - sourceFrameLow);\n\n // Interpolate each channel\n for ( var channel = 0; channel < channels; channel++ )\n {\n var sourceLowIndex = sourceFrameLow * channels + channel;\n var sourceHighIndex = sourceFrameHigh * channels + channel;\n var targetIndex = targetFrame * channels + channel;\n\n // Linear interpolation\n targetBuffer[targetIndex] = Lerp(\n sourceBuffer[sourceLowIndex],\n sourceBuffer[sourceHighIndex],\n fraction);\n }\n }\n }\n\n /// \n /// Linear interpolation between two values.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static float Lerp(float a, float b, float t) { return a + (b - a) * t; }\n\n /// \n /// Converts mono float32 audio to stereo int16 PCM format.\n /// \n /// The mono float32 audio buffer.\n /// The target buffer to receive the stereo int16 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoFloat32ToStereoInt16(\n ReadOnlyMemory monoFloat32Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(32, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(16, sampleRate);\n\n return Convert(monoFloat32Buffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Converts mono int16 audio to stereo float32 PCM format.\n /// \n /// The mono int16 audio buffer.\n /// The target buffer to receive the stereo float32 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoInt16ToStereoFloat32(\n ReadOnlyMemory monoInt16Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(16, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(32, sampleRate);\n\n // Use fast path for this specific conversion\n var framesCount = monoInt16Buffer.Length / sourceFormat.BytesPerFrame;\n var expectedTargetSize = framesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n ConvertMonoInt16ToStereoFloat32Direct(monoInt16Buffer, targetBuffer, framesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Optimized direct conversion from mono float32 to stereo int16.\n /// \n private static void ConvertMonoFloat32ToStereoInt16Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 4 bytes per float32\n var targetIndex = frame * 4; // 2 bytes per int16 * 2 channels\n\n // Read float32 value\n var floatValue = BinaryPrimitives.ReadSingleLittleEndian(sourceSpan.Slice(sourceIndex, 4));\n\n // Convert to int16 (with clamping)\n var int16Value = ClampToInt16(floatValue * 32767f);\n\n // Write the same value to both left and right channels\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex, 2), int16Value);\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex + 2, 2), int16Value);\n }\n }\n\n /// \n /// Optimized direct conversion from stereo int16 to mono float32.\n /// \n private static void ConvertStereoInt16ToMonoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 2 bytes per int16 * 2 channels\n var targetIndex = frame * 4; // 4 bytes per float32\n\n // Read int16 values for left and right channels\n var leftValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n var rightValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex + 2, 2));\n\n // Convert to float32 and average the channels\n var floatValue = (leftValue + rightValue) * 0.5f / 32768f;\n\n // Write to target buffer\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n }\n }\n\n /// \n /// Optimized direct conversion from mono int16 to stereo float32.\n /// \n private static void ConvertMonoInt16ToStereoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2; // 2 bytes per int16\n var targetIndex = frame * 8; // 4 bytes per float32 * 2 channels\n\n // Read int16 value\n var int16Value = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n\n // Convert to float32\n var floatValue = int16Value / 32768f;\n\n // Write the same float value to both left and right channels\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex + 4, 4), floatValue);\n }\n }\n\n /// \n /// General case conversion using intermediate float format.\n /// \n private static int ConvertGeneral(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount,\n bool needsResampling)\n {\n // Deserialize to float samples - this will give us interleaved float samples\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Perform resampling if needed\n Memory resampledSamples;\n int actualFrameCount;\n\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n actualFrameCount = targetFramesCount;\n }\n else\n {\n resampledSamples = floatSamples;\n actualFrameCount = sourceFramesCount;\n }\n\n // Convert channel configuration if needed\n Memory convertedSamples;\n\n if ( sourceFormat.Channels != targetFormat.Channels )\n {\n var convertedBuffer = new float[actualFrameCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceFormat.Channels,\n targetFormat.Channels,\n actualFrameCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n // No channel conversion needed\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return actualFrameCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Converts between different channel configurations.\n /// \n private static void ConvertChannels(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n // If source and target have the same number of channels, just copy\n if ( sourceChannels == targetChannels )\n {\n source.CopyTo(target);\n\n return;\n }\n\n // Handle specific conversions with optimized implementations\n if ( sourceChannels == 1 && targetChannels == 2 )\n {\n // Mono to stereo conversion\n ConvertMonoToStereo(source, target, framesCount);\n }\n else if ( sourceChannels == 2 && targetChannels == 1 )\n {\n // Stereo to mono conversion\n ConvertStereoToMono(source, target, framesCount);\n }\n else\n {\n // More general conversion implementation\n ConvertChannelsGeneral(source, target, sourceChannels, targetChannels, framesCount);\n }\n }\n\n /// \n /// Converts mono audio to stereo by duplicating each sample.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertMonoToStereo(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceSample = source[frame];\n var targetIndex = frame * 2;\n\n target[targetIndex] = sourceSample; // Left channel\n target[targetIndex + 1] = sourceSample; // Right channel\n }\n }\n\n /// \n /// Converts stereo audio to mono by averaging the channels.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertStereoToMono(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2;\n var leftSample = source[sourceIndex];\n var rightSample = source[sourceIndex + 1];\n\n target[frame] = (leftSample + rightSample) * 0.5f; // Average the channels\n }\n }\n\n /// \n /// General method for converting between different channel configurations.\n /// \n private static void ConvertChannelsGeneral(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n ConvertChannelsChunk(source, target, sourceChannels, targetChannels, 0, framesCount);\n }\n\n /// \n /// Converts a chunk of frames between different channel configurations.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertChannelsChunk(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int startFrame,\n int endFrame)\n {\n for ( var frame = startFrame; frame < endFrame; frame++ )\n {\n var sourceFrameOffset = frame * sourceChannels;\n var targetFrameOffset = frame * targetChannels;\n\n // Find the minimum of source and target channels\n var minChannels = Math.Min(sourceChannels, targetChannels);\n\n // Copy the available channels\n for ( var channel = 0; channel < minChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + channel];\n }\n\n // If target has more channels than source, duplicate the last channel\n for ( var channel = minChannels; channel < targetChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + (minChannels - 1)];\n }\n }\n }\n\n /// \n /// Clamps a float value to the range of a 16-bit integer.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static short ClampToInt16(float value)\n {\n if ( value > 32767f )\n {\n return 32767;\n }\n\n if ( value < -32768f )\n {\n return -32768;\n }\n\n return (short)value;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/RouletteWheel.Transform.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic partial class RouletteWheel\n{\n /// \n /// Defines how the wheel position is tracked and updated during window resizing.\n /// \n public enum PositionMode\n {\n /// \n /// Position is fixed in absolute pixels and won't change during resizing.\n /// \n Absolute,\n\n /// \n /// Position is based on viewport percentages and will scale with resizing.\n /// \n Percentage,\n\n /// \n /// Position is based on viewport anchors and will adapt during resizing.\n /// \n Anchored\n }\n\n /// \n /// Represents anchor points within the viewport for positioning the wheel.\n /// \n public enum ViewportAnchor\n {\n Center,\n\n TopLeft,\n\n TopCenter,\n\n TopRight,\n\n MiddleLeft,\n\n MiddleRight,\n\n BottomLeft,\n\n BottomCenter,\n\n BottomRight\n }\n\n private Vector2 _anchorOffset = Vector2.Zero;\n\n private ViewportAnchor _currentAnchor = ViewportAnchor.Center;\n\n private PositionMode _positionMode = PositionMode.Absolute;\n\n private Vector2 _positionPercentage = new(0.5f, 0.5f);\n\n /// \n /// Gets the current radius of the wheel in pixels.\n /// \n public float Radius => Diameter / 2;\n\n /// \n /// Gets the current diameter of the wheel in pixels.\n /// \n public float Diameter => Math.Min(_viewportWidth, _viewportHeight) * _wheelSize * OUTER_RADIUS_FACTOR;\n\n /// \n /// Gets or sets the rotation of the wheel in radians.\n /// \n public float Rotation { get; private set; } = 0f;\n\n /// \n /// Gets or sets the rotation of the wheel in degrees.\n /// \n public float RotationDegrees => Rotation * 180 / MathF.PI;\n\n public void Resize()\n {\n _viewportWidth = _config.CurrentValue.Width;\n _viewportHeight = _config.CurrentValue.Height;\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n\n switch ( _positionMode )\n {\n case PositionMode.Anchored:\n UpdatePositionFromAnchor();\n\n break;\n case PositionMode.Percentage:\n UpdatePositionFromPercentage();\n\n break;\n case PositionMode.Absolute:\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n /// \n /// Rotates the wheel by the specified angle in radians.\n /// \n public void RotateBy(float angleRadians) { Rotation += angleRadians; }\n\n /// \n /// Rotates the wheel by the specified angle in radians.\n /// \n public void RotateByDegrees(float angleDegrees) { Rotation += angleDegrees * MathF.PI / 180; }\n\n /// \n /// Sets the diameter of the wheel in pixels.\n /// \n public void SetDiameter(float diameter)\n {\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n _wheelSize = Math.Clamp(diameter / minDimension, 0.1f, 1.0f);\n }\n\n /// \n /// Sets the radius of the wheel in pixels.\n /// \n public void SetRadius(float radius) { SetDiameter(radius * 2); }\n\n /// \n /// Sets the wheel size as a percentage of the viewport (0.0 to 1.0).\n /// \n /// Value between 0.0 and 1.0\n public void SetSizePercentage(float percentage) { _wheelSize = Math.Clamp(percentage, 0.1f, 1.0f); }\n\n /// \n /// Scales the wheel size by the specified factor relative to its current size.\n /// \n public void Scale(float factor) { _wheelSize = Math.Clamp(_wheelSize * factor, 0.1f, 1.0f); }\n\n /// \n /// Translates the wheel by the specified amount.\n /// \n public void Translate(float deltaX, float deltaY)\n {\n _positionMode = PositionMode.Absolute;\n _position = new Vector2(_position.X + deltaX, _position.Y + deltaY);\n }\n\n /// \n /// Translates the wheel by the specified vector.\n /// \n public void Translate(Vector2 delta)\n {\n _positionMode = PositionMode.Absolute;\n _position += delta;\n }\n\n /// \n /// Sets the position using viewport percentages (0.0 to 1.0 for each axis)\n /// \n public void PositionByPercentage(float xPercent, float yPercent)\n {\n _positionMode = PositionMode.Percentage;\n _positionPercentage = new Vector2(\n Math.Clamp(xPercent, 0, 1),\n Math.Clamp(yPercent, 0, 1)\n );\n\n UpdatePositionFromPercentage();\n }\n\n /// \n /// Updates position based on viewport percentages\n /// \n private void UpdatePositionFromPercentage()\n {\n _position = new Vector2(\n _viewportWidth * _positionPercentage.X,\n _viewportHeight * _positionPercentage.Y\n );\n }\n\n /// \n /// Sets the position in absolute pixels. This will not adjust with window resizing.\n /// \n public void SetAbsolutePosition(float x, float y)\n {\n _positionMode = PositionMode.Absolute;\n _position = new Vector2(x, y);\n }\n\n /// \n /// Positions the wheel at the specified viewport anchor with an optional offset.\n /// \n public void PositionAt(ViewportAnchor anchor, Vector2 offset = default)\n {\n _positionMode = PositionMode.Anchored;\n _currentAnchor = anchor;\n _anchorOffset = offset;\n\n UpdatePositionFromAnchor();\n }\n\n /// \n /// Updates position based on the current anchor and offset\n /// \n private void UpdatePositionFromAnchor()\n {\n float x = 0,\n y = 0;\n\n switch ( _currentAnchor )\n {\n case ViewportAnchor.Center:\n x = _viewportWidth / 2.0f;\n y = _viewportHeight / 2.0f;\n\n break;\n case ViewportAnchor.TopLeft:\n x = Radius;\n y = Radius;\n\n break;\n case ViewportAnchor.TopCenter:\n x = _viewportWidth / 2.0f;\n y = Radius;\n\n break;\n case ViewportAnchor.TopRight:\n x = _viewportWidth - Radius;\n y = Radius;\n\n break;\n case ViewportAnchor.MiddleLeft:\n x = Radius;\n y = _viewportHeight / 2.0f;\n\n break;\n case ViewportAnchor.MiddleRight:\n x = _viewportWidth - Radius;\n y = _viewportHeight / 2.0f;\n\n break;\n case ViewportAnchor.BottomLeft:\n x = Radius;\n y = _viewportHeight - Radius;\n\n break;\n case ViewportAnchor.BottomCenter:\n x = _viewportWidth / 2.0f;\n y = _viewportHeight - Radius;\n\n break;\n case ViewportAnchor.BottomRight:\n x = _viewportWidth - Radius;\n y = _viewportHeight - Radius;\n\n break;\n }\n\n _position = new Vector2(x + _anchorOffset.X, y + _anchorOffset.Y);\n }\n\n /// \n /// Centers the wheel in the viewport.\n /// \n public void CenterInViewport() { _position = new Vector2(_viewportWidth / 2.0f, _viewportHeight / 2.0f); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismModelSettingJson.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class CubismModelSettingJson\n{\n // JSON keys\n public const string Version = \"Version\";\n\n public const string FileReferences = \"FileReferences\";\n\n public const string Groups = \"Groups\";\n\n public const string Layout = \"Layout\";\n\n public const string HitAreas = \"HitAreas\";\n\n public const string Moc = \"Moc\";\n\n public const string Textures = \"Textures\";\n\n public const string Physics = \"Physics\";\n\n public const string DisplayInfo = \"DisplayInfo\";\n\n public const string Pose = \"Pose\";\n\n public const string Expressions = \"Expressions\";\n\n public const string Motions = \"Motions\";\n\n public const string UserData = \"UserData\";\n\n public const string Name = \"Name\";\n\n public const string FilePath = \"File\";\n\n public const string Id = \"Id\";\n\n public const string Ids = \"Ids\";\n\n public const string Target = \"Target\";\n\n // Motions\n public const string Idle = \"Idle\";\n\n public const string TapBody = \"TapBody\";\n\n public const string PinchIn = \"PinchIn\";\n\n public const string PinchOut = \"PinchOut\";\n\n public const string Shake = \"Shake\";\n\n public const string FlickHead = \"FlickHead\";\n\n public const string Parameter = \"Parameter\";\n\n public const string SoundPath = \"Sound\";\n\n public const string FadeInTime = \"FadeInTime\";\n\n public const string FadeOutTime = \"FadeOutTime\";\n\n // Layout\n public const string CenterX = \"CenterX\";\n\n public const string CenterY = \"CenterY\";\n\n public const string X = \"X\";\n\n public const string Y = \"Y\";\n\n public const string Width = \"Width\";\n\n public const string Height = \"Height\";\n\n public const string LipSync = \"LipSync\";\n\n public const string EyeBlink = \"EyeBlink\";\n\n public const string InitParameter = \"init_param\";\n\n public const string InitPartsVisible = \"init_parts_visible\";\n\n public const string Val = \"val\";\n\n public static bool GetLayoutMap(this ModelSettingObj obj, Dictionary outLayoutMap)\n {\n var node = obj.Layout;\n if ( node == null )\n {\n return false;\n }\n\n var ret = false;\n foreach ( var item in node )\n {\n if ( outLayoutMap.ContainsKey(item.Key) )\n {\n outLayoutMap[item.Key] = item.Value;\n }\n else\n {\n outLayoutMap.Add(item.Key, item.Value);\n }\n\n ret = true;\n }\n\n return ret;\n }\n\n public static bool IsExistEyeBlinkParameters(this ModelSettingObj obj)\n {\n var node = obj.Groups;\n if ( node == null )\n {\n return false;\n }\n\n foreach ( var item in node )\n {\n if ( item.Name == EyeBlink )\n {\n return true;\n }\n }\n\n return false;\n }\n\n public static bool IsExistLipSyncParameters(this ModelSettingObj obj)\n {\n var node = obj.Groups;\n if ( node == null )\n {\n return false;\n }\n\n foreach ( var item in node )\n {\n if ( item.Name == LipSync )\n {\n return true;\n }\n }\n\n return false;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SampleSerializer.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Serializer for converting float samples to and from PCM byte buffers.\n/// \n/// \n/// For now, this class only supports 8, 16, 24, 32 and 64 bits per sample.\n/// \npublic static class SampleSerializer\n{\n /// \n /// Deserialize the PCM byte buffer into a new float samples.\n /// \n /// \n public static Memory Deserialize(ReadOnlyMemory buffer, ushort bitsPerSample)\n {\n var floatBuffer = new float[buffer.Length / (bitsPerSample / 8)];\n Deserialize(buffer, floatBuffer, bitsPerSample);\n\n return floatBuffer.AsMemory();\n }\n\n /// \n /// Serializes the float samples into a PCM byte buffer.\n /// \n /// \n public static Memory Serialize(ReadOnlyMemory samples, ushort bitsPerSample)\n {\n // Transform to long as we might overflow the int because of the multiplications (even if we cast to int later)\n var memoryBufferLength = (long)samples.Length * bitsPerSample / 8;\n\n var buffer = new byte[(int)memoryBufferLength];\n Serialize(samples, buffer, bitsPerSample);\n\n return buffer.AsMemory();\n }\n\n /// \n /// Serializes the float samples into a PCM byte buffer.\n /// \n public static void Serialize(ReadOnlyMemory samples, Memory buffer, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n var totalSamples = samples.Length;\n var totalBytes = totalSamples * bytesPerSample;\n\n if ( buffer.Length < totalBytes )\n {\n throw new ArgumentException(\"Buffer too small to hold the serialized data.\");\n }\n\n var samplesSpan = samples.Span;\n var bufferSpan = buffer.Span;\n\n var sampleIndex = 0;\n var bufferIndex = 0;\n\n while ( sampleIndex < totalSamples )\n {\n var sampleValue = samplesSpan[sampleIndex];\n WriteSample(bufferSpan, bufferIndex, sampleValue, bitsPerSample);\n bufferIndex += bytesPerSample;\n sampleIndex++;\n }\n }\n\n /// \n /// Deserializes the PCM byte buffer into float samples.\n /// \n public static void Deserialize(ReadOnlyMemory buffer, Memory samples, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n var totalSamples = buffer.Length / bytesPerSample;\n\n if ( samples.Length < totalSamples )\n {\n throw new ArgumentException(\"Samples buffer is too small to hold the deserialized data.\");\n }\n\n var bufferSpan = buffer.Span;\n var samplesSpan = samples.Span;\n\n var sampleIndex = 0;\n var bufferIndex = 0;\n\n while ( bufferIndex < bufferSpan.Length )\n {\n var sampleValue = ReadSample(bufferSpan, ref bufferIndex, bitsPerSample);\n samplesSpan[sampleIndex++] = sampleValue;\n // bufferIndex is already incremented inside ReadSample\n }\n }\n\n /// \n /// Reads a single sample from the byte span, considering the bit index and sample bit depth.\n /// \n internal static float ReadSample(ReadOnlySpan span, ref int index, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n\n float sampleValue;\n\n switch ( bitsPerSample )\n {\n case 8:\n var sampleByte = span[index];\n sampleValue = sampleByte / 127.5f - 1.0f;\n\n break;\n\n case 16:\n var sampleShort = BinaryPrimitives.ReadInt16LittleEndian(span.Slice(index, 2));\n sampleValue = sampleShort / 32768f;\n\n break;\n\n case 24:\n var sample24Bit = ReadInt24LittleEndian(span.Slice(index, 3));\n sampleValue = sample24Bit / 8388608f;\n\n break;\n\n case 32:\n var sampleInt = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(index, 4));\n sampleValue = sampleInt / 2147483648f;\n\n break;\n\n case 64:\n var sampleLong = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(index, 8));\n sampleValue = sampleLong / 9223372036854775808f;\n\n break;\n\n default:\n throw new NotSupportedException($\"Bits per sample {bitsPerSample} is not supported.\");\n }\n\n index += bytesPerSample;\n\n return sampleValue;\n }\n\n /// \n /// Writes a single sample into the byte span at the specified index.\n /// \n internal static void WriteSample(Span span, int index, float sampleValue, ushort bitsPerSample)\n {\n switch ( bitsPerSample )\n {\n case 8:\n var sampleByte = (byte)((sampleValue + 1.0f) * 127.5f);\n span[index] = sampleByte;\n\n break;\n\n case 16:\n var sampleShort = (short)(sampleValue * 32767f);\n BinaryPrimitives.WriteInt16LittleEndian(span.Slice(index, 2), sampleShort);\n\n break;\n\n case 24:\n var sample24Bit = (int)(sampleValue * 8388607f);\n WriteInt24LittleEndian(span.Slice(index, 3), sample24Bit);\n\n break;\n\n case 32:\n var sampleInt = (int)(sampleValue * 2147483647f);\n BinaryPrimitives.WriteInt32LittleEndian(span.Slice(index, 4), sampleInt);\n\n break;\n\n case 64:\n var sampleLong = (long)(sampleValue * 9223372036854775807f);\n BinaryPrimitives.WriteInt64LittleEndian(span.Slice(index, 8), sampleLong);\n\n break;\n\n default:\n throw new NotSupportedException($\"Bits per sample {bitsPerSample} is not supported.\");\n }\n }\n\n /// \n /// Reads a 24-bit integer from a byte span in little-endian order.\n /// \n private static int ReadInt24LittleEndian(ReadOnlySpan span)\n {\n int b0 = span[0];\n int b1 = span[1];\n int b2 = span[2];\n var sample = (b2 << 16) | (b1 << 8) | b0;\n\n // Sign-extend to 32 bits if necessary\n if ( (sample & 0x800000) != 0 )\n {\n sample |= unchecked((int)0xFF000000);\n }\n\n return sample;\n }\n\n /// \n /// Writes a 24-bit integer to a byte span in little-endian order.\n /// \n private static void WriteInt24LittleEndian(Span span, int value)\n {\n span[0] = (byte)(value & 0xFF);\n span[1] = (byte)((value >> 8) & 0xFF);\n span[2] = (byte)((value >> 16) & 0xFF);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismShader_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal class CubismShader_OpenGLES2(OpenGLApi gl)\n{\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_HIGH = \"highp\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_MID = \"mediump\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_LOW = \"lowp\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION = CSM_FRAGMENT_SHADER_FP_PRECISION_HIGH;\n\n private const string GLES2 = \"#version 100\\n\";\n\n private const string GLES2C = GLES2 + \"precision \" + CSM_FRAGMENT_SHADER_FP_PRECISION + \" float;\";\n\n private const string Normal = \"#version 120\\n\";\n\n private const string Tegra = \"#version 100\\n\" +\n \"#extension GL_NV_shader_framebuffer_fetch : enable\\n\" +\n \"precision \" + CSM_FRAGMENT_SHADER_FP_PRECISION + \" float;\";\n\n // SetupMask\n public const string VertShaderSrcSetupMask_ES2 =\n GLES2 + VertShaderSrcSetupMask_Base;\n\n public const string VertShaderSrcSetupMask_Normal =\n Normal + VertShaderSrcSetupMask_Base;\n\n private const string VertShaderSrcSetupMask_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nvarying vec4 v_myPos;\nuniform mat4 u_clipMatrix;\nvoid main()\n{\ngl_Position = u_clipMatrix * a_position;\nv_myPos = u_clipMatrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n public const string FragShaderSrcSetupMask_ES2 = GLES2C + FragShaderSrcSetupMask_Base;\n\n public const string FragShaderSrcSetupMask_Normal = Normal + FragShaderSrcSetupMask_Base;\n\n private const string FragShaderSrcSetupMask_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_myPos;\nuniform sampler2D s_texture0;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nvoid main()\n{\nfloat isInside = \n step(u_baseColor.x, v_myPos.x/v_myPos.w)\n* step(u_baseColor.y, v_myPos.y/v_myPos.w)\n* step(v_myPos.x/v_myPos.w, u_baseColor.z)\n* step(v_myPos.y/v_myPos.w, u_baseColor.w);\ngl_FragColor = u_channelFlag * texture2D(s_texture0 , v_texCoord).a * isInside;\n}\";\n\n public const string FragShaderSrcSetupMaskTegra =\n Tegra + FragShaderSrcSetupMask_Base;\n\n //----- バーテックスシェーダプログラム -----\n // Normal & Add & Mult 共通\n public const string VertShaderSrc_ES2 = GLES2 + VertShaderSrc_Base;\n\n public const string VertShaderSrc_Normal = Normal + VertShaderSrc_Base;\n\n private const string VertShaderSrc_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nuniform mat4 u_matrix;\nvoid main()\n{\ngl_Position = u_matrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用)\n public const string VertShaderSrcMasked_ES2 = GLES2 + VertShaderSrcMasked_Base;\n\n public const string VertShaderSrcMasked_Normal = Normal + VertShaderSrcMasked_Base;\n\n private const string VertShaderSrcMasked_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform mat4 u_matrix;\nuniform mat4 u_clipMatrix;\nvoid main()\n{\ngl_Position = u_matrix * a_position;\nv_clipPos = u_clipMatrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n //----- フラグメントシェーダプログラム -----\n // Normal & Add & Mult 共通\n public const string FragShaderSrc_ES2 = GLES2C + FragShaderSrc_Base;\n\n public const string FragShaderSrc_Normal = Normal + FragShaderSrc_Base;\n\n public const string FragShaderSrc_Base =\n @\"varying vec2 v_texCoord;\nuniform sampler2D s_texture0;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 color = texColor * u_baseColor;\ngl_FragColor = vec4(color.rgb * color.a, color.a);\n}\";\n\n public const string FragShaderSrcTegra = Tegra + FragShaderSrc_Base;\n\n // Normal & Add & Mult 共通 (PremultipliedAlpha)\n public const string FragShaderSrcPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcPremultipliedAlpha_Base;\n\n public const string FragShaderSrcPremultipliedAlpha_Normal = Normal + FragShaderSrcPremultipliedAlpha_Base;\n\n public const string FragShaderSrcPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\nuniform sampler2D s_texture0;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\ngl_FragColor = texColor * u_baseColor;\n}\";\n\n public const string FragShaderSrcPremultipliedAlphaTegra = Tegra + FragShaderSrcPremultipliedAlpha_Base;\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用)\n public const string FragShaderSrcMask_ES2 = GLES2C + FragShaderSrcMask_Base;\n\n public const string FragShaderSrcMask_Normal = Normal + FragShaderSrcMask_Base;\n\n public const string FragShaderSrcMask_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\ncol_formask.rgb = col_formask.rgb * col_formask.a ;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * maskVal;\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskTegra = Tegra + FragShaderSrcMask_Base;\n\n // Normal & Add & Mult 共通(クリッピングされて反転使用の描画用)\n public const string FragShaderSrcMaskInverted_ES2 = GLES2C + FragShaderSrcMaskInverted_Base;\n\n public const string FragShaderSrcMaskInverted_Normal = Normal + FragShaderSrcMaskInverted_Base;\n\n public const string FragShaderSrcMaskInverted_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\ncol_formask.rgb = col_formask.rgb * col_formask.a ;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * (1.0 - maskVal);\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskInvertedTegra = Tegra + FragShaderSrcMaskInverted_Base;\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用、PremultipliedAlphaの場合)\n public const string FragShaderSrcMaskPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskPremultipliedAlpha_Normal = Normal + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\n varying vec4 v_clipPos;\n uniform sampler2D s_texture0;\n uniform sampler2D s_texture1;\n uniform vec4 u_channelFlag;\n uniform vec4 u_baseColor;\n uniform vec4 u_multiplyColor;\n uniform vec4 u_screenColor;\n void main()\n {\n vec4 texColor = texture2D(s_texture0 , v_texCoord);\n texColor.rgb = texColor.rgb * u_multiplyColor.rgb;\n texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\n vec4 col_formask = texColor * u_baseColor;\n vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\n float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\n col_formask = col_formask * maskVal;\n gl_FragColor = col_formask;\n }\";\n\n public const string FragShaderSrcMaskPremultipliedAlphaTegra = Tegra + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n // Normal & Add & Mult 共通(クリッピングされて反転使用の描画用、PremultipliedAlphaの場合)\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_Normal = Normal + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * (1.0 - maskVal);\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlphaTegra = Tegra + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const int ShaderCount = 19; // シェーダの数 = マスク生成用 + (通常 + 加算 + 乗算) * (マスク無 + マスク有 + マスク有反転 + マスク無の乗算済アルファ対応版 + マスク有の乗算済アルファ対応版 + マスク有反転の乗算済アルファ対応版)\n\n /// \n /// ロードしたシェーダプログラムを保持する変数\n /// \n private readonly List _shaderSets = [];\n\n /// \n /// Tegra対応.拡張方式で描画\n /// \n internal bool s_extMode;\n\n /// \n /// 拡張方式のPA設定用の変数\n /// \n internal bool s_extPAMode;\n\n /// \n /// シェーダプログラムの一連のセットアップを実行する\n /// \n /// レンダラのインスタンス\n /// GPUのテクスチャID\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 不透明度\n /// カラーブレンディングのタイプ\n /// ベースカラー\n /// \n /// \n /// 乗算済みアルファかどうか\n /// Model-View-Projection行列\n /// マスクを反転して使用するフラグ\n internal void SetupShaderProgramForDraw(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index)\n {\n if ( _shaderSets.Count == 0 )\n {\n GenerateShaders();\n }\n\n // Blending\n int SRC_COLOR;\n int DST_COLOR;\n int SRC_ALPHA;\n int DST_ALPHA;\n\n // _shaderSets用のオフセット計算\n var masked = renderer.ClippingContextBufferForDraw != null; // この描画オブジェクトはマスク対象か\n var invertedMask = model.GetDrawableInvertedMask(index);\n var isPremultipliedAlpha = renderer.IsPremultipliedAlpha;\n var offset = (masked ? invertedMask ? 2 : 1 : 0) + (isPremultipliedAlpha ? 3 : 0);\n\n CubismShaderSet shaderSet;\n switch ( model.GetDrawableBlendMode(index) )\n {\n case CubismBlendMode.Normal:\n default:\n shaderSet = _shaderSets[(int)ShaderNames.Normal + offset];\n SRC_COLOR = gl.GL_ONE;\n DST_COLOR = gl.GL_ONE_MINUS_SRC_ALPHA;\n SRC_ALPHA = gl.GL_ONE;\n DST_ALPHA = gl.GL_ONE_MINUS_SRC_ALPHA;\n\n break;\n\n case CubismBlendMode.Additive:\n shaderSet = _shaderSets[(int)ShaderNames.Add + offset];\n SRC_COLOR = gl.GL_ONE;\n DST_COLOR = gl.GL_ONE;\n SRC_ALPHA = gl.GL_ZERO;\n DST_ALPHA = gl.GL_ONE;\n\n break;\n\n case CubismBlendMode.Multiplicative:\n shaderSet = _shaderSets[(int)ShaderNames.Mult + offset];\n SRC_COLOR = gl.GL_DST_COLOR;\n DST_COLOR = gl.GL_ONE_MINUS_SRC_ALPHA;\n SRC_ALPHA = gl.GL_ZERO;\n DST_ALPHA = gl.GL_ONE;\n\n break;\n }\n\n gl.UseProgram(shaderSet.ShaderProgram);\n\n // 頂点配列の設定\n SetupTexture(renderer, model, index, shaderSet);\n\n // テクスチャ頂点の設定\n SetVertexAttributes(shaderSet);\n\n if ( masked )\n {\n gl.ActiveTexture(gl.GL_TEXTURE1);\n\n var draw = renderer.ClippingContextBufferForDraw!;\n\n // frameBufferに書かれたテクスチャ\n var tex = renderer.GetMaskBuffer(draw.BufferIndex).ColorBuffer;\n\n gl.BindTexture(gl.GL_TEXTURE_2D, tex);\n gl.Uniform1i(shaderSet.SamplerTexture1Location, 1);\n\n // View座標をClippingContextの座標に変換するための行列を設定\n gl.UniformMatrix4fv(shaderSet.UniformClipMatrixLocation, 1, false, draw.MatrixForDraw.Tr);\n\n // 使用するカラーチャンネルを設定\n SetColorChannelUniformVariables(shaderSet, renderer.ClippingContextBufferForDraw!);\n }\n\n //座標変換\n gl.UniformMatrix4fv(shaderSet.UniformMatrixLocation, 1, false, renderer.GetMvpMatrix().Tr);\n\n // ユニフォーム変数設定\n var baseColor = renderer.GetModelColorWithOpacity(model.GetDrawableOpacity(index));\n var multiplyColor = model.GetMultiplyColor(index);\n var screenColor = model.GetScreenColor(index);\n SetColorUniformVariables(shaderSet, baseColor, multiplyColor, screenColor);\n\n gl.BlendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);\n }\n\n internal void SetupShaderProgramForMask(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index)\n {\n if ( _shaderSets.Count == 0 )\n {\n GenerateShaders();\n }\n\n // Blending\n var SRC_COLOR = gl.GL_ZERO;\n var DST_COLOR = gl.GL_ONE_MINUS_SRC_COLOR;\n var SRC_ALPHA = gl.GL_ZERO;\n var DST_ALPHA = gl.GL_ONE_MINUS_SRC_ALPHA;\n\n var shaderSet = _shaderSets[(int)ShaderNames.SetupMask];\n gl.UseProgram(shaderSet.ShaderProgram);\n\n var draw = renderer.ClippingContextBufferForMask!;\n\n //テクスチャ設定\n SetupTexture(renderer, model, index, shaderSet);\n\n // 頂点配列の設定\n SetVertexAttributes(shaderSet);\n\n // 使用するカラーチャンネルを設定\n SetColorChannelUniformVariables(shaderSet, draw);\n\n gl.UniformMatrix4fv(shaderSet.UniformClipMatrixLocation, 1, false, draw.MatrixForMask.Tr);\n\n var rect = draw.LayoutBounds;\n CubismTextureColor baseColor = new(rect.X * 2.0f - 1.0f, rect.Y * 2.0f - 1.0f, rect.GetRight() * 2.0f - 1.0f, rect.GetBottom() * 2.0f - 1.0f);\n var multiplyColor = model.GetMultiplyColor(index);\n var screenColor = model.GetScreenColor(index);\n SetColorUniformVariables(shaderSet, baseColor, multiplyColor, screenColor);\n\n gl.BlendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);\n }\n\n /// \n /// シェーダプログラムを解放する\n /// \n internal void ReleaseShaderProgram()\n {\n for ( var i = 0; i < _shaderSets.Count; i++ )\n {\n if ( _shaderSets[i].ShaderProgram != 0 )\n {\n gl.DeleteProgram(_shaderSets[i].ShaderProgram);\n _shaderSets[i].ShaderProgram = 0;\n }\n }\n }\n\n /// \n /// シェーダプログラムを初期化する\n /// \n internal void GenerateShaders()\n {\n for ( var i = 0; i < ShaderCount; i++ )\n {\n _shaderSets.Add(new CubismShaderSet());\n }\n\n if ( gl.IsES2 )\n {\n if ( s_extMode )\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_ES2, FragShaderSrcSetupMaskTegra);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcTegra);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskTegra);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedTegra);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcPremultipliedAlphaTegra);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskPremultipliedAlphaTegra);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedPremultipliedAlphaTegra);\n }\n else\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_ES2, FragShaderSrcSetupMask_ES2);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrc_ES2);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMask_ES2);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInverted_ES2);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcPremultipliedAlpha_ES2);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskPremultipliedAlpha_ES2);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedPremultipliedAlpha_ES2);\n }\n\n // 加算も通常と同じシェーダーを利用する\n _shaderSets[7].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[8].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[9].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[10].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[11].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[12].ShaderProgram = _shaderSets[6].ShaderProgram;\n\n // 乗算も通常と同じシェーダーを利用する\n _shaderSets[13].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[14].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[15].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[16].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[17].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[18].ShaderProgram = _shaderSets[6].ShaderProgram;\n }\n else\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_Normal, FragShaderSrcSetupMask_Normal);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_Normal, FragShaderSrc_Normal);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMask_Normal);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskInverted_Normal);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_Normal, FragShaderSrcPremultipliedAlpha_Normal);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskPremultipliedAlpha_Normal);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskInvertedPremultipliedAlpha_Normal);\n\n // 加算も通常と同じシェーダーを利用する\n _shaderSets[7].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[8].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[9].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[10].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[11].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[12].ShaderProgram = _shaderSets[6].ShaderProgram;\n\n // 乗算も通常と同じシェーダーを利用する\n _shaderSets[13].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[14].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[15].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[16].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[17].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[18].ShaderProgram = _shaderSets[6].ShaderProgram;\n }\n\n // SetupMask\n _shaderSets[0].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[0].ShaderProgram, \"a_position\");\n _shaderSets[0].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[0].ShaderProgram, \"a_texCoord\");\n _shaderSets[0].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"s_texture0\");\n _shaderSets[0].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[0].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_channelFlag\");\n _shaderSets[0].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_baseColor\");\n _shaderSets[0].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[0].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_screenColor\");\n\n // 通常\n _shaderSets[1].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[1].ShaderProgram, \"a_position\");\n _shaderSets[1].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[1].ShaderProgram, \"a_texCoord\");\n _shaderSets[1].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"s_texture0\");\n _shaderSets[1].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_matrix\");\n _shaderSets[1].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_baseColor\");\n _shaderSets[1].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[1].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング)\n _shaderSets[2].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[2].ShaderProgram, \"a_position\");\n _shaderSets[2].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[2].ShaderProgram, \"a_texCoord\");\n _shaderSets[2].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"s_texture0\");\n _shaderSets[2].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"s_texture1\");\n _shaderSets[2].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_matrix\");\n _shaderSets[2].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[2].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_channelFlag\");\n _shaderSets[2].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_baseColor\");\n _shaderSets[2].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[2].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング・反転)\n _shaderSets[3].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[3].ShaderProgram, \"a_position\");\n _shaderSets[3].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[3].ShaderProgram, \"a_texCoord\");\n _shaderSets[3].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"s_texture0\");\n _shaderSets[3].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"s_texture1\");\n _shaderSets[3].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_matrix\");\n _shaderSets[3].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[3].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_channelFlag\");\n _shaderSets[3].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_baseColor\");\n _shaderSets[3].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[3].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_screenColor\");\n\n // 通常(PremultipliedAlpha)\n _shaderSets[4].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[4].ShaderProgram, \"a_position\");\n _shaderSets[4].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[4].ShaderProgram, \"a_texCoord\");\n _shaderSets[4].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"s_texture0\");\n _shaderSets[4].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_matrix\");\n _shaderSets[4].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_baseColor\");\n _shaderSets[4].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[4].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング、PremultipliedAlpha)\n _shaderSets[5].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[5].ShaderProgram, \"a_position\");\n _shaderSets[5].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[5].ShaderProgram, \"a_texCoord\");\n _shaderSets[5].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"s_texture0\");\n _shaderSets[5].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"s_texture1\");\n _shaderSets[5].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_matrix\");\n _shaderSets[5].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[5].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_channelFlag\");\n _shaderSets[5].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_baseColor\");\n _shaderSets[5].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[5].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[6].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[6].ShaderProgram, \"a_position\");\n _shaderSets[6].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[6].ShaderProgram, \"a_texCoord\");\n _shaderSets[6].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"s_texture0\");\n _shaderSets[6].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"s_texture1\");\n _shaderSets[6].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_matrix\");\n _shaderSets[6].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[6].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_channelFlag\");\n _shaderSets[6].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_baseColor\");\n _shaderSets[6].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[6].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_screenColor\");\n\n // 加算\n _shaderSets[7].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[7].ShaderProgram, \"a_position\");\n _shaderSets[7].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[7].ShaderProgram, \"a_texCoord\");\n _shaderSets[7].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"s_texture0\");\n _shaderSets[7].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_matrix\");\n _shaderSets[7].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_baseColor\");\n _shaderSets[7].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[7].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング)\n _shaderSets[8].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[8].ShaderProgram, \"a_position\");\n _shaderSets[8].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[8].ShaderProgram, \"a_texCoord\");\n _shaderSets[8].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"s_texture0\");\n _shaderSets[8].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"s_texture1\");\n _shaderSets[8].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_matrix\");\n _shaderSets[8].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[8].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_channelFlag\");\n _shaderSets[8].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_baseColor\");\n _shaderSets[8].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[8].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング・反転)\n _shaderSets[9].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[9].ShaderProgram, \"a_position\");\n _shaderSets[9].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[9].ShaderProgram, \"a_texCoord\");\n _shaderSets[9].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"s_texture0\");\n _shaderSets[9].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"s_texture1\");\n _shaderSets[9].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_matrix\");\n _shaderSets[9].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[9].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_channelFlag\");\n _shaderSets[9].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_baseColor\");\n _shaderSets[9].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[9].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_screenColor\");\n\n // 加算(PremultipliedAlpha)\n _shaderSets[10].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[10].ShaderProgram, \"a_position\");\n _shaderSets[10].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[10].ShaderProgram, \"a_texCoord\");\n _shaderSets[10].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"s_texture0\");\n _shaderSets[10].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_matrix\");\n _shaderSets[10].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_baseColor\");\n _shaderSets[10].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[10].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング、PremultipliedAlpha)\n _shaderSets[11].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[11].ShaderProgram, \"a_position\");\n _shaderSets[11].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[11].ShaderProgram, \"a_texCoord\");\n _shaderSets[11].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"s_texture0\");\n _shaderSets[11].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"s_texture1\");\n _shaderSets[11].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_matrix\");\n _shaderSets[11].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[11].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_channelFlag\");\n _shaderSets[11].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_baseColor\");\n _shaderSets[11].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[11].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[12].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[12].ShaderProgram, \"a_position\");\n _shaderSets[12].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[12].ShaderProgram, \"a_texCoord\");\n _shaderSets[12].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"s_texture0\");\n _shaderSets[12].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"s_texture1\");\n _shaderSets[12].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_matrix\");\n _shaderSets[12].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[12].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_channelFlag\");\n _shaderSets[12].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_baseColor\");\n _shaderSets[12].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[12].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_screenColor\");\n\n // 乗算\n _shaderSets[13].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[13].ShaderProgram, \"a_position\");\n _shaderSets[13].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[13].ShaderProgram, \"a_texCoord\");\n _shaderSets[13].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"s_texture0\");\n _shaderSets[13].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_matrix\");\n _shaderSets[13].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_baseColor\");\n _shaderSets[13].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[13].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング)\n _shaderSets[14].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[14].ShaderProgram, \"a_position\");\n _shaderSets[14].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[14].ShaderProgram, \"a_texCoord\");\n _shaderSets[14].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"s_texture0\");\n _shaderSets[14].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"s_texture1\");\n _shaderSets[14].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_matrix\");\n _shaderSets[14].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[14].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_channelFlag\");\n _shaderSets[14].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_baseColor\");\n _shaderSets[14].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[14].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング・反転)\n _shaderSets[15].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[15].ShaderProgram, \"a_position\");\n _shaderSets[15].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[15].ShaderProgram, \"a_texCoord\");\n _shaderSets[15].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"s_texture0\");\n _shaderSets[15].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"s_texture1\");\n _shaderSets[15].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_matrix\");\n _shaderSets[15].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[15].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_channelFlag\");\n _shaderSets[15].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_baseColor\");\n _shaderSets[15].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[15].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_screenColor\");\n\n // 乗算(PremultipliedAlpha)\n _shaderSets[16].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[16].ShaderProgram, \"a_position\");\n _shaderSets[16].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[16].ShaderProgram, \"a_texCoord\");\n _shaderSets[16].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"s_texture0\");\n _shaderSets[16].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_matrix\");\n _shaderSets[16].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_baseColor\");\n _shaderSets[16].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[16].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング、PremultipliedAlpha)\n _shaderSets[17].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[17].ShaderProgram, \"a_position\");\n _shaderSets[17].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[17].ShaderProgram, \"a_texCoord\");\n _shaderSets[17].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"s_texture0\");\n _shaderSets[17].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"s_texture1\");\n _shaderSets[17].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_matrix\");\n _shaderSets[17].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[17].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_channelFlag\");\n _shaderSets[17].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_baseColor\");\n _shaderSets[17].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[17].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[18].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[18].ShaderProgram, \"a_position\");\n _shaderSets[18].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[18].ShaderProgram, \"a_texCoord\");\n _shaderSets[18].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"s_texture0\");\n _shaderSets[18].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"s_texture1\");\n _shaderSets[18].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_matrix\");\n _shaderSets[18].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[18].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_channelFlag\");\n _shaderSets[18].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_baseColor\");\n _shaderSets[18].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[18].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_screenColor\");\n }\n\n /// \n /// シェーダプログラムをロードしてアドレス返す。\n /// \n /// 頂点シェーダのソース\n /// フラグメントシェーダのソース\n /// シェーダプログラムのアドレス\n internal int LoadShaderProgram(string vertShaderSrc, string fragShaderSrc)\n {\n // Create shader program.\n var shaderProgram = gl.CreateProgram();\n\n if ( !CompileShaderSource(out var vertShader, gl.GL_VERTEX_SHADER, vertShaderSrc) )\n {\n CubismLog.Error(\"[Live2D SDK]Vertex shader compile error!\");\n\n return 0;\n }\n\n // Create and compile fragment shader.\n if ( !CompileShaderSource(out var fragShader, gl.GL_FRAGMENT_SHADER, fragShaderSrc) )\n {\n CubismLog.Error(\"[Live2D SDK]Fragment shader compile error!\");\n\n return 0;\n }\n\n // Attach vertex shader to program.\n gl.AttachShader(shaderProgram, vertShader);\n\n // Attach fragment shader to program.\n gl.AttachShader(shaderProgram, fragShader);\n\n // Link program.\n if ( !LinkProgram(shaderProgram) )\n {\n CubismLog.Error(\"[Live2D SDK]Failed to link program: %d\", shaderProgram);\n\n if ( vertShader != 0 )\n {\n gl.DeleteShader(vertShader);\n }\n\n if ( fragShader != 0 )\n {\n gl.DeleteShader(fragShader);\n }\n\n if ( shaderProgram != 0 )\n {\n gl.DeleteProgram(shaderProgram);\n }\n\n return 0;\n }\n\n // Release vertex and fragment shaders.\n if ( vertShader != 0 )\n {\n gl.DetachShader(shaderProgram, vertShader);\n gl.DeleteShader(vertShader);\n }\n\n if ( fragShader != 0 )\n {\n gl.DetachShader(shaderProgram, fragShader);\n gl.DeleteShader(fragShader);\n }\n\n return shaderProgram;\n }\n\n /// \n /// シェーダプログラムをコンパイルする\n /// \n /// コンパイルされたシェーダプログラムのアドレス\n /// シェーダタイプ(Vertex/Fragment)\n /// シェーダソースコード\n /// \n /// true . コンパイル成功\n /// false . コンパイル失敗\n /// \n internal unsafe bool CompileShaderSource(out int outShader, int shaderType, string shaderSource)\n {\n int status;\n\n outShader = gl.CreateShader(shaderType);\n gl.ShaderSource(outShader, shaderSource);\n gl.CompileShader(outShader);\n\n int logLength;\n gl.GetShaderiv(outShader, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetShaderInfoLog(outShader, out var log);\n CubismLog.Error($\"[Live2D SDK]Shader compile log: {log}\");\n }\n\n gl.GetShaderiv(outShader, gl.GL_COMPILE_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n gl.DeleteShader(outShader);\n\n return false;\n }\n\n return true;\n }\n\n /// \n /// シェーダプログラムをリンクする\n /// \n /// リンクするシェーダプログラムのアドレス\n /// \n /// true . リンク成功\n /// false . リンク失敗\n /// \n internal unsafe bool LinkProgram(int shaderProgram)\n {\n int status;\n gl.LinkProgram(shaderProgram);\n\n int logLength;\n gl.GetProgramiv(shaderProgram, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetProgramInfoLog(shaderProgram, out var log);\n CubismLog.Error($\"[Live2D SDK]Program link log: {log}\");\n }\n\n gl.GetProgramiv(shaderProgram, gl.GL_LINK_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n return false;\n }\n\n return true;\n }\n\n /// \n /// シェーダプログラムを検証する\n /// \n /// 検証するシェーダプログラムのアドレス\n /// \n /// true . 正常\n /// false . 異常\n /// \n internal unsafe bool ValidateProgram(int shaderProgram)\n {\n int logLength,\n status;\n\n gl.ValidateProgram(shaderProgram);\n gl.GetProgramiv(shaderProgram, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetProgramInfoLog(shaderProgram, out var log);\n CubismLog.Error($\"[Live2D SDK]Validate program log: {log}\");\n }\n\n gl.GetProgramiv(shaderProgram, gl.GL_VALIDATE_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n return false;\n }\n\n return true;\n }\n\n /// \n /// Tegraプロセッサ対応。拡張方式による描画の有効・無効\n /// \n /// trueなら拡張方式で描画する\n /// trueなら拡張方式のPA設定を有効にする\n internal void SetExtShaderMode(bool extMode, bool extPAMode)\n {\n s_extMode = extMode;\n s_extPAMode = extPAMode;\n }\n\n /// \n /// 必要な頂点属性を設定する\n /// \n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n public void SetVertexAttributes(CubismShaderSet shaderSet)\n {\n // 頂点位置属性の設定\n gl.EnableVertexAttribArray(shaderSet.AttributePositionLocation);\n gl.VertexAttribPointer(shaderSet.AttributePositionLocation, 2, gl.GL_FLOAT, false, 4 * sizeof(float), 0);\n\n // テクスチャ座標属性の設定\n gl.EnableVertexAttribArray(shaderSet.AttributeTexCoordLocation);\n gl.VertexAttribPointer(shaderSet.AttributeTexCoordLocation, 2, gl.GL_FLOAT, false, 4 * sizeof(float), 2 * sizeof(float));\n }\n\n /// \n /// テクスチャの設定を行う\n /// \n /// レンダラー\n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n public void SetupTexture(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index, CubismShaderSet shaderSet)\n {\n var textureIndex = model.GetDrawableTextureIndex(index);\n var textureId = renderer.GetBindedTextureId(textureIndex);\n gl.ActiveTexture(gl.GL_TEXTURE0);\n gl.BindTexture(gl.GL_TEXTURE_2D, textureId);\n gl.Uniform1i(shaderSet.SamplerTexture0Location, 0);\n }\n\n /// \n /// 色関連のユニフォーム変数の設定を行う\n /// \n /// レンダラー\n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n /// ベースカラー\n /// 乗算カラー\n /// スクリーンカラー\n public void SetColorUniformVariables(CubismShaderSet shaderSet,\n CubismTextureColor baseColor, CubismTextureColor multiplyColor, CubismTextureColor screenColor)\n {\n gl.Uniform4f(shaderSet.UniformBaseColorLocation, baseColor.R, baseColor.G, baseColor.B, baseColor.A);\n gl.Uniform4f(shaderSet.UniformMultiplyColorLocation, multiplyColor.R, multiplyColor.G, multiplyColor.B, multiplyColor.A);\n gl.Uniform4f(shaderSet.UniformScreenColorLocation, screenColor.R, screenColor.G, screenColor.B, screenColor.A);\n }\n\n /// \n /// カラーチャンネル関連のユニフォーム変数の設定を行う\n /// \n /// シェーダープログラムのセット\n /// 描画コンテクスト\n public void SetColorChannelUniformVariables(CubismShaderSet shaderSet, CubismClippingContext contextBuffer)\n {\n var channelIndex = contextBuffer.LayoutChannelIndex;\n var colorChannel = contextBuffer.Manager.GetChannelFlagAsColor(channelIndex);\n gl.Uniform4f(shaderSet.UnifromChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnxSimd.cs", "using System.Buffers;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\nusing System.Runtime.Intrinsics.X86;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnxSimd : IF0Predictor, IDisposable\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n // Preallocated buffers\n private readonly float[] _inputBatchBuffer;\n\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Flattened arrays for better cache locality and SIMD operations\n private readonly float[] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[] _tempBuffer; // Used for temporary calculations\n\n private readonly float[] _transitionMatrix;\n\n private readonly float[] _transOutBuffer;\n\n private readonly float[] _valueBuffer;\n\n // SIMD vector size based on hardware\n private readonly int _vectorSize;\n\n public CrepeOnnxSimd(string modelPath)\n {\n // Determine vector size based on hardware capabilities\n _vectorSize = Vector.Count;\n\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n // Use hardware specific optimizations if available\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Initialize preallocated buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Initialize flattened buffers for Viterbi algorithm\n _logProbBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE * PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = new float[PITCH_BINS * PITCH_BINS];\n _transOutBuffer = new float[PITCH_BINS * PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n _tempBuffer = new float[Math.Max(BATCH_SIZE, PITCH_BINS) * _vectorSize];\n\n // Initialize logPInitBuffer with equal probabilities\n var logInitProb = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n FillArray(_logPInitBuffer, logInitProb);\n\n // Initialize transition matrix\n InitializeTransitionMatrix(_transitionMatrix);\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n if ( length > f0Output.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Rent buffer from pool for periodicity data\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = pdBuffer.AsSpan(0, length);\n var wavSpan = wav.Span;\n var f0Span = f0Output.Span.Slice(0, length);\n\n // Process audio to extract F0\n Crepe(wavSpan, f0Span, pdSpan);\n\n // Apply post-processing with SIMD\n ApplyPeriodicityThreshold(f0Span, pdSpan, length);\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var totalFrames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < totalFrames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, totalFrames - b);\n\n // Fill the batch input buffer with SIMD\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing with SIMD\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection padding\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection padding\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame using SIMD\n NormalizeAvx(frame);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeSimd(Span input)\n {\n // 1. Calculate mean using SIMD\n float sum = 0;\n var vectorCount = input.Length / _vectorSize;\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var v = new Vector(input.Slice(i * _vectorSize, _vectorSize));\n sum += Vector.Sum(v);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n sum += input[i];\n }\n\n var mean = sum / input.Length;\n\n // 2. Subtract mean and calculate variance using SIMD\n float variance = 0;\n var meanVector = new Vector(mean);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var centered = v - meanVector;\n centered.CopyTo(slice);\n variance += Vector.Sum(centered * centered);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] -= mean;\n variance += input[i] * input[i];\n }\n\n // 3. Calculate stddev and normalize\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVector = new Vector(stddev);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var normalized = v / stddevVector;\n normalized.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] /= stddev;\n }\n }\n\n // Hardware-specific optimization for AVX2-capable systems\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeAvx(Span input)\n {\n if ( !Avx.IsSupported || input.Length < 8 )\n {\n NormalizeSimd(input);\n\n return;\n }\n\n unsafe\n {\n fixed (float* pInput = input)\n {\n // Calculate sum using AVX\n var sumVec = Vector256.Zero;\n var avxVectorCount = input.Length / 8;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n sumVec = Avx.Add(sumVec, v);\n }\n\n // Horizontal sum\n var sumArray = stackalloc float[8];\n Avx.Store(sumArray, sumVec);\n\n float sum = 0;\n for ( var i = 0; i < 8; i++ )\n {\n sum += sumArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n sum += pInput[i];\n }\n\n var mean = sum / input.Length;\n var meanVec = Vector256.Create(mean);\n\n // Subtract mean and compute variance\n var varianceVec = Vector256.Zero;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var centered = Avx.Subtract(v, meanVec);\n Avx.Store(pInput + i * 8, centered);\n varianceVec = Avx.Add(varianceVec, Avx.Multiply(centered, centered));\n }\n\n // Get variance\n var varArray = stackalloc float[8];\n Avx.Store(varArray, varianceVec);\n\n float variance = 0;\n for ( var i = 0; i < 8; i++ )\n {\n variance += varArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] -= mean;\n variance += pInput[i] * pInput[i];\n }\n\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVec = Vector256.Create(stddev);\n\n // Normalize\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var normalized = Avx.Divide(v, stddevVec);\n Avx.Store(pInput + i * 8, normalized);\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] /= stddev;\n }\n }\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor using SIMD where possible\n for ( var i = 0; i < batchSize; i++ )\n {\n var inputOffset = i * WINDOW_SIZE;\n var vectorCount = WINDOW_SIZE / _vectorSize;\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var vectorOffset = v * _vectorSize;\n var source = new Vector(_inputBatchBuffer.AsSpan(inputOffset + vectorOffset, _vectorSize));\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n _inputTensor[i, vectorOffset + j] = source[j];\n }\n }\n\n // Handle remainder\n for ( var j = vectorCount * _vectorSize; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[inputOffset + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Apply frequency range limitation using SIMD where possible\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n ApplyFrequencyRangeLimit(probabilities, outputSize, minidx, maxidx);\n\n // Make a safe copy of the spans since we can't capture them in parallel operations\n var f0Array = new float[f0.Length];\n var pdArray = new float[pd.Length];\n f0.CopyTo(f0Array);\n pd.CopyTo(pdArray);\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0Array, pdArray, outputSize, offset);\n\n // Copy results back\n for ( var i = 0; i < outputSize; i++ )\n {\n if ( offset + i < f0.Length )\n {\n f0[offset + i] = f0Array[offset + i];\n pd[offset + i] = pdArray[offset + i];\n }\n }\n }\n\n private void ApplyFrequencyRangeLimit(float[] probabilities, int outputSize, int minIdx, int maxIdx)\n {\n // Set values outside the frequency range to negative infinity\n Parallel.For(0, outputSize, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Handle first part (below minIdx)\n for ( var i = 0; i < minIdx; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n\n // Handle second part (above maxIdx)\n for ( var i = maxIdx; i < PITCH_BINS; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n });\n }\n\n private void DecodeViterbi(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n // Transfer probabilities to logProbBuffer and apply softmax\n Buffer.BlockCopy(probabilities, 0, _logProbBuffer, 0, nSteps * PITCH_BINS * sizeof(float));\n\n // Apply softmax with SIMD\n SoftmaxSimd(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n ApplyLogToProbs(_logProbBuffer, nSteps);\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[i] = _logProbBuffer[i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm (forward pass)\n for ( var t = 1; t < nSteps; t++ )\n {\n ViterbiForward(t, nSteps);\n }\n\n // Find the most likely final state\n var maxI = FindArgMax(_valueBuffer, (nSteps - 1) * PITCH_BINS, PITCH_BINS);\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[(t + 1) * PITCH_BINS + _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values and apply periodicity\n ConvertToF0(probabilities, f0, pd, nSteps, offset);\n }\n\n private void SoftmaxSimd(float[] data, int nSteps)\n {\n Parallel.For(0, nSteps, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Find max for numerical stability\n var max = float.NegativeInfinity;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n max = Math.Max(max, data[baseIdx + i]);\n }\n\n // Compute exp(x - max) and sum\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[baseIdx + i] = MathF.Exp(data[baseIdx + i] - max);\n sum += data[baseIdx + i];\n }\n\n // Normalize\n var invSum = 1.0f / sum;\n var vecCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var idx = baseIdx + v * _vectorSize;\n var values = new Vector(data.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n data[idx + j] = normalized[j];\n }\n }\n\n // Handle remainder\n for ( var i = baseIdx + vecCount * _vectorSize; i < baseIdx + PITCH_BINS; i++ )\n {\n data[i] *= invSum;\n }\n });\n }\n\n private void ApplyLogToProbs(float[] data, int nSteps)\n {\n var totalSize = nSteps * PITCH_BINS;\n var vecCount = totalSize / _vectorSize;\n var dataSpan = data.AsSpan(0, totalSize);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var slice = dataSpan.Slice(v * _vectorSize, _vectorSize);\n var values = new Vector(slice);\n var logValues = Vector.Log(values + new Vector(float.Epsilon));\n logValues.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vecCount * _vectorSize; i < totalSize; i++ )\n {\n data[i] = MathF.Log(data[i] + float.Epsilon);\n }\n }\n\n private void ViterbiForward(int t, int nSteps)\n {\n var baseIdxCurrent = t * PITCH_BINS;\n var baseIdxPrev = (t - 1) * PITCH_BINS;\n\n // Fixed number of threads to avoid thread contention\n var threadCount = Math.Min(Environment.ProcessorCount, PITCH_BINS);\n\n Parallel.For(0, threadCount, threadIdx =>\n {\n // Each thread processes a chunk of states\n var statesPerThread = (PITCH_BINS + threadCount - 1) / threadCount;\n var startState = threadIdx * statesPerThread;\n var endState = Math.Min(startState + statesPerThread, PITCH_BINS);\n\n for ( var j = startState; j < endState; j++ )\n {\n var maxI = 0;\n var maxVal = float.NegativeInfinity;\n\n // Find max transition - this could be further vectorized for specific hardware\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n var transVal = _valueBuffer[baseIdxPrev + k] + _transitionMatrix[j * PITCH_BINS + k];\n if ( transVal > maxVal )\n {\n maxVal = transVal;\n maxI = k;\n }\n }\n\n _ptrBuffer[baseIdxCurrent + j] = maxI;\n _valueBuffer[baseIdxCurrent + j] = _logProbBuffer[baseIdxCurrent + j] + maxVal;\n }\n });\n }\n\n private int FindArgMax(float[] data, int offset, int length)\n {\n var maxIdx = 0;\n var maxVal = float.NegativeInfinity;\n\n for ( var i = 0; i < length; i++ )\n {\n if ( data[offset + i] > maxVal )\n {\n maxVal = data[offset + i];\n maxIdx = i;\n }\n }\n\n return maxIdx;\n }\n\n private void ConvertToF0(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n if ( offset + t >= f0.Length )\n {\n break;\n }\n\n var bin = _stateBuffer[t];\n var periodicity = probabilities[t * PITCH_BINS + bin];\n var frequency = ConvertBinToFrequency(bin);\n\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n\n private void ApplyPeriodicityThreshold(Span f0, Span pd, int length)\n {\n const float threshold = 0.1f;\n var vecCount = length / _vectorSize;\n\n // Use SIMD for bulk processing\n for ( var v = 0; v < vecCount; v++ )\n {\n var offset = v * _vectorSize;\n var pdSlice = pd.Slice(offset, _vectorSize);\n var f0Slice = f0.Slice(offset, _vectorSize);\n\n var pdVec = new Vector(pdSlice);\n var thresholdVec = new Vector(threshold);\n var zeroVec = new Vector(0.0f);\n var f0Vec = new Vector(f0Slice);\n\n // Where pd < threshold, set f0 to 0\n var mask = Vector.LessThan(pdVec, thresholdVec);\n var result = Vector.ConditionalSelect(mask, zeroVec, f0Vec);\n\n result.CopyTo(f0Slice);\n }\n\n // Handle remainder with scalar code\n for ( var i = vecCount * _vectorSize; i < length; i++ )\n {\n if ( pd[i] < threshold )\n {\n f0[i] = 0;\n }\n }\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use thread-local window buffers for parallel processing\n Parallel.For(0, length, i =>\n {\n // Allocate a local median buffer for each thread\n var localMedianBuffer = new float[windowSize];\n\n // Get window values\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - radius;\n k = Math.Clamp(k, 0, length - 1);\n localMedianBuffer[j] = original[k];\n }\n\n // Simple sort for small window\n Array.Sort(localMedianBuffer, 0, windowSize);\n result[i] = localMedianBuffer[radius];\n });\n\n // Copy results back to the span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n // Copy to array for processing\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use arrays instead of spans for parallel processing\n Parallel.For(0, length, i =>\n {\n float sum = 0;\n for ( var j = -radius; j <= radius; j++ )\n {\n var k = Math.Clamp(i + j, 0, length - 1);\n sum += original[k];\n }\n\n result[i] = sum / windowSize;\n });\n\n // Copy back to span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void InitializeTransitionMatrix(float[] transitionMatrix)\n {\n Parallel.For(0, PITCH_BINS, y =>\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n float v = 12 - Math.Abs(x - y);\n v = Math.Max(v, 0);\n transitionMatrix[y * PITCH_BINS + x] = v;\n sum += v;\n }\n\n // Normalize and pre-apply log\n var invSum = 1.0f / sum;\n var vectorCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n var epsilonVec = new Vector(float.Epsilon);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var idx = y * PITCH_BINS + v * _vectorSize;\n var values = new Vector(transitionMatrix.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n var logValues = Vector.Log(normalized + epsilonVec);\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n transitionMatrix[idx + j] = logValues[j];\n }\n }\n\n // Handle remainder\n for ( var x = vectorCount * _vectorSize; x < PITCH_BINS; x++ )\n {\n var idx = y * PITCH_BINS + x;\n transitionMatrix[idx] = transitionMatrix[idx] * invSum;\n transitionMatrix[idx] = MathF.Log(transitionMatrix[idx] + float.Epsilon);\n }\n });\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private float ConvertBinToFrequency(int bin)\n {\n const float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n\n return 10 * MathF.Pow(2, cents / 1200);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void FillArray(Span array, float value)\n {\n var vectorCount = array.Length / _vectorSize;\n var valueVec = new Vector(value);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n valueVec.CopyTo(array.Slice(v * _vectorSize, _vectorSize));\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < array.Length; i++ )\n {\n array[i] = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.App/Program.cs", "using System.Text;\n\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\n\nusing PersonaEngine.Lib;\nusing PersonaEngine.Lib.Core;\n\nusing Serilog;\nusing Serilog.Events;\n\nnamespace PersonaEngine.App;\n\ninternal static class Program\n{\n private static async Task Main()\n {\n Console.OutputEncoding = Encoding.UTF8;\n\n var builder = new ConfigurationBuilder()\n .SetBasePath(Directory.GetCurrentDirectory())\n .AddJsonFile(\"appsettings.json\", false, true);\n\n IConfiguration config = builder.Build();\n var services = new ServiceCollection();\n\n services.AddLogging(loggingBuilder =>\n {\n CreateLogger();\n loggingBuilder.AddSerilog();\n });\n\n services.AddMetrics();\n services.AddApp(config);\n\n var serviceProvider = services.BuildServiceProvider();\n \n var window = serviceProvider.GetRequiredService();\n window.Run();\n\n await serviceProvider.DisposeAsync();\n }\n\n private static void CreateLogger()\n {\n Log.Logger = new LoggerConfiguration()\n .MinimumLevel.Warning()\n .MinimumLevel.Override(\"PersonaEngine.Lib.Core.Conversation\", LogEventLevel.Information)\n .Enrich.FromLogContext()\n .Enrich.With()\n .WriteTo.Console(\n outputTemplate: \"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}\"\n )\n .CreateLogger();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionService.cs", "using Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Implementation of the emotion tracking service\n/// \npublic class EmotionService : IEmotionService\n{\n private readonly Dictionary> _emotionMap = new();\n\n private readonly ILogger _logger;\n\n public EmotionService(ILogger logger) { _logger = logger; }\n\n public void RegisterEmotions(Guid segmentId, IReadOnlyList emotions)\n {\n if (_emotionMap.Count > 100)\n {\n _emotionMap.Clear();\n _logger.LogWarning(\"Emotion map cleared due to size limit\");\n }\n \n if ( emotions is not { Count: > 0 } )\n {\n return;\n }\n\n _emotionMap[segmentId] = emotions;\n _logger.LogDebug(\"Registered {Count} emotions for segment {SegmentId}\", emotions.Count, segmentId);\n }\n\n public IReadOnlyList GetEmotions(Guid segmentId)\n {\n if ( _emotionMap.TryGetValue(segmentId, out var emotions) )\n {\n return emotions;\n }\n\n return Array.Empty();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AwaitableAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that can be awaited for audio data.\n/// \n/// \n/// Important: This should be used at most by one writer and one reader.\n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class AwaitableAudioSource(\n IReadOnlyDictionary metadata,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = BufferedMemoryAudioSource.DefaultInitialSize,\n int initialSizeBytes = BufferedMemoryAudioSource.DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : DiscardableMemoryAudioSource(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy), IAwaitableAudioSource\n{\n private readonly TaskCompletionSource initializationTcs = new();\n\n private readonly AsyncAutoResetEvent samplesAvailableEvent = new();\n\n protected readonly Lock syncRoot = new();\n\n /// \n /// Gets a value indicating whether the source is flushed.\n /// \n public bool IsFlushed { get; private set; }\n\n public override Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n lock (syncRoot)\n {\n // Calling the base method with lock is fine here, as the base method will not await anything.\n return base.GetFramesAsync(startFrame, maxFrames, cancellationToken);\n }\n }\n\n public override Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n lock (syncRoot)\n {\n // Calling the base method with lock is fine here, as the base method will not await anything.\n return base.CopyFramesAsync(destination, startFrame, maxFrames, cancellationToken);\n }\n }\n\n public override Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n lock (syncRoot)\n {\n // Calling the base method with lock is fine here, as the base method will not await anything.\n return base.GetSamplesAsync(startFrame, maxFrames, cancellationToken);\n }\n }\n\n /// \n public async Task WaitForNewSamplesAsync(long sampleCount, CancellationToken cancellationToken)\n {\n while ( !IsFlushed && SampleVirtualCount <= sampleCount )\n {\n await samplesAvailableEvent.WaitAsync().WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n }\n\n public async Task WaitForNewSamplesAsync(TimeSpan minimumDuration, CancellationToken cancellationToken)\n {\n while ( !IsFlushed && Duration <= minimumDuration )\n {\n await samplesAvailableEvent.WaitAsync().WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n public async Task WaitForInitializationAsync(CancellationToken cancellationToken)\n {\n if ( IsInitialized )\n {\n return;\n }\n\n await initializationTcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public void Flush()\n {\n lock (syncRoot)\n {\n IsFlushed = true;\n samplesAvailableEvent.Set();\n }\n }\n\n public override void DiscardFrames(int count)\n {\n lock (syncRoot)\n {\n base.DiscardFrames(count);\n }\n }\n\n public override void AddFrame(ReadOnlyMemory frame)\n {\n lock (syncRoot)\n {\n if ( IsFlushed )\n {\n throw new InvalidOperationException(\"The source is flushed and cannot accept new frames.\");\n }\n\n base.AddFrame(frame);\n if ( IsInitialized && !initializationTcs.Task.IsCompleted )\n {\n initializationTcs.SetResult(true);\n }\n }\n }\n\n public override void AddFrame(ReadOnlyMemory frame)\n {\n lock (syncRoot)\n {\n if ( IsFlushed )\n {\n throw new InvalidOperationException(\"The source is flushed and cannot accept new frames.\");\n }\n\n base.AddFrame(frame);\n if ( IsInitialized && !initializationTcs.Task.IsCompleted )\n {\n initializationTcs.SetResult(true);\n }\n }\n }\n\n /// \n /// Notifies that new samples are available.\n /// \n public void NotifyNewSamples() { samplesAvailableEvent.Set(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsMemoryCache.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Enhanced memory-efficient TTS cache implementation with expiration and metrics\n/// \npublic class TtsMemoryCache : ITtsCache, IAsyncDisposable\n{\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly Timer _cleanupTimer;\n\n private readonly ILogger _logger;\n\n private readonly TtsCacheOptions _options;\n\n private readonly ConcurrentDictionary _pendingOperations = new();\n\n private bool _disposed;\n\n private long _evictions;\n\n // Metrics\n private long _hits;\n\n private long _misses;\n\n public TtsMemoryCache(\n ILogger logger,\n IOptions options = null)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _options = options?.Value ?? new TtsCacheOptions();\n\n // Set up periodic cleanup if expiration is enabled\n if ( _options.ItemExpiration.HasValue )\n {\n // Run cleanup at half the expiration interval or at least every minute\n var cleanupInterval = TimeSpan.FromMilliseconds(\n Math.Max(_options.ItemExpiration.Value.TotalMilliseconds / 2, 60000));\n\n _cleanupTimer = new Timer(CleanupExpiredItems, null, cleanupInterval, cleanupInterval);\n }\n }\n\n /// \n /// Gets or adds an item to the cache with metrics and expiration support\n /// \n public async Task GetOrAddAsync(\n string key,\n Func> valueFactory,\n CancellationToken cancellationToken = default) where T : class\n {\n // Argument validation\n if ( string.IsNullOrEmpty(key) )\n {\n throw new ArgumentException(\"Cache key cannot be null or empty\", nameof(key));\n }\n\n if ( valueFactory == null )\n {\n throw new ArgumentNullException(nameof(valueFactory));\n }\n\n // Check for cancellation\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check if the item exists in cache and is valid\n if ( _cache.TryGetValue(key, out var cacheItem) )\n {\n if ( cacheItem.Value is T typedValue && !IsExpired(cacheItem) )\n {\n Interlocked.Increment(ref _hits);\n _logger.LogDebug(\"Cache hit for key {Key}\", key);\n\n return typedValue;\n }\n\n // Item exists but is either wrong type or expired - remove it\n _cache.TryRemove(key, out _);\n }\n\n // Item not in cache or was invalid, create it\n Interlocked.Increment(ref _misses);\n _logger.LogDebug(\"Cache miss for key {Key}, creating new value\", key);\n\n var stopwatch = new Stopwatch();\n if ( _options.CollectMetrics )\n {\n _pendingOperations[key] = stopwatch;\n stopwatch.Start();\n }\n\n try\n {\n // Create the value\n var value = await valueFactory(cancellationToken);\n\n if ( value == null )\n {\n _logger.LogWarning(\"Value factory for key {Key} returned null\", key);\n\n return null;\n }\n\n // Enforce maximum cache size if configured\n EnforceSizeLimit();\n\n // Add to cache using GetOrAdd to handle the case where another thread might have\n // added the same key while we were creating the value\n var newItem = new CacheItem { Value = value };\n var actualItem = _cache.GetOrAdd(key, newItem);\n\n // If another thread beat us to it and that value is of the correct type, use it\n if ( actualItem != newItem && actualItem.Value is T existingValue && !IsExpired(actualItem) )\n {\n _logger.LogDebug(\"Another thread already added key {Key}\", key);\n\n return existingValue;\n }\n\n return value;\n }\n catch (Exception ex) when (ex is not OperationCanceledException)\n {\n _logger.LogError(ex, \"Error creating value for key {Key}\", key);\n\n throw;\n }\n finally\n {\n if ( _options.CollectMetrics && _pendingOperations.TryRemove(key, out var sw) )\n {\n sw.Stop();\n _logger.LogDebug(\"Value creation for key {Key} took {ElapsedMs}ms\", key, sw.ElapsedMilliseconds);\n }\n }\n }\n\n /// \n /// Removes an item from the cache\n /// \n public void Remove(string key)\n {\n if ( string.IsNullOrEmpty(key) )\n {\n throw new ArgumentException(\"Cache key cannot be null or empty\", nameof(key));\n }\n\n if ( _cache.TryRemove(key, out _) )\n {\n _logger.LogDebug(\"Removed item with key {Key} from cache\", key);\n }\n }\n\n /// \n /// Clears the cache\n /// \n public void Clear()\n {\n _cache.Clear();\n _logger.LogInformation(\"Cache cleared\");\n }\n\n /// \n /// Disposes the cache resources\n /// \n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n\n _cleanupTimer?.Dispose();\n _cache.Clear();\n\n var stats = GetStatistics();\n _logger.LogInformation(\n \"Cache disposed. Final stats: Size={Size}, Hits={Hits}, Misses={Misses}, Evictions={Evictions}\",\n stats.Size, stats.Hits, stats.Misses, stats.Evictions);\n\n await Task.CompletedTask;\n }\n\n /// \n /// Gets the current cache statistics\n /// \n public (int Size, long Hits, long Misses, long Evictions) GetStatistics() { return (_cache.Count, _hits, _misses, _evictions); }\n\n /// \n /// Determines if a cache item has expired\n /// \n private bool IsExpired(CacheItem item)\n {\n if ( _options.ItemExpiration == null )\n {\n return false;\n }\n\n return DateTime.UtcNow - item.CreatedAt > _options.ItemExpiration.Value;\n }\n\n /// \n /// Enforces the maximum cache size by removing oldest items if necessary\n /// \n private void EnforceSizeLimit()\n {\n if ( _options.MaxItems <= 0 || _cache.Count < _options.MaxItems )\n {\n return;\n }\n\n // Get all items with their ages\n var items = _cache.ToArray();\n\n // Sort by creation time (oldest first)\n Array.Sort(items, (a, b) => a.Value.CreatedAt.CompareTo(b.Value.CreatedAt));\n\n // Remove oldest items to get back under the limit\n // We'll remove 10% of max capacity to avoid doing this too frequently\n var toRemove = Math.Max(1, _options.MaxItems / 10);\n\n for ( var i = 0; i < toRemove && i < items.Length; i++ )\n {\n if ( _cache.TryRemove(items[i].Key, out _) )\n {\n Interlocked.Increment(ref _evictions);\n }\n }\n\n _logger.LogInformation(\"Removed {Count} items from cache due to size limit\", toRemove);\n }\n\n /// \n /// Periodically removes expired items from the cache\n /// \n private void CleanupExpiredItems(object state)\n {\n if ( _disposed )\n {\n return;\n }\n\n try\n {\n var removed = 0;\n foreach ( var key in _cache.Keys )\n {\n if ( _cache.TryGetValue(key, out var item) && IsExpired(item) )\n {\n if ( _cache.TryRemove(key, out _) )\n {\n removed++;\n Interlocked.Increment(ref _evictions);\n }\n }\n }\n\n if ( removed > 0 )\n {\n _logger.LogInformation(\"Removed {Count} expired items from cache\", removed);\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during cache cleanup\");\n }\n }\n\n private class CacheItem\n {\n public object Value { get; set; }\n\n public DateTime CreatedAt { get; } = DateTime.UtcNow;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismRenderer_OpenGLES2.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic class CubismRenderer_OpenGLES2 : CubismRenderer\n{\n public const int ColorChannelCount = 4; // 実験時に1チャンネルの場合は1、RGBだけの場合は3、アルファも含める場合は4\n\n public const int ClippingMaskMaxCountOnDefault = 36; // 通常のフレームバッファ1枚あたりのマスク最大数\n\n public const int ClippingMaskMaxCountOnMultiRenderTexture = 32; // フレームバッファが2枚以上ある場合のフレームバッファ1枚あたりのマスク最大数\n\n /// \n /// マスク描画用のフレームバッファ\n /// \n private readonly List _offscreenFrameBuffers = [];\n\n /// \n /// OpenGLのステートを保持するオブジェクト\n /// \n private readonly CubismRendererProfile_OpenGLES2 _rendererProfile;\n\n /// \n /// 描画オブジェクトのインデックスを描画順に並べたリスト\n /// \n private readonly int[] _sortedDrawableIndexList;\n\n /// \n /// モデルが参照するテクスチャとレンダラでバインドしているテクスチャとのマップ\n /// \n private readonly Dictionary _textures;\n\n private readonly OpenGLApi GL;\n\n /// \n /// クリッピングマスク管理オブジェクト\n /// \n private CubismClippingManager_OpenGLES2? _clippingManager;\n\n internal CubismShader_OpenGLES2 Shader;\n\n internal VBO[] vbo = new VBO[512];\n\n public CubismRenderer_OpenGLES2(OpenGLApi gl, CubismModel model, int maskBufferCount = 1) : base(model)\n {\n GL = gl;\n Shader = new CubismShader_OpenGLES2(gl);\n _rendererProfile = new CubismRendererProfile_OpenGLES2(gl);\n _textures = new Dictionary(32);\n\n VertexArray = GL.GenVertexArray();\n VertexBuffer = GL.GenBuffer();\n IndexBuffer = GL.GenBuffer();\n\n // 1未満は1に補正する\n if ( maskBufferCount < 1 )\n {\n maskBufferCount = 1;\n CubismLog.Warning(\"[Live2D SDK]The number of render textures must be an integer greater than or equal to 1. Set the number of render textures to 1.\");\n }\n\n if ( model.IsUsingMasking() )\n {\n _clippingManager = new CubismClippingManager_OpenGLES2(GL); //クリッピングマスク・バッファ前処理方式を初期化\n _clippingManager.Initialize(model, maskBufferCount);\n\n _offscreenFrameBuffers.Clear();\n for ( var i = 0; i < maskBufferCount; ++i )\n {\n var offscreenSurface = new CubismOffscreenSurface_OpenGLES2(GL);\n offscreenSurface.CreateOffscreenSurface((int)_clippingManager.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n _offscreenFrameBuffers.Add(offscreenSurface);\n }\n }\n\n _sortedDrawableIndexList = new int[model.GetDrawableCount()];\n }\n\n /// \n /// マスクテクスチャに描画するためのクリッピングコンテキスト\n /// \n internal CubismClippingContext? ClippingContextBufferForMask { get; set; }\n\n /// \n /// 画面上描画するためのクリッピングコンテキスト\n /// \n internal CubismClippingContext? ClippingContextBufferForDraw { get; set; }\n\n internal int VertexArray { get; private set; }\n\n internal int VertexBuffer { get; private set; }\n\n internal int IndexBuffer { get; private set; }\n\n /// \n /// Tegraプロセッサ対応。拡張方式による描画の有効・無効\n /// \n /// trueなら拡張方式で描画する\n /// trueなら拡張方式のPA設定を有効にする\n public void SetExtShaderMode(bool extMode, bool extPAMode = false)\n {\n Shader.SetExtShaderMode(extMode, extPAMode);\n Shader.ReleaseShaderProgram();\n }\n\n /// \n /// OpenGLテクスチャのバインド処理\n /// CubismRendererにテクスチャを設定し、CubismRenderer中でその画像を参照するためのIndex値を戻り値とする\n /// \n /// セットするモデルテクスチャの番号\n /// OpenGLテクスチャの番号\n public void BindTexture(int modelTextureNo, int glTextureNo) { _textures[modelTextureNo] = glTextureNo; }\n\n /// \n /// OpenGLにバインドされたテクスチャのリストを取得する\n /// \n /// テクスチャのアドレスのリスト\n public Dictionary GetBindedTextures() { return _textures; }\n\n /// \n /// クリッピングマスクバッファのサイズを設定する\n /// マスク用のFrameBufferを破棄・再作成するため処理コストは高い。\n /// \n /// クリッピングマスクバッファのサイズ\n /// クリッピングマスクバッファのサイズ\n public void SetClippingMaskBufferSize(float width, float height)\n {\n if ( _clippingManager == null )\n {\n return;\n }\n\n // インスタンス破棄前にレンダーテクスチャの数を保存\n var renderTextureCount = _clippingManager.RenderTextureCount;\n\n _clippingManager = new CubismClippingManager_OpenGLES2(GL);\n\n _clippingManager.SetClippingMaskBufferSize(width, height);\n\n _clippingManager.Initialize(Model, renderTextureCount);\n }\n\n /// \n /// クリッピングマスクのバッファを取得する\n /// \n /// クリッピングマスクのバッファへのポインタ\n public CubismOffscreenSurface_OpenGLES2 GetMaskBuffer(int index) { return _offscreenFrameBuffers[index]; }\n\n internal override unsafe void DrawMesh(int textureNo, int indexCount, int vertexCount\n , ushort* indexArray, float* vertexArray, float* uvArray\n , float opacity, CubismBlendMode colorBlendMode, bool invertedMask)\n {\n throw new Exception(\"[Live2D Core]Use 'DrawMeshOpenGL' function\");\n }\n\n public bool IsGeneratingMask() { return ClippingContextBufferForMask != null; }\n\n /// \n /// [オーバーライド]\n /// 描画オブジェクト(アートメッシュ)を描画する。\n /// ポリゴンメッシュとテクスチャ番号をセットで渡す。\n /// \n /// 描画するテクスチャ番号\n /// 描画オブジェクトのインデックス値\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュのインデックス配列\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 乗算色\n /// スクリーン色\n /// 不透明度\n /// カラー合成タイプ\n /// マスク使用時のマスクの反転使用\n internal unsafe void DrawMeshOpenGL(CubismModel model, int index)\n {\n if ( _textures[model.GetDrawableTextureIndex(index)] == 0 )\n {\n return; // モデルが参照するテクスチャがバインドされていない場合は描画をスキップする\n }\n\n // 裏面描画の有効・無効\n if ( IsCulling )\n {\n GL.Enable(GL.GL_CULL_FACE);\n }\n else\n {\n GL.Disable(GL.GL_CULL_FACE);\n }\n\n GL.FrontFace(GL.GL_CCW); // Cubism SDK OpenGLはマスク・アートメッシュ共にCCWが表面\n\n var vertexCount = model.GetDrawableVertexCount(index);\n var vertexArray = model.GetDrawableVertices(index);\n var uvArray = (float*)model.GetDrawableVertexUvs(index);\n\n GL.BindVertexArray(VertexArray);\n\n if ( vbo == null || vbo.Length < vertexCount )\n {\n vbo = new VBO[vertexCount];\n }\n\n for ( var a = 0; a < vertexCount; a++ )\n {\n vbo[a].ver0 = vertexArray[a * 2];\n vbo[a].ver1 = vertexArray[a * 2 + 1];\n vbo[a].uv0 = uvArray[a * 2];\n vbo[a].uv1 = uvArray[a * 2 + 1];\n }\n\n var indexCount = model.GetDrawableVertexIndexCount(index);\n var indexArray = model.GetDrawableVertexIndices(index);\n\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, VertexBuffer);\n fixed (void* p = vbo)\n {\n GL.BufferData(GL.GL_ARRAY_BUFFER, vertexCount * sizeof(VBO), new IntPtr(p), GL.GL_STATIC_DRAW);\n }\n\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n GL.BufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(ushort), new IntPtr(indexArray), GL.GL_STATIC_DRAW);\n\n if ( IsGeneratingMask() ) // マスク生成時\n {\n Shader.SetupShaderProgramForMask(this, model, index);\n }\n else\n {\n Shader.SetupShaderProgramForDraw(this, model, index);\n }\n\n // ポリゴンメッシュを描画する\n GL.DrawElements(GL.GL_TRIANGLES, indexCount, GL.GL_UNSIGNED_SHORT, 0);\n\n // 後処理\n GL.UseProgram(0);\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, 0);\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);\n GL.BindVertexArray(0);\n ClippingContextBufferForDraw = null;\n ClippingContextBufferForMask = null;\n }\n\n /// \n /// 描画開始時の追加処理。\n /// モデルを描画する前にクリッピングマスクに必要な処理を実装している。\n /// \n internal void PreDraw()\n {\n GL.Disable(GL.GL_SCISSOR_TEST);\n GL.Disable(GL.GL_STENCIL_TEST);\n GL.Disable(GL.GL_DEPTH_TEST);\n\n GL.Enable(GL.GL_BLEND);\n GL.ColorMask(true, true, true, true);\n\n if ( GL.IsPhoneES2 )\n {\n GL.BindVertexArrayOES(0);\n }\n\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, 0); //前にバッファがバインドされていたら破棄する必要がある\n\n //異方性フィルタリング。プラットフォームのOpenGLによっては未対応の場合があるので、未設定のときは設定しない\n if ( Anisotropy > 0.0f )\n {\n for ( var i = 0; i < _textures.Count; i++ )\n {\n GL.BindTexture(GL.GL_TEXTURE_2D, _textures[i]);\n GL.TexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, Anisotropy);\n }\n }\n }\n\n /// \n /// モデル描画直前のOpenGLES2のステートを保持する\n /// \n protected override void SaveProfile() { _rendererProfile.Save(); }\n\n /// \n /// モデル描画直前のOpenGLES2のステートを保持する\n /// \n protected override void RestoreProfile() { _rendererProfile.Restore(); }\n\n protected override unsafe void DoDrawModel()\n {\n //------------ クリッピングマスク・バッファ前処理方式の場合 ------------\n if ( _clippingManager != null )\n {\n PreDraw();\n\n // サイズが違う場合はここで作成しなおし\n for ( var i = 0; i < _clippingManager.RenderTextureCount; ++i )\n {\n if ( _offscreenFrameBuffers[i].BufferWidth != (uint)_clippingManager.ClippingMaskBufferSize.X ||\n _offscreenFrameBuffers[i].BufferHeight != (uint)_clippingManager.ClippingMaskBufferSize.Y )\n {\n _offscreenFrameBuffers[i].CreateOffscreenSurface(\n (int)_clippingManager.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n }\n }\n\n if ( UseHighPrecisionMask )\n {\n _clippingManager.SetupMatrixForHighPrecision(Model, false);\n }\n else\n {\n _clippingManager.SetupClippingContext(Model, this, _rendererProfile.LastFBO, _rendererProfile.LastViewport);\n }\n }\n\n // 上記クリッピング処理内でも一度PreDrawを呼ぶので注意!!\n PreDraw();\n\n var drawableCount = Model.GetDrawableCount();\n var renderOrder = Model.GetDrawableRenderOrders();\n\n // インデックスを描画順でソート\n for ( var i = 0; i < drawableCount; ++i )\n {\n var order = renderOrder[i];\n _sortedDrawableIndexList[order] = i;\n }\n\n if ( GL.AlwaysClear )\n {\n GL.ClearColor(ClearColor.R,\n ClearColor.G,\n ClearColor.B,\n ClearColor.A);\n\n GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n }\n\n // 描画\n for ( var i = 0; i < drawableCount; ++i )\n {\n var drawableIndex = _sortedDrawableIndexList[i];\n\n // Drawableが表示状態でなければ処理をパスする\n if ( !Model.GetDrawableDynamicFlagIsVisible(drawableIndex) )\n {\n continue;\n }\n\n // クリッピングマスク\n var clipContext = _clippingManager?.ClippingContextListForDraw[drawableIndex];\n\n if ( clipContext != null && UseHighPrecisionMask ) // マスクを書く必要がある\n {\n if ( clipContext.IsUsing ) // 書くことになっていた\n {\n // 生成したFrameBufferと同じサイズでビューポートを設定\n GL.Viewport(0, 0, (int)_clippingManager!.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n\n PreDraw(); // バッファをクリアする\n\n // ---------- マスク描画処理 ----------\n // マスク用RenderTextureをactiveにセット\n GetMaskBuffer(clipContext.BufferIndex).BeginDraw(_rendererProfile.LastFBO);\n\n // マスクをクリアする\n // 1が無効(描かれない)領域、0が有効(描かれる)領域。(シェーダで Cd*Csで0に近い値をかけてマスクを作る。1をかけると何も起こらない)\n GL.ClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n GL.Clear(GL.GL_COLOR_BUFFER_BIT);\n }\n\n {\n var clipDrawCount = clipContext.ClippingIdCount;\n for ( var index = 0; index < clipDrawCount; index++ )\n {\n var clipDrawIndex = clipContext.ClippingIdList[index];\n\n // 頂点情報が更新されておらず、信頼性がない場合は描画をパスする\n if ( !Model.GetDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex) )\n {\n continue;\n }\n\n IsCulling = Model.GetDrawableCulling(clipDrawIndex);\n\n // 今回専用の変換を適用して描く\n // チャンネルも切り替える必要がある(A,R,G,B)\n ClippingContextBufferForMask = clipContext;\n\n DrawMeshOpenGL(Model, clipDrawIndex);\n }\n }\n\n {\n // --- 後処理 ---\n GetMaskBuffer(clipContext.BufferIndex).EndDraw();\n ClippingContextBufferForMask = null;\n GL.Viewport(_rendererProfile.LastViewport[0], _rendererProfile.LastViewport[1], _rendererProfile.LastViewport[2], _rendererProfile.LastViewport[3]);\n\n PreDraw(); // バッファをクリアする\n }\n }\n\n // クリッピングマスクをセットする\n ClippingContextBufferForDraw = clipContext;\n\n IsCulling = Model.GetDrawableCulling(drawableIndex);\n\n DrawMeshOpenGL(Model, drawableIndex);\n }\n }\n\n public override void Dispose() { Shader.ReleaseShaderProgram(); }\n\n public int GetBindedTextureId(int textureId) { return _textures[textureId] != 0 ? _textures[textureId] : -1; }\n\n [StructLayout(LayoutKind.Sequential, Pack = 4)]\n internal struct VBO\n {\n public float ver0;\n\n public float ver1;\n\n public float uv0;\n\n public float uv1;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiConfigurationManager.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements centralized configuration management\n/// \npublic class UiConfigurationManager : IUiConfigurationManager\n{\n private readonly string _configFilePath;\n\n private readonly IOptionsMonitor _configMonitor;\n\n private AvatarAppConfig _currentConfig;\n\n public UiConfigurationManager(\n IOptionsMonitor configMonitor,\n string configFilePath = \"appsettings.json\")\n {\n _configMonitor = configMonitor ?? throw new ArgumentNullException(nameof(configMonitor));\n _configFilePath = configFilePath;\n _currentConfig = _configMonitor.CurrentValue;\n\n // Subscribe to configuration changes\n _configMonitor.OnChange(config =>\n {\n _currentConfig = config;\n OnConfigurationChanged(null, ConfigurationChangedEventArgs.ChangeType.Reloaded);\n });\n }\n\n public event EventHandler ConfigurationChanged;\n\n public T GetConfiguration(string sectionKey = null)\n {\n if ( sectionKey == null )\n {\n if ( typeof(T) == typeof(AvatarAppConfig) )\n {\n return (T)(object)_currentConfig;\n }\n\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} without section key\");\n }\n\n return sectionKey switch {\n \"TTS\" => (T)(object)_currentConfig.Tts,\n \"Voice\" => (T)(object)_currentConfig.Tts.Voice,\n \"RouletteWheel\" => (T)(object)_currentConfig.RouletteWheel,\n \"Microphone\" => (T)(object)_currentConfig.Microphone,\n _ => throw new ArgumentException($\"Unknown section key: {sectionKey}\")\n };\n }\n\n public void UpdateConfiguration(T configuration, string? sectionKey = null)\n {\n if ( sectionKey == null )\n {\n if ( configuration is AvatarAppConfig appConfig )\n {\n _currentConfig = appConfig;\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n\n return;\n }\n\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} without section key\");\n }\n\n switch ( sectionKey )\n {\n case \"TTS\":\n if ( configuration is TtsConfiguration ttsConfig )\n {\n _currentConfig = _currentConfig with { Tts = ttsConfig };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n\n break;\n\n case \"Voice\":\n if ( configuration is KokoroVoiceOptions voiceOptions )\n {\n var tts = _currentConfig.Tts;\n _currentConfig = _currentConfig with { Tts = tts with { Voice = voiceOptions } };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n\n break;\n\n case \"Roulette\":\n if ( configuration is RouletteWheelOptions rouletteWheelOptions )\n {\n _currentConfig = _currentConfig with { RouletteWheel = rouletteWheelOptions };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n\n break;\n case \"Microphone\":\n if ( configuration is MicrophoneConfiguration microphoneConfig )\n {\n _currentConfig = _currentConfig with { Microphone = microphoneConfig };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n \n break;\n default:\n throw new ArgumentException($\"Unknown section key: {sectionKey}\");\n }\n }\n\n public void SaveConfiguration()\n {\n // Save the configuration to the JSON file\n try\n {\n var jsonString = JsonSerializer.Serialize(\n new Dictionary { { \"Config\", _currentConfig } },\n new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }\n );\n\n File.WriteAllText(_configFilePath, jsonString);\n OnConfigurationChanged(null, ConfigurationChangedEventArgs.ChangeType.Saved);\n }\n catch (Exception ex)\n {\n // Convert to a more specific exception type with details\n throw new ConfigurationSaveException($\"Failed to save configuration to {_configFilePath}\", ex);\n }\n }\n\n public void ReloadConfiguration()\n {\n // Load the latest configuration from options monitor\n _currentConfig = _configMonitor.CurrentValue;\n OnConfigurationChanged(null, ConfigurationChangedEventArgs.ChangeType.Reloaded);\n }\n\n private void OnConfigurationChanged(string sectionKey, ConfigurationChangedEventArgs.ChangeType type) { ConfigurationChanged?.Invoke(this, new ConfigurationChangedEventArgs(sectionKey, type)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/BufferObject.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\npublic class BufferObject : IDisposable where T : unmanaged\n{\n private readonly BufferTargetARB _bufferType;\n\n private readonly GL _gl;\n\n private readonly uint _handle;\n\n private readonly int _size;\n\n public unsafe BufferObject(GL glApi, int size, BufferTargetARB bufferType, bool isDynamic)\n {\n _gl = glApi;\n\n _bufferType = bufferType;\n _size = size;\n\n _handle = _gl.GenBuffer();\n _gl.CheckError();\n\n Bind();\n\n var elementSizeInBytes = Marshal.SizeOf();\n _gl.BufferData(bufferType, (nuint)(size * elementSizeInBytes), null, isDynamic ? BufferUsageARB.StreamDraw : BufferUsageARB.StaticDraw);\n _gl.CheckError();\n }\n\n public void Dispose()\n {\n _gl.DeleteBuffer(_handle);\n _gl.CheckError();\n }\n\n public void Bind()\n {\n _gl.BindBuffer(_bufferType, _handle);\n _gl.CheckError();\n }\n\n public unsafe void SetData(T[] data, int startIndex, int elementCount)\n {\n Bind();\n\n fixed (T* dataPtr = &data[startIndex])\n {\n var elementSizeInBytes = sizeof(T);\n\n _gl.BufferSubData(_bufferType, 0, (nuint)(elementCount * elementSizeInBytes), dataPtr);\n _gl.CheckError();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/VisualQASemanticKernelChatEngine.cs", "using System.Runtime.CompilerServices;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.SemanticKernel;\nusing Microsoft.SemanticKernel.ChatCompletion;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic class VisualQASemanticKernelChatEngine : IVisualChatEngine\n{\n private readonly IChatCompletionService _chatCompletionService;\n\n private readonly ILogger _logger;\n\n private readonly SemaphoreSlim _semaphore = new(1, 1);\n\n public VisualQASemanticKernelChatEngine(Kernel kernel, ILogger logger)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _chatCompletionService = kernel.GetRequiredService(\"vision\");\n }\n\n public void Dispose()\n {\n try\n {\n _logger.LogInformation(\"Disposing VisualQASemanticKernelChatEngine\");\n _semaphore.Dispose();\n GC.SuppressFinalize(this);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error occurred while disposing VisualQASemanticKernelChatEngine\");\n }\n }\n\n public async IAsyncEnumerable GetStreamingChatResponseAsync(\n VisualChatMessage visualInput,\n PromptExecutionSettings? executionSettings = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n await _semaphore.WaitAsync(cancellationToken);\n\n try\n {\n var chatHistory = new ChatHistory(\"You are a helpful assistant.\");\n chatHistory.AddUserMessage(\n [\n new TextContent(visualInput.Query),\n new ImageContent(visualInput.ImageData, \"image/png\")\n ]);\n\n var chunkCount = 0;\n\n var streamingResponse = _chatCompletionService.GetStreamingChatMessageContentsAsync(\n chatHistory,\n executionSettings,\n null,\n cancellationToken);\n\n await foreach ( var chunk in streamingResponse.ConfigureAwait(false) )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n chunkCount++;\n var content = chunk.Content ?? string.Empty;\n\n yield return content;\n }\n\n _logger.LogInformation(\"Visual QA response streaming completed. Total chunks: {ChunkCount}\", chunkCount);\n }\n finally\n {\n _semaphore.Release();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismMoc.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// Mocデータの管理を行うクラス。\n/// \npublic class CubismMoc : IDisposable\n{\n /// \n /// Mocデータ\n /// \n private readonly IntPtr _moc;\n\n /// \n /// バッファからMocファイルを読み取り、Mocデータを作成する。\n /// \n /// Mocファイルのバッファ\n /// MOCの整合性チェックフラグ(初期値 : false)\n /// \n public CubismMoc(byte[] mocBytes, bool shouldCheckMocConsistency = false)\n {\n var alignedBuffer = CubismFramework.AllocateAligned(mocBytes.Length, CsmEnum.csmAlignofMoc);\n Marshal.Copy(mocBytes, 0, alignedBuffer, mocBytes.Length);\n\n if ( shouldCheckMocConsistency )\n {\n // .moc3の整合性を確認\n var consistency = HasMocConsistency(alignedBuffer, mocBytes.Length);\n if ( !consistency )\n {\n CubismFramework.DeallocateAligned(alignedBuffer);\n\n // 整合性が確認できなければ処理しない\n throw new Exception(\"Inconsistent MOC3.\");\n }\n }\n\n var moc = CubismCore.ReviveMocInPlace(alignedBuffer, mocBytes.Length);\n\n if ( moc == IntPtr.Zero )\n {\n throw new Exception(\"MOC3 is null\");\n }\n\n _moc = moc;\n\n MocVersion = CubismCore.GetMocVersion(alignedBuffer, mocBytes.Length);\n\n var modelSize = CubismCore.GetSizeofModel(_moc);\n var modelMemory = CubismFramework.AllocateAligned(modelSize, CsmEnum.CsmAlignofModel);\n\n var model = CubismCore.InitializeModelInPlace(_moc, modelMemory, modelSize);\n\n if ( model == IntPtr.Zero )\n {\n throw new Exception(\"MODEL is null\");\n }\n\n Model = new CubismModel(model);\n }\n\n /// \n /// 読み込んだモデルの.moc3 Version\n /// \n public uint MocVersion { get; }\n\n public CubismModel Model { get; }\n\n /// \n /// デストラクタ。\n /// \n public void Dispose()\n {\n Model.Dispose();\n CubismFramework.DeallocateAligned(_moc);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// 最新の.moc3 Versionを取得する。\n /// \n /// \n public static uint GetLatestMocVersion() { return CubismCore.GetLatestMocVersion(); }\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// '1' if Moc is valid; '0' otherwise.\n public static bool HasMocConsistency(IntPtr address, int size) { return CubismCore.HasMocConsistency(address, size); }\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Mocファイルのバッファ\n /// バッファのサイズ\n /// 'true' if Moc is valid; 'false' otherwise.\n public static bool HasMocConsistencyFromUnrevivedMoc(byte[] data)\n {\n var alignedBuffer = CubismFramework.AllocateAligned(data.Length, CsmEnum.csmAlignofMoc);\n Marshal.Copy(data, 0, alignedBuffer, data.Length);\n\n var consistency = HasMocConsistency(alignedBuffer, data.Length);\n\n CubismFramework.DeallocateAligned(alignedBuffer);\n\n return consistency;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/GeneralEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic record BaseOutputEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent;\n\npublic record ErrorOutputEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, Exception Exception) : IOutputEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/SentenceSegmenter.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// High-performance sentence segmentation using both rule-based and ML approaches with\n/// advanced handling of edge cases and text structures\n/// \npublic partial class SentenceSegmenter(IMlSentenceDetector mlDetector, ILogger logger) : ISentenceSegmenter\n{\n private const int MinimumSentences = 2;\n\n private static readonly Regex SpecialTokenPattern = new(@\"\\[[A-Z]+:[^\\]]+\\]\", RegexOptions.Compiled);\n\n private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n private readonly IMlSentenceDetector _mlDetector = mlDetector ?? throw new ArgumentNullException(nameof(mlDetector));\n\n /// \n /// Segments text into sentences with optimized handling and pre-processing for boundary detection\n /// \n public IReadOnlyList Segment(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Array.Empty();\n }\n\n try\n {\n // First attempt with original text\n var sentences = _mlDetector.Detect(text);\n\n // If we have fewer than minimum required sentences, try pre-processing\n if ( sentences.Count < MinimumSentences )\n {\n _logger.LogTrace(\"Initial segmentation yielded only {count} sentence(s), attempting pre-processing\", sentences.Count);\n\n // Apply pre-processing to create potential sentence boundaries\n var preprocessedText = AddPotentialSentenceBoundaries(text);\n\n // Re-detect sentences with the pre-processed text\n sentences = _mlDetector.Detect(preprocessedText);\n\n _logger.LogTrace(\"After pre-processing, segmentation yielded {count} sentence(s)\", sentences.Count);\n }\n\n return sentences;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error in sentence segmentation.\");\n\n return Array.Empty();\n }\n }\n\n /// \n /// Adds potential sentence boundaries by replacing certain punctuation with periods\n /// to help generate at least 2 sentences when possible\n /// \n private string AddPotentialSentenceBoundaries(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return text;\n }\n\n try\n {\n if ( !SpecialTokenPattern.IsMatch(text) )\n {\n // No special tokens - apply normal processing\n return ApplyBasicPreprocessing(text);\n }\n\n var result = new StringBuilder(text.Length + 20);\n var currentPosition = 0;\n\n foreach ( Match match in SpecialTokenPattern.Matches(text) )\n {\n // Process the text between the last token and this one\n if ( match.Index > currentPosition )\n {\n var segment = text.Substring(currentPosition, match.Index - currentPosition);\n result.Append(ApplyBasicPreprocessing(segment));\n }\n\n // Append the token unchanged\n result.Append(match.Value);\n currentPosition = match.Index + match.Length;\n }\n\n if ( currentPosition < text.Length )\n {\n var segment = text[currentPosition..];\n result.Append(ApplyBasicPreprocessing(segment));\n }\n\n return result.ToString();\n }\n catch (Exception ex)\n {\n _logger.LogWarning(ex, \"Error during preprocessing for sentence boundaries. Using original text.\");\n\n return text;\n }\n }\n\n /// \n /// Applies basic preprocessing rules to a text segment without special tokens\n /// \n private string ApplyBasicPreprocessing(string text)\n {\n // Replace semicolons with periods\n text = text.Replace(\";\", \".\");\n\n // Replace colons with periods\n text = text.Replace(\":\", \".\");\n\n // Replace dashes with periods (when surrounded by spaces)\n text = text.Replace(\" - \", \". \");\n text = text.Replace(\" – \", \". \");\n text = text.Replace(\" — \", \". \");\n\n // Ensure proper spacing after periods for the ML detector\n text = TextAfterSpaceRegex().Replace(text, \". $1\");\n\n return text;\n }\n\n [GeneratedRegex(@\"\\.([A-Za-z0-9])\")] private static partial Regex TextAfterSpaceRegex();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/DiscardableMemoryAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that can be discard samples at the beginning of the stream if not needed.\n/// \n/// \n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class DiscardableMemoryAudioSource(\n IReadOnlyDictionary metadata,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = BufferedMemoryAudioSource.DefaultInitialSize,\n int initialSizeBytes = BufferedMemoryAudioSource.DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : BufferedMemoryAudioSource(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy), IDiscardableAudioSource\n{\n private long framesDiscarded;\n\n public long SampleVirtualCount => base.FramesCount;\n\n public override long FramesCount => base.FramesCount - framesDiscarded;\n\n public override TimeSpan Duration => TimeSpan.FromMilliseconds(SampleVirtualCount * 1000d / SampleRate);\n\n /// \n public virtual void DiscardFrames(int count)\n {\n ThrowIfNotInitialized();\n\n if ( count <= 0 )\n {\n throw new ArgumentOutOfRangeException(nameof(count), \"Count must be positive.\");\n }\n\n if ( count > FramesCount )\n {\n throw new ArgumentOutOfRangeException(nameof(count), \"Cannot discard more samples than available.\");\n }\n\n var framesToKeep = FramesCount - count;\n if ( FloatFrames != null )\n {\n var samplesToDiscard = count * ChannelCount;\n var samplesToKeep = framesToKeep * ChannelCount;\n Array.Copy(FloatFrames, samplesToDiscard, FloatFrames, 0, samplesToKeep);\n }\n\n if ( ByteFrames != null )\n {\n var bytesToDiscard = count * FrameSize;\n var bytesToKeep = framesToKeep * FrameSize;\n Array.Copy(ByteFrames, bytesToDiscard, ByteFrames, 0, bytesToKeep);\n }\n\n framesDiscarded += count;\n }\n\n /// \n public override Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(startFrame, framesDiscarded, nameof(startFrame));\n\n return base.GetSamplesAsync(startFrame - framesDiscarded, maxFrames, cancellationToken);\n }\n\n /// \n public override Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(startFrame, framesDiscarded, nameof(startFrame));\n\n return base.GetFramesAsync(startFrame - framesDiscarded, maxFrames, cancellationToken);\n }\n\n public override Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(startFrame, framesDiscarded, nameof(startFrame));\n\n return base.CopyFramesAsync(destination, startFrame - framesDiscarded, maxFrames, cancellationToken);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismClippingManager_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic class CubismClippingManager_OpenGLES2(OpenGLApi gl) : CubismClippingManager(RenderType.OpenGL)\n{\n /// \n /// クリッピングコンテキストを作成する。モデル描画時に実行する。\n /// \n /// モデルのインスタンス\n /// レンダラのインスタンス\n /// フレームバッファ\n /// ビューポート\n internal unsafe void SetupClippingContext(CubismModel model, CubismRenderer_OpenGLES2 renderer, int lastFBO, int[] lastViewport)\n {\n // 全てのクリッピングを用意する\n // 同じクリップ(複数の場合はまとめて1つのクリップ)を使う場合は1度だけ設定する\n var usingClipCount = 0;\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // 1つのクリッピングマスクに関して\n var cc = ClippingContextListForMask[clipIndex];\n\n // このクリップを利用する描画オブジェクト群全体を囲む矩形を計算\n CalcClippedDrawTotalBounds(model, cc!);\n\n if ( cc!.IsUsing )\n {\n usingClipCount++; //使用中としてカウント\n }\n }\n\n if ( usingClipCount <= 0 )\n {\n return;\n }\n\n // マスク作成処理\n // 生成したOffscreenSurfaceと同じサイズでビューポートを設定\n gl.Viewport(0, 0, (int)ClippingMaskBufferSize.X, (int)ClippingMaskBufferSize.Y);\n\n // 後の計算のためにインデックスの最初をセット\n CurrentMaskBuffer = renderer.GetMaskBuffer(0);\n // ----- マスク描画処理 -----\n CurrentMaskBuffer.BeginDraw(lastFBO);\n\n renderer.PreDraw(); // バッファをクリアする\n\n // 各マスクのレイアウトを決定していく\n SetupLayoutBounds(usingClipCount);\n\n // サイズがレンダーテクスチャの枚数と合わない場合は合わせる\n if ( ClearedMaskBufferFlags.Count != RenderTextureCount )\n {\n ClearedMaskBufferFlags.Clear();\n\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n }\n else\n {\n // マスクのクリアフラグを毎フレーム開始時に初期化\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags[i] = false;\n }\n }\n\n // 実際にマスクを生成する\n // 全てのマスクをどの様にレイアウトして描くかを決定し、ClipContext , ClippedDrawContext に記憶する\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // --- 実際に1つのマスクを描く ---\n var clipContext = ClippingContextListForMask[clipIndex];\n var allClippedDrawRect = clipContext!.AllClippedDrawRect; //このマスクを使う、全ての描画オブジェクトの論理座標上の囲み矩形\n var layoutBoundsOnTex01 = clipContext.LayoutBounds; //この中にマスクを収める\n var MARGIN = 0.05f;\n\n // clipContextに設定したオフスクリーンサーフェイスをインデックスで取得\n var clipContextOffscreenSurface = renderer.GetMaskBuffer(clipContext.BufferIndex);\n\n // 現在のオフスクリーンサーフェイスがclipContextのものと異なる場合\n if ( CurrentMaskBuffer != clipContextOffscreenSurface )\n {\n CurrentMaskBuffer.EndDraw();\n CurrentMaskBuffer = clipContextOffscreenSurface;\n // マスク用RenderTextureをactiveにセット\n CurrentMaskBuffer.BeginDraw(lastFBO);\n\n // バッファをクリアする。\n renderer.PreDraw();\n }\n\n // モデル座標上の矩形を、適宜マージンを付けて使う\n TmpBoundsOnModel.SetRect(allClippedDrawRect);\n TmpBoundsOnModel.Expand(allClippedDrawRect.Width * MARGIN, allClippedDrawRect.Height * MARGIN);\n //########## 本来は割り当てられた領域の全体を使わず必要最低限のサイズがよい\n // シェーダ用の計算式を求める。回転を考慮しない場合は以下のとおり\n // movePeriod' = movePeriod * scaleX + offX [[ movePeriod' = (movePeriod - tmpBoundsOnModel.movePeriod)*scale + layoutBoundsOnTex01.movePeriod ]]\n var scaleX = layoutBoundsOnTex01.Width / TmpBoundsOnModel.Width;\n var scaleY = layoutBoundsOnTex01.Height / TmpBoundsOnModel.Height;\n\n // マスク生成時に使う行列を求める\n CreateMatrixForMask(false, layoutBoundsOnTex01, scaleX, scaleY);\n\n clipContext.MatrixForMask.SetMatrix(TmpMatrixForMask.Tr);\n clipContext.MatrixForDraw.SetMatrix(TmpMatrixForDraw.Tr);\n\n // 実際の描画を行う\n var clipDrawCount = clipContext.ClippingIdCount;\n for ( var i = 0; i < clipDrawCount; i++ )\n {\n var clipDrawIndex = clipContext.ClippingIdList[i];\n\n // 頂点情報が更新されておらず、信頼性がない場合は描画をパスする\n if ( !model.GetDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex) )\n {\n continue;\n }\n\n renderer.IsCulling = model.GetDrawableCulling(clipDrawIndex);\n\n // マスクがクリアされていないなら処理する\n if ( !ClearedMaskBufferFlags[clipContext.BufferIndex] )\n {\n // マスクをクリアする\n // 1が無効(描かれない)領域、0が有効(描かれる)領域。(シェーダーCd*Csで0に近い値をかけてマスクを作る。1をかけると何も起こらない)\n gl.ClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n gl.Clear(gl.GL_COLOR_BUFFER_BIT);\n ClearedMaskBufferFlags[clipContext.BufferIndex] = true;\n }\n\n // 今回専用の変換を適用して描く\n // チャンネルも切り替える必要がある(A,R,G,B)\n renderer.ClippingContextBufferForMask = clipContext;\n\n renderer.DrawMeshOpenGL(model, clipDrawIndex);\n }\n }\n\n // --- 後処理 ---\n CurrentMaskBuffer.EndDraw();\n renderer.ClippingContextBufferForMask = null;\n gl.Viewport(lastViewport[0], lastViewport[1], lastViewport[2], lastViewport[3]);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/BufferedMemoryAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that stores audio samples in memory.\n/// \n/// \n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class BufferedMemoryAudioSource : IAudioSource, IMemoryBackedAudioSource\n{\n public const int DefaultInitialSize = 1024 * 16;\n\n private readonly IChannelAggregationStrategy? aggregationStrategy;\n\n protected byte[]? ByteFrames;\n\n protected float[]? FloatFrames;\n\n private long framesCount;\n\n private bool isDisposed;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// A value indicating whether to store samples as floats. Default true.\n /// A value indicating whether to store samples as byte[]. Default false.\n /// Optional. The channel aggregation strategy to use.\n public BufferedMemoryAudioSource(IReadOnlyDictionary metadata,\n bool storeFloats = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n {\n Metadata = metadata;\n this.aggregationStrategy = aggregationStrategy;\n\n if ( !storeFloats && !storeBytes )\n {\n throw new ArgumentException(\"At least one of storeFloats or storeBytes must be true.\");\n }\n\n if ( storeFloats )\n {\n FloatFrames = new float[initialSizeFloats];\n }\n\n if ( storeBytes )\n {\n ByteFrames = new byte[initialSizeBytes];\n }\n }\n\n /// \n /// Gets the header of the audio source.\n /// \n protected AudioSourceHeader Header { get; private set; } = null!;\n\n /// \n /// Gets the size of a single frame in the current wave file.\n /// \n public int FrameSize => BitsPerSample * ChannelCount / 8;\n\n /// \n /// Represents the actual number of channels in the source.\n /// \n /// \n /// Note, that the actual number of channels may be different from the number of channels in the header if the source\n /// uses an aggregation strategy.\n /// \n public ushort ChannelCount => aggregationStrategy == null ? Header.Channels : (ushort)1;\n\n /// \n /// Gets the number of samples for each channel.\n /// \n public virtual long FramesCount => framesCount;\n\n /// \n /// Gets a value indicating whether the source is initialized.\n /// \n public bool IsInitialized { get; private set; }\n\n public uint SampleRate => Header.SampleRate;\n\n public ushort BitsPerSample => Header.BitsPerSample;\n\n public IReadOnlyDictionary Metadata { get; }\n\n public virtual TimeSpan Duration => TimeSpan.FromMilliseconds(FramesCount * 1000d / SampleRate);\n\n public virtual TimeSpan TotalDuration => TimeSpan.FromMilliseconds(framesCount * 1000d / SampleRate);\n\n /// \n public void Dispose()\n {\n if ( isDisposed )\n {\n return;\n }\n\n Dispose(true);\n GC.SuppressFinalize(this);\n isDisposed = true;\n }\n\n public virtual Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ThrowIfNotInitialized();\n\n // We first check if we have the samples as floats, if not we deserialize them from bytes\n if ( FloatFrames != null )\n {\n return Task.FromResult(GetFloatFramesSlice(startFrame, maxFrames));\n }\n\n var byteSlice = GetByteFramesSlice(startFrame, maxFrames);\n\n return Task.FromResult(SampleSerializer.Deserialize(byteSlice, BitsPerSample));\n }\n\n public virtual Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n // We first check if we have the samples as bytes, if not we serialize them from floats\n if ( ByteFrames != null )\n {\n return Task.FromResult(GetByteFramesSlice(startFrame, maxFrames));\n }\n\n var slice = GetFloatFramesSlice(startFrame, maxFrames);\n\n return Task.FromResult(SampleSerializer.Serialize(slice, BitsPerSample));\n }\n\n public virtual Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n if ( ByteFrames != null )\n {\n var slice = GetByteFramesSlice(startFrame, maxFrames);\n\n slice.CopyTo(destination);\n var byteFrameCount = slice.Length / FrameSize;\n\n return Task.FromResult(byteFrameCount);\n }\n\n var floatSlice = GetFloatFramesSlice(startFrame, maxFrames);\n SampleSerializer.Serialize(floatSlice, destination, BitsPerSample);\n\n var frameCount = floatSlice.Length / ChannelCount;\n\n return Task.FromResult(frameCount);\n }\n\n public bool StoresFloats => FloatFrames != null;\n\n public bool StoresBytes => ByteFrames != null;\n\n ~BufferedMemoryAudioSource() { Dispose(false); }\n\n /// \n /// Initializes the source with the specified header.\n /// \n /// The audio source header.\n /// Thrown when the source is already initialized.\n public virtual void Initialize(AudioSourceHeader header)\n {\n if ( IsInitialized )\n {\n throw new InvalidOperationException(\"The source is already initialized.\");\n }\n\n Header = header;\n IsInitialized = true;\n }\n\n /// \n /// Adds frames to the source.\n /// \n /// The frame of samples to add.\n /// Thrown when the source is not initialized.\n /// Thrown when the frame size does not match the channels.\n public virtual void AddFrame(ReadOnlyMemory frame)\n {\n ThrowIfNotInitialized();\n\n if ( frame.Length != Header.Channels )\n {\n throw new ArgumentException(\"The frame size does not match the channels.\", nameof(frame));\n }\n\n if ( FloatFrames != null )\n {\n AddFrameToSamples(frame);\n }\n\n if ( ByteFrames != null )\n {\n AddFrameToFrames(frame);\n }\n\n framesCount++;\n }\n\n /// \n /// Adds frames to the source.\n /// \n /// The frame buffer to add.\n /// Thrown when the source is not initialized.\n /// Thrown when the frame size does not match the channels.\n public virtual void AddFrame(ReadOnlyMemory frame)\n {\n ThrowIfNotInitialized();\n if ( frame.Length != Header.Channels * Header.BitsPerSample / 8 )\n {\n throw new ArgumentException(\"The frame size does not match the channels.\", nameof(frame));\n }\n\n if ( FloatFrames != null )\n {\n AddFrameToSamples(frame);\n }\n\n if ( ByteFrames != null )\n {\n AddFrameToFrames(frame);\n }\n\n framesCount++;\n }\n\n protected void ThrowIfNotInitialized()\n {\n if ( !IsInitialized )\n {\n throw new InvalidOperationException(\"The source is not initialized.\");\n }\n }\n\n /// \n /// Disposes the object.\n /// \n /// A value indicating whether the method is called from Dispose.\n protected virtual void Dispose(bool disposing)\n {\n if ( disposing )\n {\n FloatFrames = [];\n ByteFrames = [];\n }\n }\n\n private Memory GetFloatFramesSlice(long startFrame, int maxFrames)\n {\n var startSample = (int)(startFrame * ChannelCount);\n var length = (int)(Math.Min(maxFrames, FramesCount - startFrame) * ChannelCount);\n\n return FloatFrames.AsMemory(startSample, length);\n }\n\n private Memory GetByteFramesSlice(long startFrame, int maxFrames)\n {\n var startByte = (int)(startFrame * FrameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * FrameSize);\n\n return ByteFrames.AsMemory(startByte, lengthBytes);\n }\n\n private void AddFrameToFrames(ReadOnlyMemory frame)\n {\n if ( ByteFrames!.Length <= FramesCount * FrameSize )\n {\n Array.Resize(ref ByteFrames, ByteFrames.Length * 2);\n }\n\n var startByte = (int)(FramesCount * FrameSize);\n var destinationMemory = ByteFrames.AsMemory(startByte);\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory, BitsPerSample);\n }\n else\n {\n frame.Span.CopyTo(destinationMemory.Span);\n }\n }\n\n private void AddFrameToSamples(ReadOnlyMemory frame)\n {\n if ( FloatFrames!.Length <= FramesCount * ChannelCount )\n {\n Array.Resize(ref FloatFrames, FloatFrames.Length * 2);\n }\n\n var destinationMemory = FloatFrames.AsMemory((int)(FramesCount * ChannelCount));\n\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory, BitsPerSample);\n }\n else\n {\n SampleSerializer.Deserialize(frame, FloatFrames.AsMemory((int)(FramesCount * ChannelCount)), BitsPerSample);\n }\n }\n\n private void AddFrameToFrames(ReadOnlyMemory frame)\n {\n if ( ByteFrames!.Length <= FramesCount * FrameSize )\n {\n Array.Resize(ref ByteFrames, ByteFrames.Length * 2);\n }\n\n var startByte = (int)(FramesCount * FrameSize);\n var destinationMemory = ByteFrames.AsMemory(startByte);\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory, BitsPerSample);\n }\n else\n {\n SampleSerializer.Serialize(frame, ByteFrames.AsMemory(startByte), BitsPerSample);\n }\n }\n\n private void AddFrameToSamples(ReadOnlyMemory frame)\n {\n if ( FloatFrames!.Length <= FramesCount * ChannelCount )\n {\n Array.Resize(ref FloatFrames, FloatFrames.Length * 2);\n }\n\n var destinationMemory = FloatFrames.AsMemory((int)(FramesCount * ChannelCount));\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory);\n }\n else\n {\n frame.Span.CopyTo(destinationMemory.Span);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AwaitableWaveFileSource.cs", "using PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Similar with allows writing data from a wave file instead of writing the\n/// samples directly.\n/// \n/// \n/// Important: This should be used at most by one writer and one reader.\n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class AwaitableWaveFileSource(\n IReadOnlyDictionary metadata,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = BufferedMemoryAudioSource.DefaultInitialSize,\n int initialSizeBytes = BufferedMemoryAudioSource.DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : AwaitableAudioSource(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy)\n{\n private MergedMemoryChunks? headerChunks;\n\n private MergedMemoryChunks? sampleDataChunks;\n\n public void WriteData(ReadOnlyMemory data)\n {\n if ( IsFlushed )\n {\n throw new InvalidOperationException(\"Cannot write to flushed stream.\");\n }\n\n // We need the dataOffset in case the data contains both header and samples\n var dataOffset = 0;\n if ( !IsInitialized )\n {\n if ( headerChunks == null )\n {\n headerChunks = new MergedMemoryChunks(data);\n }\n else\n {\n headerChunks.AddChunk(data);\n }\n\n var headerParseResult = WaveFileUtils.ParseHeader(headerChunks);\n if ( headerParseResult.IsIncomplete )\n {\n // Need more data for header\n // We need to copy the last chunk as we'll keep it for the next iteration\n headerChunks = new MergedMemoryChunks(headerChunks.ToArray());\n\n return;\n }\n\n if ( headerParseResult.IsCorrupt )\n {\n throw new InvalidOperationException(headerParseResult.ErrorMessage);\n }\n\n if ( !headerParseResult.IsSuccess || headerParseResult.Header == null )\n {\n throw new NotSupportedException(headerParseResult.ErrorMessage);\n }\n\n base.Initialize(headerParseResult.Header);\n dataOffset = headerParseResult.DataOffset;\n }\n\n // Now process sample data\n var sampleData = dataOffset == 0 ? data : data.Slice(dataOffset);\n lock (syncRoot)\n {\n ProcessSamples(sampleData);\n }\n\n NotifyNewSamples();\n }\n\n private void ProcessSamples(ReadOnlyMemory sampleData)\n {\n if ( sampleDataChunks != null )\n {\n sampleDataChunks.AddChunk(sampleData);\n }\n else\n {\n sampleDataChunks = new MergedMemoryChunks(sampleData);\n }\n\n // Calculate how many complete frames we can process\n var framesToProcess = sampleDataChunks.Length / FrameSize;\n\n if ( framesToProcess == 0 )\n {\n // Not enough data to process even a single frame, wait for more data\n return;\n }\n\n for ( var frameIndex = 0; frameIndex < framesToProcess; frameIndex++ )\n {\n var frame = sampleDataChunks.GetChunk(FrameSize);\n AddFrame(frame);\n }\n\n // After processing, check if there are remaining bytes and store them for the next iteration\n // We need to copy the memory (with ToArray()) as otherwise, it might be overriden by the new chunk.\n sampleDataChunks = sampleDataChunks.Length > sampleDataChunks.Position\n ? new MergedMemoryChunks(sampleDataChunks.GetChunk((int)(sampleDataChunks.Length - sampleDataChunks.Position)).ToArray().AsMemory())\n : null;\n }\n\n protected override void Dispose(bool disposing)\n {\n headerChunks = null;\n sampleDataChunks = null;\n base.Dispose(disposing);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/FontProvider.cs", "using System.Drawing;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.OpenGL;\n\nusing StbImageSharp;\n\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI;\n\n/// \n/// Manages caching and loading of fonts and textures.\n/// \npublic class FontProvider : IStartupTask\n{\n private const string FONTS_DIR = @\"Resources\\Fonts\";\n\n private const string IMAGES_PATH = @\"Resources\\Imgs\";\n\n private readonly Dictionary _fontCache = new();\n\n private readonly ILogger _logger;\n\n private readonly Dictionary _textureCache = new();\n\n private Texture2DManager _texture2DManager = null!;\n\n // static FontProvider()\n // {\n // FontSystemDefaults.FontLoader = new SixLaborsFontLoader();\n // }\n\n public FontProvider(ILogger logger) { _logger = logger; }\n\n public void Execute(GL gl) { _texture2DManager = new Texture2DManager(gl); }\n\n public Task> GetAvailableFontsAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n if ( !Directory.Exists(FONTS_DIR) )\n {\n _logger.LogWarning(\"Fonts directory not found: {Path}\", FONTS_DIR);\n\n return Task.FromResult>(Array.Empty());\n }\n\n var fontFiles = Directory.GetFiles(FONTS_DIR, \"*.ttf\");\n var fontNames = new List(fontFiles.Length);\n foreach ( var file in fontFiles )\n {\n var voiceId = Path.GetFileName(file);\n fontNames.Add(voiceId);\n }\n\n _logger.LogInformation(\"Found {Count} available fonts\", fontNames.Count);\n\n return Task.FromResult>(fontNames);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available fonts\");\n\n throw;\n }\n }\n\n public FontSystem GetFontSystem(string fontName)\n {\n if ( !_fontCache.TryGetValue(fontName, out var fontSystem) )\n {\n fontSystem = new FontSystem();\n var fontData = File.ReadAllBytes(Path.Combine(FONTS_DIR, fontName));\n fontSystem.AddFont(fontData);\n _fontCache[fontName] = fontSystem;\n }\n\n return fontSystem;\n }\n\n public Texture GetTexture(string imageName)\n {\n if ( !_textureCache.TryGetValue(imageName, out var texture) )\n {\n using var stream = File.OpenRead(Path.Combine(IMAGES_PATH, imageName));\n var imageResult = ImageResult.FromStream(stream, ColorComponents.RedGreenBlueAlpha);\n\n // Premultiply alpha\n unsafe\n {\n fixed (byte* b = imageResult.Data)\n {\n var ptr = b;\n for ( var i = 0; i < imageResult.Data.Length; i += 4, ptr += 4 )\n {\n var falpha = ptr[3] / 255.0f;\n ptr[0] = (byte)(ptr[0] * falpha);\n ptr[1] = (byte)(ptr[1] * falpha);\n ptr[2] = (byte)(ptr[2] * falpha);\n }\n }\n }\n\n texture = (Texture)_texture2DManager.CreateTexture(imageResult.Width, imageResult.Height);\n _texture2DManager.SetTextureData(texture, new Rectangle(0, 0, (int)texture.Width, (int)texture.Height), imageResult.Data);\n _textureCache[imageName] = texture;\n }\n\n return texture;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Vision/WindowCaptureService.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.Formats.Png;\nusing SixLabors.ImageSharp.PixelFormats;\nusing SixLabors.ImageSharp.Processing;\n\nusing uniffi.rust_lib;\n\nnamespace PersonaEngine.Lib.Vision;\n\npublic class CaptureFrameEventArgs : EventArgs\n{\n public CaptureFrameEventArgs(ReadOnlyMemory frameData) { FrameData = frameData; }\n\n public ReadOnlyMemory FrameData { get; }\n}\n\npublic class WindowCaptureService : IDisposable\n{\n private readonly VisionConfig _config;\n\n private readonly CancellationTokenSource _cts = new();\n\n private readonly Lock _lock = new();\n\n private readonly ILogger _logger;\n\n private Task? _captureTask;\n\n public WindowCaptureService(IOptions config, ILogger? logger = null)\n\n {\n _config = config.Value.Vision ?? throw new ArgumentNullException(nameof(config));\n _logger = logger ?? NullLogger.Instance;\n }\n\n public void Dispose()\n {\n StopAsync().GetAwaiter().GetResult();\n _cts.Dispose();\n GC.SuppressFinalize(this);\n }\n\n public event EventHandler? OnCaptureFrame;\n\n private void HandleCaptureFrame(ReadOnlyMemory frameData)\n {\n try\n {\n OnCaptureFrame?.Invoke(this, new CaptureFrameEventArgs(frameData));\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error raising PlaybackStarted event\");\n }\n }\n\n public Task StartAsync(CancellationToken cancellationToken = default)\n {\n lock (_lock)\n {\n if ( _captureTask != null )\n {\n return Task.CompletedTask;\n }\n\n _captureTask = Task.Run(() => CaptureLoop(_cts.Token), cancellationToken);\n }\n\n return Task.CompletedTask;\n }\n\n public async Task StopAsync()\n {\n lock (_lock)\n {\n if ( _captureTask == null )\n {\n return;\n }\n\n _cts.Cancel();\n }\n\n try\n {\n await _captureTask.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n // Expected when cancellation is requested.\n }\n finally\n {\n lock (_lock)\n {\n _captureTask = null;\n }\n }\n }\n\n private async Task CaptureLoop(CancellationToken token)\n {\n while ( !token.IsCancellationRequested )\n {\n try\n {\n if ( OnCaptureFrame == null )\n {\n return;\n }\n\n var result = RustLibMethods.CaptureWindowByTitle(_config.WindowTitle);\n if ( result.image != null )\n {\n var imageData = await ProcessImage(result, token);\n HandleCaptureFrame(imageData);\n }\n }\n catch (OperationCanceledException)\n {\n break;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during capture\");\n }\n\n try\n {\n await Task.Delay(_config.CaptureInterval, token).ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n break;\n }\n }\n }\n\n private async Task> ProcessImage(ImageData imageData, CancellationToken token)\n {\n var minPixels = _config.CaptureMinPixels;\n var maxPixels = _config.CaptureMaxPixels;\n\n var width = (int)imageData.width;\n var height = (int)imageData.height;\n using var image = Image.LoadPixelData(imageData.image, width, height);\n var currentPixels = width * height;\n if ( currentPixels < minPixels || currentPixels > maxPixels )\n {\n double scaleFactor;\n if ( currentPixels < minPixels )\n {\n scaleFactor = Math.Sqrt((double)minPixels / currentPixels);\n }\n else\n {\n scaleFactor = Math.Sqrt((double)maxPixels / currentPixels);\n }\n\n var newWidth = (int)(width * scaleFactor);\n var newHeight = (int)(height * scaleFactor);\n\n image.Mutate(x => x.Resize(newWidth, newHeight));\n }\n\n using var memStream = new MemoryStream();\n await image.SaveAsync(memStream, PngFormat.Instance, token);\n\n return new ReadOnlyMemory(memStream.ToArray());\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionAudioFilter.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Audio filter that attaches emotion data to segments during processing\n/// \npublic class EmotionAudioFilter : IAudioFilter\n{\n private readonly IEmotionService _emotionService;\n\n private readonly ILogger _logger;\n\n public EmotionAudioFilter(IEmotionService emotionService, ILoggerFactory loggerFactory)\n {\n _emotionService = emotionService ?? throw new ArgumentNullException(nameof(emotionService));\n _logger = loggerFactory?.CreateLogger() ??\n throw new ArgumentNullException(nameof(loggerFactory));\n }\n\n /// \n /// Priority of the filter (should run after other filters)\n /// \n public int Priority => -100;\n\n /// \n /// Processes the audio segment to attach emotion data\n /// \n public void Process(AudioSegment segment)\n {\n // No modification to the audio data is needed\n // This filter is just here to hook into the audio processing pipeline\n // and could be used to perform any additional emotion-related processing if needed\n\n var emotions = _emotionService.GetEmotions(segment.Id);\n if ( emotions.Any() )\n {\n _logger.LogDebug(\"Audio segment {SegmentId} has {Count} emotions\", segment.Id, emotions.Count);\n\n // The emotions are already registered with the emotion service\n // We could attach them directly to the segment if needed via a custom extension method\n // or simply document that they should be retrieved via the service\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Adapters/IAudioProgressNotifier.cs", "using PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\n\npublic interface IAudioProgressNotifier\n{\n event EventHandler? ChunkPlaybackStarted;\n\n event EventHandler? ChunkPlaybackEnded;\n\n event EventHandler? PlaybackProgress;\n\n void RaiseChunkStarted(object? sender, AudioChunkPlaybackStartedEvent args);\n\n void RaiseChunkEnded(object? sender, AudioChunkPlaybackEndedEvent args);\n\n void RaiseProgress(object? sender, AudioPlaybackProgressEvent args);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/Shader.cs", "using System.Diagnostics;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\ninternal struct UniformFieldInfo\n{\n public int Location;\n\n public string Name;\n\n public int Size;\n\n public UniformType Type;\n}\n\ninternal class Shader : IDisposable\n{\n private readonly Dictionary _attribLocation = new();\n\n private readonly (ShaderType Type, string Path)[] _files;\n\n private readonly GL _gl;\n\n private readonly Dictionary _uniformToLocation = new();\n\n private bool _initialized = false;\n\n public Shader(GL gl, string vertexShader, string fragmentShader)\n {\n _gl = gl;\n _files = [(ShaderType.VertexShader, vertexShader), (ShaderType.FragmentShader, fragmentShader)];\n Program = CreateProgram(_files);\n }\n\n public uint Program { get; private set; }\n\n public void Dispose()\n {\n if ( _initialized )\n {\n _gl.DeleteProgram(Program);\n _initialized = false;\n }\n }\n\n public void Use()\n {\n _gl.UseProgram(Program);\n _gl.CheckError();\n }\n\n public void SetUniform(string name, int value)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.Uniform1(location, value);\n _gl.CheckError();\n }\n\n public void SetUniform(string name, float value)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.Uniform1(location, value);\n _gl.CheckError();\n }\n\n public void SetUniform(string name, float value, float value2)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.Uniform2(location, value, value2);\n _gl.CheckError();\n }\n\n public unsafe void SetUniform(string name, Matrix4x4 value)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.UniformMatrix4(location, 1, false, (float*)&value);\n _gl.CheckError();\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public int GetUniformLocation(string uniform)\n {\n if ( _uniformToLocation.TryGetValue(uniform, out var location) == false )\n {\n location = _gl.GetUniformLocation(Program, uniform);\n _uniformToLocation.Add(uniform, location);\n\n if ( location == -1 )\n {\n Debug.Print($\"The uniform '{uniform}' does not exist in the shader!\");\n }\n }\n\n return location;\n }\n\n public UniformFieldInfo[] GetUniforms()\n {\n _gl.GetProgram(Program, GLEnum.ActiveUniforms, out var uniformCount);\n\n var uniforms = new UniformFieldInfo[uniformCount];\n\n for ( var i = 0; i < uniformCount; i++ )\n {\n var name = _gl.GetActiveUniform(Program, (uint)i, out var size, out var type);\n\n UniformFieldInfo fieldInfo;\n fieldInfo.Location = GetUniformLocation(name);\n fieldInfo.Name = name;\n fieldInfo.Size = size;\n fieldInfo.Type = type;\n\n uniforms[i] = fieldInfo;\n }\n\n return uniforms;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public int GetAttribLocation(string attrib)\n {\n if ( _attribLocation.TryGetValue(attrib, out var location) == false )\n {\n location = _gl.GetAttribLocation(Program, attrib);\n _attribLocation.Add(attrib, location);\n\n if ( location == -1 )\n {\n Debug.Print($\"The attrib '{attrib}' does not exist in the shader!\");\n }\n }\n\n return location;\n }\n\n private uint CreateProgram(params (ShaderType Type, string source)[] shaderPaths)\n {\n var program = _gl.CreateProgram();\n\n Span shaders = stackalloc uint[shaderPaths.Length];\n for ( var i = 0; i < shaderPaths.Length; i++ )\n {\n shaders[i] = CompileShader(shaderPaths[i].Type, shaderPaths[i].source);\n }\n\n foreach ( var shader in shaders )\n {\n _gl.AttachShader(program, shader);\n }\n\n _gl.LinkProgram(program);\n\n _gl.GetProgram(program, GLEnum.LinkStatus, out var success);\n if ( success == 0 )\n {\n var info = _gl.GetProgramInfoLog(program);\n Debug.WriteLine($\"GL.LinkProgram had info log:\\n{info}\");\n }\n\n foreach ( var shader in shaders )\n {\n _gl.DetachShader(program, shader);\n _gl.DeleteShader(shader);\n }\n\n _initialized = true;\n\n return program;\n }\n\n private uint CompileShader(ShaderType type, string source)\n {\n var shader = _gl.CreateShader(type);\n _gl.ShaderSource(shader, source);\n _gl.CompileShader(shader);\n\n _gl.GetShader(shader, ShaderParameterName.CompileStatus, out var success);\n if ( success == 0 )\n {\n var info = _gl.GetShaderInfoLog(shader);\n Debug.WriteLine($\"GL.CompileShader for shader [{type}] had info log:\\n{info}\");\n }\n\n return shader;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SilenceAudioSource.cs", "using System.Buffers;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that stores a continuous memory with only silence and returns it when needed.\n/// \npublic sealed class SilenceAudioSource : IAudioSource\n{\n private readonly Lazy byteSilence;\n\n private readonly Lazy floatSilence;\n\n private readonly bool useMemoryPool;\n\n public SilenceAudioSource(TimeSpan duration, uint sampleRate, IReadOnlyDictionary metadata, ushort channelCount = 1, ushort bitsPerSample = 16, bool useMemoryPool = true)\n {\n SampleRate = sampleRate;\n Metadata = metadata;\n ChannelCount = channelCount;\n BitsPerSample = bitsPerSample;\n this.useMemoryPool = useMemoryPool;\n Duration = duration;\n FramesCount = (long)(duration.TotalSeconds * sampleRate);\n\n byteSilence = new Lazy(GenerateByteSilence);\n floatSilence = new Lazy(GenerateFloatSilence);\n }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration { get; }\n\n public TimeSpan TotalDuration => Duration;\n\n public uint SampleRate { get; }\n\n public long FramesCount { get; }\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public void Dispose()\n {\n if ( useMemoryPool )\n {\n // We don't want to clear this as it is silence anyway (no user data to clear)\n if ( byteSilence.IsValueCreated )\n {\n ArrayPool.Shared.Return(byteSilence.Value);\n }\n\n if ( floatSilence.IsValueCreated )\n {\n ArrayPool.Shared.Return(floatSilence.Value, true);\n }\n }\n }\n\n public Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var startIndex = (int)(startFrame * frameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * frameSize);\n\n var slice = byteSilence.Value.AsMemory(startIndex, lengthBytes);\n\n return Task.FromResult(slice);\n }\n\n public Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var startIndex = (int)(startFrame * ChannelCount);\n var lengthSamples = (int)(Math.Min(maxFrames, FramesCount - startFrame) * ChannelCount);\n\n var slice = floatSilence.Value.AsMemory(startIndex, lengthSamples);\n\n return Task.FromResult(slice);\n }\n\n public Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var startIndex = (int)(startFrame * frameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * frameSize);\n\n var slice = byteSilence.Value.AsMemory(startIndex, lengthBytes);\n slice.CopyTo(destination);\n var frames = lengthBytes / frameSize;\n\n return Task.FromResult(frames);\n }\n\n private byte[] GenerateByteSilence()\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var totalBytes = FramesCount * frameSize;\n\n var silence = useMemoryPool ? ArrayPool.Shared.Rent((int)totalBytes) : new byte[totalBytes];\n\n // 8-bit PCM silence is centered at 128, not 0\n if ( BitsPerSample == 8 )\n {\n Array.Fill(silence, 128, 0, (int)totalBytes);\n }\n else\n {\n Array.Clear(silence, 0, (int)totalBytes); // Zero out for non-8-bit audio\n }\n\n return silence;\n }\n\n private float[] GenerateFloatSilence()\n {\n var totalSamples = FramesCount * ChannelCount;\n var silence = useMemoryPool ? ArrayPool.Shared.Rent((int)totalSamples) : new float[totalSamples];\n\n Array.Clear(silence, 0, (int)totalSamples); // Silence is zeroed-out memory\n\n return silence;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismExpressionMotionManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// パラメータに適用する表情の値を持たせる構造体\n/// \npublic record ExpressionParameterValue\n{\n /// \n /// 加算値\n /// \n public float AdditiveValue;\n\n /// \n /// 乗算値\n /// \n public float MultiplyValue;\n\n /// \n /// 上書き値\n /// \n public float OverwriteValue;\n\n /// \n /// パラメータID\n /// \n public string ParameterId;\n}\n\npublic class CubismExpressionMotionManager : CubismMotionQueueManager\n{\n // モデルに適用する各パラメータの値\n private readonly List _expressionParameterValues = [];\n\n // 再生中の表情のウェイト\n private readonly List _fadeWeights = [];\n\n /// \n /// 現在再生中のモーションの優先度\n /// \n public MotionPriority CurrentPriority { get; private set; }\n\n /// \n /// 再生予定のモーションの優先度。再生中は0になる。モーションファイルを別スレッドで読み込むときの機能。\n /// \n public MotionPriority ReservePriority { get; set; }\n\n /// \n /// 優先度を設定して表情モーションを開始する。\n /// \n /// モーション\n /// 優先度\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotionPriority(ACubismMotion motion, MotionPriority priority)\n {\n if ( priority == ReservePriority )\n {\n ReservePriority = 0; // 予約を解除\n }\n\n CurrentPriority = priority; // 再生中モーションの優先度を設定\n\n _fadeWeights.Add(0.0f);\n\n return StartMotion(motion, UserTimeSeconds);\n }\n\n /// \n /// 表情モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// \n /// true 更新されている\n /// false 更新されていない\n /// \n public bool UpdateMotion(CubismModel model, float deltaTimeSeconds)\n {\n UserTimeSeconds += deltaTimeSeconds;\n var updated = false;\n var motions = Motions;\n\n var expressionWeight = 0.0f;\n var expressionIndex = 0;\n\n // If there is already a motion, set the end flag\n var list = new List();\n foreach ( var item in motions )\n {\n if ( item.Motion is not CubismExpressionMotion expressionMotion )\n {\n list.Add(item);\n\n continue;\n }\n\n var expressionParameters = expressionMotion.Parameters;\n if ( item.Available )\n {\n // 再生中のExpressionが参照しているパラメータをすべてリストアップ\n for ( var i = 0; i < expressionParameters.Count; ++i )\n {\n if ( expressionParameters[i].ParameterId == null )\n {\n continue;\n }\n\n var index = -1;\n // リストにパラメータIDが存在するか検索\n for ( var j = 0; j < _expressionParameterValues.Count; ++j )\n {\n if ( _expressionParameterValues[j].ParameterId != expressionParameters[i].ParameterId )\n {\n continue;\n }\n\n index = j;\n\n break;\n }\n\n if ( index >= 0 )\n {\n continue;\n }\n\n // If the parameter does not exist in the list, add it.\n ExpressionParameterValue item1 = new() { ParameterId = expressionParameters[i].ParameterId, AdditiveValue = CubismExpressionMotion.DefaultAdditiveValue, MultiplyValue = CubismExpressionMotion.DefaultMultiplyValue };\n item1.OverwriteValue = model.GetParameterValue(item1.ParameterId);\n _expressionParameterValues.Add(item1);\n }\n }\n \n // ------ 値を計算する ------\n expressionMotion.SetupMotionQueueEntry(item, UserTimeSeconds);\n _fadeWeights[expressionIndex] = expressionMotion.UpdateFadeWeight(item, UserTimeSeconds);\n expressionMotion.CalculateExpressionParameters(model, UserTimeSeconds,\n item, _expressionParameterValues, expressionIndex, _fadeWeights[expressionIndex]);\n\n expressionWeight += expressionMotion.FadeInSeconds == 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((UserTimeSeconds - item.FadeInStartTime) / expressionMotion.FadeInSeconds);\n\n updated = true;\n\n if ( item.IsTriggeredFadeOut )\n {\n // フェードアウト開始\n item.StartFadeout(item.FadeOutSeconds, UserTimeSeconds);\n }\n\n ++expressionIndex;\n }\n\n // ----- 最新のExpressionのフェードが完了していればそれ以前を削除する ------\n if ( motions.Count > 1 )\n {\n var latestFadeWeight = _fadeWeights[_fadeWeights.Count - 1];\n if ( latestFadeWeight >= 1.0f )\n {\n // 配列の最後の要素は削除しない\n for ( var i = motions.Count - 2; i >= 0; i-- )\n {\n motions.RemoveAt(i);\n _fadeWeights.RemoveAt(i);\n }\n }\n }\n\n if ( expressionWeight > 1.0f )\n {\n expressionWeight = 1.0f;\n }\n\n // モデルに各値を適用\n for ( var i = 0; i < _expressionParameterValues.Count; ++i )\n {\n model.SetParameterValue(_expressionParameterValues[i].ParameterId,\n (_expressionParameterValues[i].OverwriteValue + _expressionParameterValues[i].AdditiveValue) * _expressionParameterValues[i].MultiplyValue,\n expressionWeight);\n\n _expressionParameterValues[i].AdditiveValue = CubismExpressionMotion.DefaultAdditiveValue;\n _expressionParameterValues[i].MultiplyValue = CubismExpressionMotion.DefaultMultiplyValue;\n }\n\n return updated;\n }\n\n /// \n /// 現在の表情のフェードのウェイト値を取得する。\n /// \n /// 取得する表情モーションのインデックス\n /// 表情のフェードのウェイト値\n public float GetFadeWeight(int index) { return _fadeWeights[index]; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCVoiceProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCVoiceProvider : IRVCVoiceProvider\n{\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly ConcurrentDictionary _voicePaths = new();\n\n private bool _disposed;\n\n public RVCVoiceProvider(\n IModelProvider ittsModelProvider,\n ILogger logger)\n {\n _modelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n /// \n public async Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(voiceId) )\n {\n throw new ArgumentException(\"Voice ID cannot be null or empty\", nameof(voiceId));\n }\n\n return await GetVoicePathAsync(voiceId, cancellationToken);\n }\n\n /// \n public async Task> GetAvailableVoicesAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n // Get voice directory\n var model = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCVoices, cancellationToken);\n var voicesDir = model.Path;\n\n if ( !Directory.Exists(voicesDir) )\n {\n _logger.LogWarning(\"Voices directory not found: {Path}\", voicesDir);\n\n return Array.Empty();\n }\n\n // Get all .bin files\n var voiceFiles = Directory.GetFiles(voicesDir, \"*.onnx\");\n\n // Extract voice IDs from filenames\n var voiceIds = new List(voiceFiles.Length);\n\n foreach ( var file in voiceFiles )\n {\n var voiceId = Path.GetFileNameWithoutExtension(file);\n voiceIds.Add(voiceId);\n\n // Cache the path for faster lookup\n _voicePaths[voiceId] = file;\n }\n\n _logger.LogInformation(\"Found {Count} available RVC voices\", voiceIds.Count);\n\n return voiceIds;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available voices\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voicePaths.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n private async Task GetVoicePathAsync(string voiceId, CancellationToken cancellationToken)\n {\n if ( _voicePaths.TryGetValue(voiceId, out var cachedPath) )\n {\n return cachedPath;\n }\n\n var model = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCVoices, cancellationToken);\n var voicesDir = model.Path;\n\n var voicePath = Path.Combine(voicesDir, $\"{voiceId}.onnx\");\n\n if ( !File.Exists(voicePath) )\n {\n _logger.LogWarning(\"Voice file not found: {Path}\", voicePath);\n\n throw new FileNotFoundException($\"Voice file not found for {voiceId}\", voicePath);\n }\n\n _voicePaths[voiceId] = voicePath;\n\n return voicePath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiStyler.cs", "using System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Static utility class for common UI styling operations\n/// \npublic static class UiStyler\n{\n /// \n /// Executes an action with a temporary style color change\n /// \n public static void WithStyleColor(ImGuiCol colorId, Vector4 color, Action action)\n {\n ImGui.PushStyleColor(colorId, color);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleColor();\n }\n }\n\n /// \n /// Executes an action with multiple temporary style color changes\n /// \n public static void WithStyleColors(IReadOnlyList<(ImGuiCol, Vector4)> colors, Action action)\n {\n foreach ( var (colorId, color) in colors )\n {\n ImGui.PushStyleColor(colorId, color);\n }\n\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleColor(colors.Count);\n }\n }\n\n /// \n /// Executes an action with a temporary style variable change\n /// \n public static void WithStyleVar(ImGuiStyleVar styleVar, Vector2 value, Action action)\n {\n ImGui.PushStyleVar(styleVar, value);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleVar();\n }\n }\n\n /// \n /// Executes an action with a temporary style variable change\n /// \n public static void WithStyleVar(ImGuiStyleVar styleVar, float value, Action action)\n {\n ImGui.PushStyleVar(styleVar, value);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleVar();\n }\n }\n\n /// \n /// Displays a help marker with a tooltip\n /// \n public static void HelpMarker(string desc)\n {\n ImGui.TextDisabled(\"(?)\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(desc);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n }\n\n /// \n /// Renders an input text field with optional validation\n /// \n public static bool ValidatedInputText(\n string label,\n ref string value,\n uint bufferSize,\n string? tooltip = null,\n Func? validator = null)\n {\n var changed = ImGui.InputText(label, ref value, bufferSize);\n\n // Show tooltip if provided\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n // Validate if changed and validator provided\n if ( changed && validator != null )\n {\n var isValid = validator(value);\n if ( !isValid )\n {\n ImGui.SameLine();\n ImGui.TextColored(new Vector4(1, 0, 0, 1), \"!\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.TextUnformatted(\"Invalid input\");\n ImGui.EndTooltip();\n }\n }\n }\n\n return changed;\n }\n\n /// \n /// Renders an input integer field with optional validation and constraints\n /// \n public static bool ValidatedInputInt(\n string label,\n ref int value,\n string? tooltip = null,\n Func? validator = null,\n int? min = null,\n int? max = null)\n {\n var changed = ImGui.InputInt(label, ref value);\n\n // Apply min/max constraints\n if ( changed )\n {\n if ( min.HasValue && value < min.Value )\n {\n value = min.Value;\n }\n\n if ( max.HasValue && value > max.Value )\n {\n value = max.Value;\n }\n }\n\n // Show tooltip if provided\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n // Validate if changed and validator provided\n if ( changed && validator != null )\n {\n var isValid = validator(value);\n if ( !isValid )\n {\n ImGui.SameLine();\n ImGui.TextColored(new Vector4(1, 0, 0, 1), \"!\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.TextUnformatted(\"Invalid input\");\n ImGui.EndTooltip();\n }\n }\n }\n\n return changed;\n }\n\n /// \n /// Renders a float slider with tooltip and optional animation\n /// \n public static bool TooltipSliderFloat(\n string label,\n ref float value,\n float min,\n float max,\n string format = \"%.3f\",\n string? tooltip = null,\n bool animate = false)\n {\n if ( animate )\n {\n // For animated sliders, use a pulsing accent color\n var time = (float)Math.Sin(ImGui.GetTime() * 2.0f) * 0.5f + 0.5f;\n var color = new Vector4(0.1f, 0.4f + time * 0.2f, 0.8f + time * 0.2f, 1.0f);\n ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.3f, 0.3f, 0.3f, 1.0f));\n ImGui.PushStyleColor(ImGuiCol.SliderGrab, color);\n }\n\n var changed = ImGui.SliderFloat(label, ref value, min, max, format);\n\n if ( animate )\n {\n ImGui.PopStyleColor(2);\n }\n\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n return changed;\n }\n\n /// \n /// Renders a collapsible section header\n /// \n /// \n /// Renders a collapsible section header\n /// \n public static bool SectionHeader(string label, bool defaultOpen = true)\n {\n // Define the style colors\n var styleColors = new List<(ImGuiCol, Vector4)> { (ImGuiCol.Header, new Vector4(0.15f, 0.45f, 0.8f, 0.8f)), (ImGuiCol.HeaderHovered, new Vector4(0.2f, 0.5f, 0.9f, 0.8f)), (ImGuiCol.HeaderActive, new Vector4(0.25f, 0.55f, 0.95f, 0.8f)) };\n\n var flags = defaultOpen ? ImGuiTreeNodeFlags.DefaultOpen : ImGuiTreeNodeFlags.None;\n flags |= ImGuiTreeNodeFlags.Framed;\n flags |= ImGuiTreeNodeFlags.SpanAvailWidth;\n flags |= ImGuiTreeNodeFlags.AllowOverlap;\n flags |= ImGuiTreeNodeFlags.FramePadding;\n\n // Use the WithStyleColors method properly - pass the actual rendering logic in the action\n var opened = false;\n WithStyleColors(styleColors, () => { WithStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 6), () => { opened = ImGui.CollapsingHeader(label, flags); }); });\n\n return opened;\n }\n\n /// \n /// Renders a button with animation effects\n /// \n public static bool AnimatedButton(string label, Vector2 size, bool isActive = false)\n {\n bool clicked;\n if ( isActive )\n {\n // Pulse animation for active button\n var time = (float)Math.Sin(ImGui.GetTime() * 2.0f) * 0.5f + 0.5f;\n var color = new Vector4(0.1f, 0.5f + time * 0.3f, 0.9f, 0.7f + time * 0.3f);\n ImGui.PushStyleColor(ImGuiCol.Button, color);\n ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(color.X, color.Y, color.Z, 1.0f));\n ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(color.X * 1.1f, color.Y * 1.1f, color.Z * 1.1f, 1.0f));\n clicked = ImGui.Button(label, size);\n ImGui.PopStyleColor(3);\n }\n else\n {\n // Default stylish button\n // ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.8f, 0.6f));\n // ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.2f, 0.5f, 0.9f, 0.7f));\n // ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.25f, 0.55f, 0.95f, 0.8f));\n clicked = ImGui.Button(label, size);\n }\n\n return clicked;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/ContentVec.cs", "using Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class ContentVec : IDisposable\n{\n private readonly InferenceSession _model;\n\n public ContentVec(string modelPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL,\n };\n\n options.AppendExecutionProvider_CPU();\n\n _model = new InferenceSession(modelPath, options);\n }\n\n public void Dispose() { _model?.Dispose(); }\n\n public DenseTensor Forward(ReadOnlyMemory wav)\n {\n // Create input tensor without unnecessary copying\n var tensor = new DenseTensor(new[] { 1, 1, wav.Length });\n var wavSpan = wav.Span;\n\n if ( wav.Length == 2 )\n {\n // Handle division by 2 for each element\n tensor[0, 0, 0] = wavSpan[0] / 2;\n tensor[0, 0, 1] = wavSpan[1] / 2;\n }\n else\n {\n // Process normally for all other lengths\n for ( var i = 0; i < wav.Length; i++ )\n {\n tensor[0, 0, i] = wavSpan[i];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.First(), tensor) };\n\n using var results = _model.Run(inputs);\n var output = results[0].AsTensor();\n\n // Process the output tensor\n return RVCUtils.Transpose(output, 0, 2, 1);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigEditorComponent.cs", "using System.Numerics;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.Utilities.Text;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// The main configuration editor component with improved architecture and performance\n/// \npublic class ConfigEditorComponent : IRenderComponent\n{\n private readonly IUiConfigurationManager _configManager;\n\n private readonly INotificationService _notificationService;\n\n private readonly IConfigSectionRegistry _sectionRegistry;\n\n private readonly IEditorStateManager _stateManager;\n\n private readonly IUiThemeManager _themeManager;\n\n private bool _isInitialized = false;\n\n public ConfigEditorComponent(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IConfigSectionRegistry sectionRegistry,\n IUiThemeManager themeManager,\n INotificationService notificationService)\n {\n _configManager = configManager ?? throw new ArgumentNullException(nameof(configManager));\n _stateManager = stateManager ?? throw new ArgumentNullException(nameof(stateManager));\n _sectionRegistry = sectionRegistry ?? throw new ArgumentNullException(nameof(sectionRegistry));\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));\n\n // Subscribe to configuration change events\n _configManager.ConfigurationChanged += OnConfigurationChanged;\n\n // Subscribe to state change events\n _stateManager.StateChanged += OnStateChanged;\n }\n\n public void Dispose()\n {\n // Unsubscribe from events\n _configManager.ConfigurationChanged -= OnConfigurationChanged;\n _stateManager.StateChanged -= OnStateChanged;\n\n // Dispose all registered section editors\n foreach ( var section in _sectionRegistry.GetSections() )\n {\n (section as IDisposable)?.Dispose();\n }\n\n GC.SuppressFinalize(this);\n }\n\n #region IRenderComponent Implementation\n\n public bool UseSpout => false;\n\n public string SpoutTarget => string.Empty;\n\n public int Priority => 0;\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n if ( _isInitialized )\n {\n return;\n }\n\n // Apply global UI theme\n _themeManager.ApplyTheme();\n\n // Initialize all registered section editors\n foreach ( var section in _sectionRegistry.GetSections() )\n {\n section.Initialize();\n }\n\n _isInitialized = true;\n }\n\n public void Render(float deltaTime)\n {\n // Set window parameters\n // ImGui.SetNextWindowSize(new Vector2(900, 650), ImGuiCond.FirstUseEver);\n\n // RenderMenuBar();\n\n // Show notification banner if there are unsaved changes\n // if ( _stateManager.HasUnsavedChanges )\n // {\n // RenderUnsavedChangesBanner();\n // }\n\n // Show notifications if present\n // RenderNotifications();\n\n // Render tab bar for sections\n RenderSectionTabs();\n }\n\n public void Update(float deltaTime)\n {\n // Update all registered section editors\n foreach ( var section in _sectionRegistry.GetSections() )\n {\n section.Update(deltaTime);\n }\n\n // Update notification service\n _notificationService.Update(deltaTime);\n }\n\n public void Resize()\n {\n // Not needed for this component\n }\n\n #endregion\n\n #region Private UI Methods\n\n private void RenderMenuBar()\n {\n if ( ImGui.BeginMenuBar() )\n {\n // Render section-specific menu items\n foreach ( var section in _sectionRegistry.GetSections() )\n {\n section.RenderMenuItems();\n }\n\n // Render active operations status on the right side\n RenderStatusIndicators();\n\n ImGui.EndMenuBar();\n }\n }\n\n private void RenderStatusIndicators()\n {\n var activeOperation = _stateManager.GetActiveOperation();\n if ( activeOperation != null )\n {\n var menuWidth = ImGui.GetWindowWidth();\n ImGui.SameLine(menuWidth - 160);\n\n // Display operation name\n ImGui.AlignTextToFramePadding();\n ImGui.Text(activeOperation.Name);\n\n // Animated dots\n var time = (int)(ImGui.GetTime() * 2) % 4;\n for ( var i = 0; i < time; i++ )\n {\n ImGui.SameLine(0, 2);\n ImGui.Text(\".\");\n }\n\n // Progress bar\n ImGui.SameLine();\n ImGui.SetNextItemWidth(100);\n ImGui.ProgressBar(activeOperation.Progress, new Vector2(100, 15), \"\");\n }\n }\n\n private void RenderUnsavedChangesBanner()\n {\n UiStyler.WithStyleColor(ImGuiCol.ChildBg, new Vector4(0.92f, 0.73f, 0.0f, 0.2f), () =>\n {\n UiStyler.WithStyleVar(ImGuiStyleVar.FramePadding, new Vector2(10, 5), () =>\n {\n ImGui.BeginChild(\"UnsavedChangesBar\", new Vector2(ImGui.GetContentRegionAvail().X, 40), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoScrollbar);\n\n ImGui.AlignTextToFramePadding();\n ImGui.TextColored(new Vector4(1, 0.7f, 0, 1), \"You have unsaved changes!\");\n\n ImGui.SameLine(ImGui.GetContentRegionAvail().X - 200);\n\n if ( ImGui.Button(\"Save Changes\", new Vector2(100, 30)) )\n {\n SaveConfiguration();\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"Discard\", new Vector2(80, 30)) )\n {\n ReloadConfiguration();\n }\n\n ImGui.EndChild();\n });\n });\n }\n\n private void RenderNotifications()\n {\n foreach ( var notification in _notificationService.GetActiveNotifications() )\n {\n UiStyler.WithStyleColor(ImGuiCol.ChildBg, notification.GetBackgroundColor(), () =>\n {\n UiStyler.WithStyleVar(ImGuiStyleVar.FramePadding, new Vector2(10, 5), () =>\n {\n ImGui.BeginChild($\"Notification_{notification.Id}\", new Vector2(ImGui.GetContentRegionAvail().X, 40), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoScrollbar);\n\n ImGui.AlignTextToFramePadding();\n ImGui.TextColored(notification.GetTextColor(), notification.Message);\n\n if ( notification.HasAction )\n {\n ImGui.SameLine(ImGui.GetContentRegionAvail().X - 100);\n\n if ( ImGui.Button(notification.ActionLabel, new Vector2(90, 30)) )\n {\n notification.InvokeAction();\n }\n }\n\n ImGui.EndChild();\n });\n });\n }\n }\n\n private unsafe void RenderSectionTabs()\n {\n var sections = _sectionRegistry.GetSections();\n const int bufferSize = 256;\n var buffer = stackalloc byte[bufferSize];\n StrBuilder sb = new(buffer, bufferSize);\n\n foreach ( var section in sections )\n {\n sb.Append(\"ScrollRegion\");\n sb.Append(\"##\");\n sb.Append(section.DisplayName);\n sb.End();\n\n ImGui.SetNextWindowSize(new Vector2(600, 0));\n if ( ImGui.Begin(section.DisplayName, ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoResize) )\n {\n if ( ImGui.CollapsingHeader(section.DisplayName, ImGuiTreeNodeFlags.None) )\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n ImGui.BeginChild(sb, new Vector2(availWidth, 0), ImGuiChildFlags.AutoResizeY, ImGuiWindowFlags.HorizontalScrollbar);\n section.Render();\n ImGui.EndChild();\n }\n }\n\n ImGui.End();\n\n sb.Reset();\n }\n }\n\n #endregion\n\n #region Event Handlers\n\n private void OnConfigurationChanged(object sender, ConfigurationChangedEventArgs e)\n {\n // Notify relevant sections about configuration changes\n foreach ( var section in _sectionRegistry.GetSections() )\n {\n if ( section.SectionKey == e.SectionKey || e.SectionKey == null )\n {\n section.OnConfigurationChanged(e);\n }\n }\n }\n\n private void OnStateChanged(object sender, EditorStateChangedEventArgs e)\n {\n // Handle state changes that affect the main component\n }\n\n #endregion\n\n #region Helper Methods\n\n private void SaveConfiguration()\n {\n try\n {\n _configManager.SaveConfiguration();\n _notificationService.ShowSuccess(\"Configuration saved successfully\");\n }\n catch (Exception ex)\n {\n _notificationService.ShowError($\"Failed to save configuration: {ex.Message}\");\n }\n }\n\n private void ReloadConfiguration()\n {\n try\n {\n _configManager.ReloadConfiguration();\n _notificationService.ShowInfo(\"Configuration reloaded\");\n }\n catch (Exception ex)\n {\n _notificationService.ShowError($\"Failed to reload configuration: {ex.Message}\");\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Adapters/IInputAdapter.cs", "using System.Threading.Channels;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\n\npublic interface IInputAdapter : IAsyncDisposable\n{\n Guid AdapterId { get; }\n \n ParticipantInfo Participant { get; }\n\n ValueTask InitializeAsync(Guid sessionId, ChannelWriter inputWriter, CancellationToken cancellationToken);\n\n ValueTask StartAsync(CancellationToken cancellationToken);\n\n ValueTask StopAsync(CancellationToken cancellationToken);\n}\n\npublic interface IAudioInputAdapter : IInputAdapter\n{\n IAwaitableAudioSource GetAudioSource();\n}\n\npublic interface ITextInputAdapter : IInputAdapter { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismUserModel.cs", "using PersonaEngine.Lib.Live2D.Framework.Effect;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Physics;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// ユーザーが実際に使用するモデルの基底クラス。これを継承してユーザーが実装する。\n/// \npublic abstract class CubismUserModel : IDisposable\n{\n /// \n /// X軸方向の加速度\n /// \n protected float _accelerationX;\n\n /// \n /// Y軸方向の加速度\n /// \n protected float _accelerationY;\n\n /// \n /// Z軸方向の加速度\n /// \n protected float _accelerationZ;\n\n /// \n /// 呼吸\n /// \n protected CubismBreath _breath;\n\n /// \n /// マウスドラッグ\n /// \n protected CubismTargetPoint _dragManager;\n\n /// \n /// マウスドラッグのX位置\n /// \n protected float _dragX;\n\n /// \n /// マウスドラッグのY位置\n /// \n protected float _dragY;\n\n /// \n /// 表情管理\n /// \n protected CubismExpressionMotionManager _expressionManager;\n\n /// \n /// 自動まばたき\n /// \n protected CubismEyeBlink? _eyeBlink;\n\n /// \n /// 最後のリップシンクの制御値\n /// \n protected float _lastLipSyncValue;\n\n /// \n /// リップシンクするかどうか\n /// \n protected bool _lipSync;\n\n /// \n /// Mocデータ\n /// \n protected CubismMoc _moc;\n\n /// \n /// MOC3整合性検証するかどうか\n /// \n protected bool _mocConsistency;\n\n /// \n /// ユーザデータ\n /// \n protected CubismModelUserData? _modelUserData;\n\n /// \n /// モーション管理\n /// \n protected CubismMotionManager _motionManager;\n\n /// \n /// 物理演算\n /// \n protected CubismPhysics? _physics;\n\n /// \n /// ポーズ管理\n /// \n protected CubismPose? _pose;\n\n /// \n /// コンストラクタ。\n /// \n public CubismUserModel()\n {\n _lipSync = true;\n\n Opacity = 1.0f;\n\n // モーションマネージャーを作成\n // MotionQueueManagerクラスからの継承なので使い方は同じ\n _motionManager = new CubismMotionManager();\n _motionManager.SetEventCallback(CubismDefaultMotionEventCallback, this);\n\n // 表情モーションマネージャを作成\n _expressionManager = new CubismExpressionMotionManager();\n\n // ドラッグによるアニメーション\n _dragManager = new CubismTargetPoint();\n }\n\n /// \n /// レンダラ\n /// \n public CubismRenderer? Renderer { get; private set; }\n\n /// \n /// モデル行列\n /// \n public CubismModelMatrix ModelMatrix { get; protected set; }\n\n /// \n /// Modelインスタンス\n /// \n public CubismModel Model => _moc.Model;\n\n /// \n /// 初期化されたかどうか\n /// \n public bool Initialized { get; set; }\n\n /// \n /// 更新されたかどうか\n /// \n public bool Updating { get; set; }\n\n /// \n /// 不透明度\n /// \n public float Opacity { get; set; }\n\n public void Dispose()\n {\n _moc.Dispose();\n\n DeleteRenderer();\n }\n\n /// \n /// CubismMotionQueueManagerにイベント用に登録するためのCallback。\n /// CubismUserModelの継承先のEventFiredを呼ぶ。\n /// \n /// 発火したイベントの文字列データ\n /// CubismUserModelを継承したインスタンスを想定\n public static void CubismDefaultMotionEventCallback(CubismUserModel? customData, string eventValue) { customData?.MotionEventFired(eventValue); }\n\n /// \n /// マウスドラッグの情報を設定する。\n /// \n /// ドラッグしているカーソルのX位置\n /// ドラッグしているカーソルのY位置\n public void SetDragging(float x, float y) { _dragManager.Set(x, y); }\n\n /// \n /// 加速度の情報を設定する。\n /// \n /// X軸方向の加速度\n /// Y軸方向の加速度\n /// Z軸方向の加速度\n protected void SetAcceleration(float x, float y, float z)\n {\n _accelerationX = x;\n _accelerationY = y;\n _accelerationZ = z;\n }\n\n /// \n /// モデルデータを読み込む。\n /// \n /// moc3ファイルが読み込まれているバッファ\n /// MOCの整合性チェックフラグ(初期値 : false)\n protected void LoadModel(byte[] buffer, bool shouldCheckMocConsistency = false)\n {\n _moc = new CubismMoc(buffer, shouldCheckMocConsistency);\n Model.SaveParameters();\n ModelMatrix = new CubismModelMatrix(Model.GetCanvasWidth(), Model.GetCanvasHeight());\n }\n\n /// \n /// ポーズデータを読み込む。\n /// \n /// pose3.jsonが読み込まれているバッファ\n protected void LoadPose(string buffer) { _pose = new CubismPose(buffer); }\n\n /// \n /// 物理演算データを読み込む。\n /// \n /// physics3.jsonが読み込まれているバッファ\n protected void LoadPhysics(string buffer) { _physics = new CubismPhysics(buffer); }\n\n /// \n /// ユーザーデータを読み込む。\n /// \n /// userdata3.jsonが読み込まれているバッファ\n protected void LoadUserData(string buffer) { _modelUserData = new CubismModelUserData(buffer); }\n\n /// \n /// 指定した位置にDrawableがヒットしているかどうかを取得する。\n /// \n /// 検証したいDrawableのID\n /// X位置\n /// Y位置\n /// \n /// true ヒットしている\n /// false ヒットしていない\n /// \n public unsafe bool IsHit(string drawableId, float pointX, float pointY)\n {\n var drawIndex = Model.GetDrawableIndex(drawableId);\n\n if ( drawIndex < 0 )\n {\n return false; // 存在しない場合はfalse\n }\n\n var count = Model.GetDrawableVertexCount(drawIndex);\n var vertices = Model.GetDrawableVertices(drawIndex);\n\n var left = vertices[0];\n var right = vertices[0];\n var top = vertices[1];\n var bottom = vertices[1];\n\n for ( var j = 1; j < count; ++j )\n {\n var x = vertices[CubismFramework.VertexOffset + j * CubismFramework.VertexStep];\n var y = vertices[CubismFramework.VertexOffset + j * CubismFramework.VertexStep + 1];\n\n if ( x < left )\n {\n left = x; // Min x\n }\n\n if ( x > right )\n {\n right = x; // Max x\n }\n\n if ( y < top )\n {\n top = y; // Min y\n }\n\n if ( y > bottom )\n {\n bottom = y; // Max y\n }\n }\n\n var tx = ModelMatrix.InvertTransformX(pointX);\n var ty = ModelMatrix.InvertTransformY(pointY);\n\n return left <= tx && tx <= right && top <= ty && ty <= bottom;\n }\n\n /// \n /// レンダラを生成して初期化を実行する。\n /// \n protected void CreateRenderer(CubismRenderer renderer)\n {\n if ( Renderer != null )\n {\n DeleteRenderer();\n }\n\n Renderer = renderer;\n }\n\n /// \n /// レンダラを解放する。\n /// \n protected void DeleteRenderer()\n {\n if ( Renderer != null )\n {\n Renderer.Dispose();\n Renderer = null;\n }\n }\n\n /// \n /// Eventが再生処理時にあった場合の処理をする。\n /// 継承で上書きすることを想定している。\n /// 上書きしない場合はログ出力をする。\n /// \n /// 発火したイベントの文字列データ\n protected abstract void MotionEventFired(string eventValue);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnx.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnx : IF0Predictor\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n private readonly float[] _inputBatchBuffer;\n\n // Preallocated buffers for zero-allocation processing\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Additional preallocated buffers for Viterbi decoding\n private readonly float[,] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[,] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[,] _transitionMatrix;\n\n private readonly float[,] _transOutBuffer;\n\n private readonly float[,] _valueBuffer;\n\n private readonly float[] _windowBuffer;\n\n public CrepeOnnx(string modelPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Preallocate buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _windowBuffer = new float[WINDOW_SIZE];\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Preallocate Viterbi algorithm buffers\n _logProbBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE, PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = CreateTransitionMatrix();\n _transOutBuffer = new float[PITCH_BINS, PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n\n // Initialize _logPInitBuffer with equal probabilities\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _logPInitBuffer[i] = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n }\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n var wavSpan = wav.Span;\n var outputSpan = f0Output.Span;\n\n if ( length > outputSpan.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Preallocate periodicity data buffer\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = new Span(pdBuffer, 0, length);\n\n // Process the audio to extract F0\n Crepe(wavSpan, outputSpan.Slice(0, length), pdSpan);\n\n // Apply post-processing\n for ( var i = 0; i < length; i++ )\n {\n if ( pdSpan[i] < 0.1 )\n {\n outputSpan[i] = 0;\n }\n }\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var total_frames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < total_frames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, total_frames - b);\n\n // Fill the batch input buffer\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame\n Normalize(frame);\n }\n\n private void Normalize(Span input)\n {\n // Mean center and scale\n float sum = 0;\n for ( var j = 0; j < input.Length; j++ )\n {\n sum += input[j];\n }\n\n var mean = sum / input.Length;\n float stdValue = 0;\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] - mean;\n stdValue += input[j] * input[j];\n }\n\n stdValue = stdValue / input.Length;\n stdValue = (float)Math.Sqrt(stdValue);\n\n if ( stdValue < 1e-10 )\n {\n stdValue = 1e-10f;\n }\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] / stdValue;\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor\n for ( var i = 0; i < batchSize; i++ )\n {\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[i * WINDOW_SIZE + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Remove frequencies outside of allowable range\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n for ( var t = 0; t < outputSize; t++ )\n {\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n if ( i < minidx || i >= maxidx )\n {\n probabilities[t * PITCH_BINS + i] = float.NegativeInfinity;\n }\n }\n }\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0, pd, outputSize, offset);\n }\n\n private void DecodeViterbi(float[] probabilities, Span f0, Span pd, int nSteps, int offset)\n {\n // Transfer probabilities to log_prob buffer and apply softmax\n for ( var i = 0; i < nSteps * PITCH_BINS; i++ )\n {\n _logProbBuffer[i / PITCH_BINS, i % PITCH_BINS] = probabilities[i];\n }\n\n Softmax(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n for ( var y = 0; y < nSteps; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _logProbBuffer[y, x] = (float)Math.Log(_logProbBuffer[y, x] + float.Epsilon);\n }\n }\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[0, i] = _logProbBuffer[0, i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm\n for ( var t = 1; t < nSteps; t++ )\n {\n // Calculate transition outputs\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _transOutBuffer[y, x] = _valueBuffer[t - 1, x] + _transitionMatrix[x, y]; // Transposed matrix\n }\n }\n\n for ( var j = 0; j < PITCH_BINS; j++ )\n {\n // Find argmax\n var maxI = 0;\n var maxProb = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb < _transOutBuffer[j, k] )\n {\n maxProb = _transOutBuffer[j, k];\n maxI = k;\n }\n }\n\n _ptrBuffer[t, j] = maxI;\n _valueBuffer[t, j] = _logProbBuffer[t, j] + _transOutBuffer[j, _ptrBuffer[t, j]];\n }\n }\n\n // Find the most likely final state\n var maxI2 = 0;\n var maxProb2 = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb2 < _valueBuffer[nSteps - 1, k] )\n {\n maxProb2 = _valueBuffer[nSteps - 1, k];\n maxI2 = k;\n }\n }\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI2;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[t + 1, _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values\n for ( var t = 0; t < nSteps; t++ )\n {\n var bins = _stateBuffer[t];\n var periodicity = Periodicity(probabilities, t, bins);\n var frequency = ConvertToFrequency(bins);\n\n if ( offset + t < f0.Length )\n {\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n }\n\n private void Softmax(float[,] data, int nSteps)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n sum += (float)Math.Exp(data[t, i]);\n }\n\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[t, i] = (float)Math.Exp(data[t, i]) / sum;\n }\n }\n }\n\n private float[,] CreateTransitionMatrix()\n {\n var transition = new float[PITCH_BINS, PITCH_BINS];\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n var v = 12 - Math.Abs(x - y);\n if ( v < 0 )\n {\n v = 0;\n }\n\n transition[y, x] = v;\n sum += v;\n }\n\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n transition[y, x] = transition[y, x] / sum;\n\n // Pre-apply log to the transition matrix for efficiency\n transition[y, x] = (float)Math.Log(transition[y, x] + float.Epsilon);\n }\n }\n\n return transition;\n }\n\n private float Periodicity(float[] probabilities, int t, int bins) { return probabilities[t * PITCH_BINS + bins]; }\n\n private float ConvertToFrequency(int bin)\n {\n float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n var frequency = 10 * (float)Math.Pow(2, cents / 1200);\n\n return frequency;\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n // Fill the window buffer\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n _medianBuffer[j] = original[k];\n }\n\n // Sort the window\n Array.Sort(_medianBuffer, 0, windowSize);\n\n // Set the median value\n data[i] = _medianBuffer[windowSize / 2];\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n float sum = 0;\n\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n sum += original[k];\n }\n\n // Set the mean value\n data[i] = sum / windowSize;\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/MicrophoneConfigEditor.cs", "using System.Diagnostics;\nusing System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for Microphone section configuration.\n/// Allows selection of the audio input device.\n/// \npublic class MicrophoneConfigEditor : ConfigSectionEditorBase\n{\n private const string DefaultDeviceDisplayName = \"(Default Device)\"; // Display name for null/empty device\n\n // --- Dependencies ---\n private readonly IMicrophone _microphone; // Dependency to get device list\n\n private List _availableDevices = new();\n\n // --- State ---\n private MicrophoneConfiguration _currentConfig;\n\n private bool _loadingDevices = false;\n\n private string? _selectedDeviceName; // Can be null for default device\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The configuration manager.\n /// The editor state manager.\n /// The microphone service.\n public MicrophoneConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IMicrophone microphone)\n : base(configManager, stateManager)\n {\n _microphone = microphone ?? throw new ArgumentNullException(nameof(microphone));\n\n // Load initial configuration\n LoadConfiguration();\n }\n\n // --- ConfigSectionEditorBase Implementation ---\n\n /// \n /// Gets the key for the configuration section managed by this editor.\n /// \n public override string SectionKey => \"Microphone\"; // Or your specific key\n\n /// \n /// Gets the display name for this editor section.\n /// \n public override string DisplayName => \"Microphone Settings\";\n\n /// \n /// Initializes the editor, loading necessary data like available devices.\n /// \n public override void Initialize()\n {\n LoadAvailableDevices(); // Load devices on initialization\n }\n\n /// \n /// Renders the ImGui UI for the microphone configuration.\n /// \n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // --- Device Selection Section ---\n ImGui.Spacing();\n ImGui.SeparatorText(\"Input Device Selection\");\n ImGui.Spacing();\n\n ImGui.BeginGroup(); // Group controls for alignment\n {\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Input Device:\");\n ImGui.SameLine(120); // Adjust spacing as needed\n\n // Combo box for device selection\n ImGui.SetNextItemWidth(availWidth - 120 - 100); // Width calculation: Available - Label - Refresh Button\n\n var currentSelectionDisplay = string.IsNullOrEmpty(_selectedDeviceName)\n ? DefaultDeviceDisplayName\n : _selectedDeviceName;\n\n if ( _loadingDevices )\n {\n // Show loading state\n ImGui.BeginDisabled();\n var loadingText = \"Loading devices...\";\n // Use InputText as a visual placeholder during loading\n ImGui.InputText(\"##DeviceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n // Actual combo box\n if ( ImGui.BeginCombo(\"##DeviceSelector\", currentSelectionDisplay) )\n {\n // Add \"(Default Device)\" option first\n var isDefaultSelected = string.IsNullOrEmpty(_selectedDeviceName);\n if ( ImGui.Selectable(DefaultDeviceDisplayName, isDefaultSelected) )\n {\n if ( _selectedDeviceName != null ) // Check if changed\n {\n _selectedDeviceName = null;\n UpdateConfiguration();\n }\n }\n\n if ( isDefaultSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n\n // Add actual devices if available\n if ( _availableDevices.Count == 0 && !_loadingDevices )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No input devices found.\");\n }\n else\n {\n foreach ( var device in _availableDevices )\n {\n var isSelected = device == _selectedDeviceName;\n if ( ImGui.Selectable(device, isSelected) )\n {\n if ( _selectedDeviceName != device ) // Check if changed\n {\n _selectedDeviceName = device;\n UpdateConfiguration();\n }\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n // Refresh Button\n ImGui.SameLine(0, 10); // Add spacing before button\n if ( ImGui.Button(\"Refresh##Dev\", new Vector2(80, 0)) ) // Unique ID for button\n {\n LoadAvailableDevices();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh the list of available input devices.\");\n }\n }\n\n ImGui.EndGroup(); // End device selection group\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n // --- Action Buttons ---\n // Center the buttons roughly\n float buttonWidth = 150;\n var totalButtonWidth = buttonWidth * 2 + 10; // Two buttons + spacing\n var initialPadding = (availWidth - totalButtonWidth) * 0.5f;\n if ( initialPadding < 0 )\n {\n initialPadding = 0;\n }\n\n ImGui.SetCursorPosX(initialPadding);\n\n // Reset Button\n if ( ImGui.Button(\"Reset\", new Vector2(buttonWidth, 0)) )\n {\n ResetToDefaults();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset microphone settings to default values.\");\n }\n\n ImGui.SameLine(0, 10); // Spacing between buttons\n\n // Save Button (Disabled if no changes)\n var hasChanges = StateManager.HasUnsavedChanges; // Check unsaved state\n if ( !hasChanges )\n {\n ImGui.BeginDisabled();\n }\n\n if ( ImGui.Button(\"Save\", new Vector2(buttonWidth, 0)) )\n {\n SaveConfiguration();\n }\n\n if ( ImGui.IsItemHovered() && hasChanges )\n {\n ImGui.SetTooltip(\"Save the current microphone settings.\");\n }\n\n if ( !hasChanges )\n {\n ImGui.EndDisabled();\n }\n }\n\n /// \n /// Updates the editor state (currently unused for this simple editor).\n /// \n /// Time elapsed since the last frame.\n public override void Update(float deltaTime)\n {\n // No per-frame update logic needed for this editor yet\n }\n\n /// \n /// Handles configuration changes, reloading if necessary.\n /// \n /// Event arguments containing change details.\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args); // Call base implementation\n\n // Reload configuration if the source indicates a full reload\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n // Optionally reload devices if the config might affect them,\n // though usually device list is independent of config.\n // LoadAvailableDevices();\n }\n }\n\n /// \n /// Disposes resources used by the editor (currently none specific).\n /// \n public override void Dispose()\n {\n // Unsubscribe from events if any were added\n base.Dispose(); // Call base implementation\n }\n\n // --- Configuration Management ---\n\n /// \n /// Loads the microphone configuration from the configuration manager.\n /// \n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(SectionKey)\n ?? new MicrophoneConfiguration(); // Get or create default\n\n // Update local state from loaded config\n _selectedDeviceName = _currentConfig.DeviceName;\n\n // Ensure the UI reflects the loaded state without marking as changed initially\n MarkAsSaved(); // Reset change tracking after loading\n }\n\n /// \n /// Fetches the list of available microphone devices.\n /// \n private void LoadAvailableDevices()\n {\n if ( _loadingDevices )\n {\n return; // Prevent concurrent loading\n }\n\n try\n {\n _loadingDevices = true;\n // Consider adding an ActiveOperation to StateManager if this takes time\n // var operation = new ActiveOperation(\"load-mic-devices\", \"Loading Microphones\");\n // StateManager.RegisterActiveOperation(operation);\n\n // Get devices using the injected service\n _availableDevices = _microphone.GetAvailableDevices().ToList();\n\n // Ensure the currently selected device still exists\n if ( !string.IsNullOrEmpty(_selectedDeviceName) &&\n !_availableDevices.Contains(_selectedDeviceName) )\n {\n Debug.WriteLine($\"Warning: Configured microphone '{_selectedDeviceName}' not found. Reverting to default.\");\n // Optionally notify the user here\n _selectedDeviceName = null; // Revert to default\n UpdateConfiguration(); // Update the config state\n }\n\n // StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading microphone devices: {ex.Message}\");\n _availableDevices = new List(); // Clear list on error\n // Optionally show an error message to the user via ImGui or logging\n }\n finally\n {\n _loadingDevices = false;\n }\n }\n\n /// \n /// Updates the configuration object and notifies the manager.\n /// \n private void UpdateConfiguration()\n {\n // Create the updated configuration record\n var updatedConfig = _currentConfig with // Use record 'with' expression\n {\n DeviceName = _selectedDeviceName\n };\n\n // Check if the configuration actually changed before updating\n if ( !_currentConfig.Equals(updatedConfig) )\n {\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(_currentConfig, SectionKey);\n MarkAsChanged(); // Mark that there are unsaved changes\n }\n }\n\n /// \n /// Saves the current configuration changes.\n /// \n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved(); // Mark changes as saved\n }\n\n /// \n /// Resets the microphone configuration to default values.\n /// \n private void ResetToDefaults()\n {\n var defaultConfig = new MicrophoneConfiguration(); // Create default config\n\n // Update local state\n _selectedDeviceName = defaultConfig.DeviceName; // Should be null\n\n // Update configuration only if it differs from current\n if ( !_currentConfig.Equals(defaultConfig) )\n {\n _currentConfig = defaultConfig;\n ConfigManager.UpdateConfiguration(_currentConfig, SectionKey);\n MarkAsChanged(); // Mark changes needing save\n }\n else\n {\n // If already default, just ensure saved state is correct\n MarkAsSaved();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/KokoroVoiceProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Voice provider implementation to manage voice embeddings\n/// \npublic class KokoroVoiceProvider : IKokoroVoiceProvider\n{\n private readonly ITtsCache _cache;\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly ConcurrentDictionary _voicePaths = new();\n\n private bool _disposed;\n\n public KokoroVoiceProvider(\n IModelProvider ittsModelProvider,\n ITtsCache cache,\n ILogger logger)\n {\n _modelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _cache = cache ?? throw new ArgumentNullException(nameof(cache));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n public async Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(voiceId) )\n {\n throw new ArgumentException(\"Voice ID cannot be null or empty\", nameof(voiceId));\n }\n\n try\n {\n // Use cache to avoid repeated loading\n return await _cache.GetOrAddAsync($\"voice_{voiceId}\", async ct =>\n {\n _logger.LogDebug(\"Loading voice data for {VoiceId}\", voiceId);\n\n // Get voice directory\n var voiceDirPath = await GetVoicePathAsync(voiceId, ct);\n\n // Load binary data\n var bytes = await File.ReadAllBytesAsync(voiceDirPath, ct);\n\n // Convert to float array\n var embedding = new float[bytes.Length / sizeof(float)];\n Buffer.BlockCopy(bytes, 0, embedding, 0, bytes.Length);\n\n _logger.LogInformation(\"Loaded voice {VoiceId} with {EmbeddingSize} embedding dimensions\",\n voiceId, embedding.Length);\n\n return new VoiceData(voiceId, embedding);\n }, cancellationToken);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading voice {VoiceId}\", voiceId);\n\n throw;\n }\n }\n\n /// \n public async Task> GetAvailableVoicesAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n // Get voice directory\n var model = await _modelProvider.GetModelAsync(ModelType.KokoroVoices, cancellationToken);\n var voicesDir = model.Path;\n\n if ( !Directory.Exists(voicesDir) )\n {\n _logger.LogWarning(\"Voices directory not found: {Path}\", voicesDir);\n\n return Array.Empty();\n }\n\n // Get all .bin files\n var voiceFiles = Directory.GetFiles(voicesDir, \"*.bin\");\n\n // Extract voice IDs from filenames\n var voiceIds = new List(voiceFiles.Length);\n\n foreach ( var file in voiceFiles )\n {\n var voiceId = Path.GetFileNameWithoutExtension(file);\n voiceIds.Add(voiceId);\n\n // Cache the path for faster lookup\n _voicePaths[voiceId] = file;\n }\n\n _logger.LogInformation(\"Found {Count} available Kokoro voices\", voiceIds.Count);\n\n return voiceIds;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available voices\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voicePaths.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Gets the file path for a voice\n /// \n private async Task GetVoicePathAsync(string voiceId, CancellationToken cancellationToken)\n {\n // Check if path is cached\n if ( _voicePaths.TryGetValue(voiceId, out var cachedPath) )\n {\n return cachedPath;\n }\n\n // Get base directory\n var model = await _modelProvider.GetModelAsync(ModelType.KokoroVoices, cancellationToken);\n var voicesDir = model.Path;\n\n // Build path\n var voicePath = Path.Combine(voicesDir, $\"{voiceId}.bin\");\n\n // Check if file exists\n if ( !File.Exists(voicePath) )\n {\n _logger.LogWarning(\"Voice file not found: {Path}\", voicePath);\n\n throw new FileNotFoundException($\"Voice file not found for {voiceId}\", voicePath);\n }\n\n // Cache the path\n _voicePaths[voiceId] = voicePath;\n\n return voicePath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SliceAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\npublic readonly struct SliceAudioSource : IAudioSource\n{\n private readonly long frameStart;\n\n private readonly int maxSliceFrames;\n\n private readonly IAudioSource audioSource;\n\n private readonly TimeSpan startTime;\n\n private readonly TimeSpan maxDuration;\n\n public uint SampleRate { get; }\n\n /// \n /// Gets the total number of frames in the stream\n /// \n /// \n /// This can be more than actual number of frames in the source if the source is not big enough.\n /// \n public long FramesCount => (long)(Duration.TotalMilliseconds * SampleRate / 1000);\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration\n {\n get\n {\n var maxSourceDuration = audioSource.TotalDuration - startTime;\n\n return maxSourceDuration > maxDuration ? maxDuration : maxSourceDuration;\n }\n }\n\n public TimeSpan TotalDuration => Duration;\n\n /// \n /// Creates a slice of an audio source (without copying the audio data).\n /// \n public SliceAudioSource(IAudioSource audioSource, TimeSpan startTime, TimeSpan maxDuration)\n {\n frameStart = (long)(startTime.TotalMilliseconds * audioSource.SampleRate / 1000);\n maxSliceFrames = (int)(maxDuration.TotalMilliseconds * audioSource.SampleRate / 1000);\n SampleRate = audioSource.SampleRate;\n\n if ( startTime >= audioSource.Duration )\n {\n throw new ArgumentOutOfRangeException(nameof(startTime), $\"The start time is beyond the end of the audio source. Start time: {startTime}, Source Duration: {audioSource.Duration}\");\n }\n\n ChannelCount = audioSource.ChannelCount;\n BitsPerSample = audioSource.BitsPerSample;\n this.audioSource = audioSource;\n this.maxDuration = maxDuration;\n Metadata = audioSource.Metadata;\n this.startTime = startTime;\n }\n\n public void Dispose() { }\n\n public Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var adjustedMax = (int)Math.Min(maxFrames, maxSliceFrames - startFrame);\n\n return audioSource.GetFramesAsync(startFrame + frameStart, adjustedMax, cancellationToken);\n }\n\n public Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var adjustedMax = (int)Math.Min(maxFrames, maxSliceFrames - startFrame);\n\n return audioSource.GetSamplesAsync(startFrame + frameStart, adjustedMax, cancellationToken);\n }\n\n public Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var adjustedMax = (int)Math.Min(maxFrames, maxSliceFrames - startFrame);\n\n return audioSource.CopyFramesAsync(destination, startFrame + frameStart, adjustedMax, cancellationToken);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/EmbeddedResource.cs", "using System.Collections.Concurrent;\nusing System.ComponentModel;\n\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib;\n\ninternal static class ModelUtils\n{\n public static string GetModelPath(ModelType modelType)\n {\n var enumDescription = modelType.GetDescription();\n var fullPath = Path.Combine(Directory.GetCurrentDirectory(), \"Resources\", \"Models\", $\"{enumDescription}\");\n\n // Check file or dir exists\n if ( !Path.Exists(fullPath) )\n {\n throw new ApplicationException($\"For {modelType} path {fullPath} doesn't exist\");\n }\n\n return fullPath;\n }\n}\n\ninternal static class PromptUtils\n{\n private static readonly ConcurrentDictionary PromptCache = new();\n\n private static string GetModelPath(string filename)\n {\n var fullPath = Path.Combine(Directory.GetCurrentDirectory(), \"Resources\", \"Prompts\", filename);\n\n if ( !File.Exists(fullPath) )\n {\n throw new ApplicationException($\"Prompt file '{filename}' not found at path: {fullPath}\");\n }\n\n return fullPath;\n }\n\n public static bool TryGetPrompt(string filename, out string? prompt)\n {\n if ( PromptCache.TryGetValue(filename, out prompt) )\n {\n return true;\n }\n\n try\n {\n var fullPath = GetModelPath(filename);\n var promptContent = File.ReadAllText(fullPath);\n PromptCache.AddOrUpdate(filename, promptContent, (_, _) => promptContent);\n prompt = promptContent;\n\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n public static void ClearCache() { PromptCache.Clear(); }\n}\n\npublic enum ModelType\n{\n [Description(\"silero_vad_v5.onnx\")] Silero,\n\n [Description(\"ggml-large-v3-turbo.bin\")]\n WhisperGgmlTurbov3,\n\n [Description(\"ggml-tiny.en.bin\")] WhisperGgmlTiny,\n\n [Description(\"badwords.txt\")] BadWords,\n\n [Description(\"tiny_toxic_detector.onnx\")]\n TinyToxic,\n\n [Description(\"tiny_toxic_detector_vocab.txt\")]\n TinyToxicVocab\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/WhisperNetSpeechTranscriptorFactory.cs", "using System.Globalization;\n\nusing PersonaEngine.Lib.Configuration;\n\nusing Whisper.net;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic sealed class WhisperSpeechTranscriptorFactory : ISpeechTranscriptorFactory\n{\n private readonly WhisperProcessorBuilder builder;\n\n private readonly WhisperFactory? whisperFactory;\n\n public WhisperSpeechTranscriptorFactory(WhisperFactory factory, bool dispose = true)\n {\n builder = factory.CreateBuilder();\n if ( dispose )\n {\n whisperFactory = factory;\n }\n }\n\n public WhisperSpeechTranscriptorFactory(WhisperProcessorBuilder builder) { this.builder = builder; }\n\n public WhisperSpeechTranscriptorFactory(string modelFileName)\n {\n whisperFactory = WhisperFactory.FromPath(modelFileName);\n builder = whisperFactory.CreateBuilder();\n }\n\n public ISpeechTranscriptor Create(SpeechTranscriptorOptions options)\n {\n var currentBuilder = builder;\n if ( options.Prompt != null )\n {\n currentBuilder = currentBuilder.WithPrompt(options.Prompt);\n }\n\n if ( options.LanguageAutoDetect )\n {\n currentBuilder = currentBuilder.WithLanguage(\"auto\");\n }\n else\n {\n currentBuilder = currentBuilder.WithLanguage(ToWhisperLanguage(options.Language));\n }\n\n if ( options.RetrieveTokenDetails )\n {\n currentBuilder = currentBuilder.WithTokenTimestamps();\n }\n \n if ( options.Template != null )\n {\n currentBuilder = currentBuilder.ApplyTemplate(options.Template.Value);\n }\n\n var processor = currentBuilder.Build();\n\n return new WhisperNetSpeechTranscriptor(processor);\n }\n\n public void Dispose() { whisperFactory?.Dispose(); }\n\n private static string ToWhisperLanguage(CultureInfo languageCode)\n {\n if ( !WhisperNetSupportedLanguage.IsSupported(languageCode) )\n {\n throw new NotSupportedException($\"The language provided as: {languageCode.ThreeLetterISOLanguageName} is not supported by Whisper.net.\");\n }\n\n return languageCode.TwoLetterISOLanguageName;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/TimedPlaybackController.cs", "using System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Implementation of IPlaybackController that works with large audio segments.\n/// \npublic class TimedPlaybackController : IPlaybackController\n{\n private readonly int _initialBufferMs;\n\n private readonly double _latencyThresholdMs;\n\n private readonly ILogger _logger;\n\n private readonly Stopwatch _playbackTimer = new();\n\n // For time updates\n private readonly object _timeLock = new();\n\n private readonly int _timeUpdateIntervalMs;\n\n private readonly Timer _timeUpdateTimer;\n\n // Latency tracking\n\n private int _currentSampleRate;\n\n private double _lastReportedLatencyMs;\n\n private long _startTimeMs; // When playback actually started (system time)\n\n /// \n /// Initializes a new instance of the TimedPlaybackController class.\n /// \n /// Initial buffer size in milliseconds.\n /// Threshold for significant latency changes in milliseconds.\n /// Interval in milliseconds for time updates.\n /// Logger instance.\n public TimedPlaybackController(\n int initialBufferMs = 20,\n double latencyThresholdMs = 20.0,\n int timeUpdateIntervalMs = 20,\n ILogger? logger = null)\n {\n _initialBufferMs = initialBufferMs;\n _latencyThresholdMs = latencyThresholdMs;\n _timeUpdateIntervalMs = timeUpdateIntervalMs;\n _logger = logger ?? NullLogger.Instance;\n\n // Start a timer to update the playback time periodically\n _timeUpdateTimer = new Timer(UpdateTime, null, Timeout.Infinite, Timeout.Infinite);\n }\n\n /// \n public float CurrentTime { get; private set; }\n\n /// \n public long TotalSamplesPlayed { get; private set; }\n\n /// \n public double CurrentLatencyMs { get; private set; }\n\n /// \n public bool HasLatencyInformation { get; private set; }\n\n /// \n /// Event that fires when the playback time changes substantially.\n /// \n public event EventHandler TimeChanged\n {\n add\n {\n lock (_timeLock)\n {\n TimeChangedInternal += value;\n }\n }\n remove\n {\n lock (_timeLock)\n {\n TimeChangedInternal -= value;\n }\n }\n }\n\n /// \n public event EventHandler? LatencyChanged;\n\n /// \n public void Reset()\n {\n _playbackTimer.Reset();\n TotalSamplesPlayed = 0;\n CurrentTime = 0;\n _startTimeMs = 0;\n\n // Stop the time update timer\n _timeUpdateTimer.Change(Timeout.Infinite, Timeout.Infinite);\n }\n\n /// \n public void UpdateLatency(double latencyMs)\n {\n var oldLatency = CurrentLatencyMs;\n CurrentLatencyMs = latencyMs;\n HasLatencyInformation = true;\n\n // Only notify if the change is significant\n if ( Math.Abs(latencyMs - _lastReportedLatencyMs) >= _latencyThresholdMs )\n {\n _logger.LogInformation(\"Playback latency updated: {OldLatency:F1}ms -> {NewLatency:F1}ms\",\n oldLatency, latencyMs);\n\n _lastReportedLatencyMs = latencyMs;\n LatencyChanged?.Invoke(this, latencyMs);\n }\n }\n\n /// \n public Task SchedulePlaybackAsync(int samplesPerChannel, int sampleRate, CancellationToken cancellationToken)\n {\n // Store the sample rate for time calculations\n _currentSampleRate = sampleRate;\n\n // Update total samples\n TotalSamplesPlayed += samplesPerChannel;\n\n // Start the playback timer if this is the first call\n if ( !_playbackTimer.IsRunning )\n {\n _logger.LogDebug(\"Starting playback timer\");\n\n // Account for initial buffering\n var initialBufferMs = HasLatencyInformation\n ? Math.Max(50, _initialBufferMs + CurrentLatencyMs)\n : _initialBufferMs;\n\n // Record when playback will actually start (now + buffer)\n _startTimeMs = Environment.TickCount64 + (long)initialBufferMs;\n\n // Start the stopwatch for measuring elapsed time\n _playbackTimer.Start();\n\n // Start the timer to update current time periodically\n _timeUpdateTimer.Change(_timeUpdateIntervalMs, _timeUpdateIntervalMs);\n }\n\n // Always send the data - the transport will handle chunking\n return Task.FromResult(true);\n }\n\n /// \n /// Disposes resources used by the controller.\n /// \n public void Dispose() { _timeUpdateTimer.Dispose(); }\n\n private event EventHandler? TimeChangedInternal;\n\n // Private methods\n\n private void UpdateTime(object? state)\n {\n if ( !_playbackTimer.IsRunning || _currentSampleRate <= 0 )\n {\n return;\n }\n\n // Calculate current system time\n var currentTimeMs = Environment.TickCount64;\n\n // Calculate how much time has passed since playback started\n var elapsedSinceStartMs = currentTimeMs > _startTimeMs\n ? currentTimeMs - _startTimeMs\n : 0;\n\n // Apply latency adjustment if available\n var adjustedElapsedMs = HasLatencyInformation\n ? elapsedSinceStartMs - CurrentLatencyMs\n : elapsedSinceStartMs;\n\n // Don't allow negative time\n adjustedElapsedMs = Math.Max(0, adjustedElapsedMs);\n\n // Convert to seconds\n var newPlaybackTime = (float)(adjustedElapsedMs / 1000.0);\n\n // Only update and notify if the time changed significantly\n if ( Math.Abs(newPlaybackTime - CurrentTime) >= 0.01f ) // 10ms threshold\n {\n CurrentTime = newPlaybackTime;\n\n EventHandler? handler;\n lock (_timeLock)\n {\n handler = TimeChangedInternal;\n }\n\n handler?.Invoke(this, newPlaybackTime);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/IConversationCleanupStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic interface IConversationCleanupStrategy\n{\n bool Cleanup(List history, ConversationContextOptions options, IReadOnlyDictionary participants);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleSegment.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Represents a processed audio segment, broken down into lines and words\n/// with calculated timing and layout information ready for the timeline.\n/// \npublic class SubtitleSegment(AudioSegment originalAudioSegment, float absoluteStartTime, string fullText)\n{\n public AudioSegment OriginalAudioSegment { get; } = originalAudioSegment;\n\n public float AbsoluteStartTime { get; } = absoluteStartTime;\n\n public string FullText { get; } = fullText;\n\n public List Lines { get; } = new();\n\n public float EstimatedEndTime { get; private set; } = absoluteStartTime;\n\n public void AddLine(SubtitleLine line)\n {\n Lines.Add(line);\n if ( line.Words.Count <= 0 )\n {\n return;\n }\n\n var lastWord = line.Words[^1];\n EstimatedEndTime = Math.Max(EstimatedEndTime, lastWord.AbsoluteStartTime + lastWord.Duration);\n }\n\n public void Clear()\n {\n Lines.Clear();\n EstimatedEndTime = AbsoluteStartTime;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/WaveFileUtils.cs", "using System.Buffers;\n\nusing PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.Utils;\n\n/// \n/// Utility class for reading and writing wave files.\n/// \ninternal class WaveFileUtils\n{\n private static readonly byte[] ExpectedSubFormatForPcm = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71];\n\n public static async Task ParseHeaderAsync(Stream stream, CancellationToken cancellationToken)\n {\n var toReturn = new List();\n try\n {\n var headerChunks = new MergedMemoryChunks();\n\n // We load the first 44 bytes directly as we know that is the minimum size for a wave file header.\n if ( !await HaveEnoughDataAsync(headerChunks, 44, stream, toReturn, cancellationToken) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n AudioSourceHeader? header = null;\n\n var chunkID = headerChunks.ReadUInt32LittleEndian();\n // Skip the file size\n headerChunks.TrySkip(4);\n var riffType = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkID != 0x46464952 /*'RIFF'*/ || riffType != 0x45564157 /*'WAVE'*/ )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file header.\");\n }\n\n // Read chunks until we find 'fmt ' and 'data'\n while ( true )\n {\n if ( !await HaveEnoughDataAsync(headerChunks, 8, stream, toReturn, cancellationToken) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n var chunkType = headerChunks.ReadUInt32LittleEndian();\n var chunkSize = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkType == 0x20746D66 /*'fmt '*/ )\n {\n if ( chunkSize < 16 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n if ( !await HaveEnoughDataAsync(headerChunks, chunkSize, stream, toReturn, cancellationToken) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n var formatTag = headerChunks.ReadUInt16LittleEndian();\n var channels = headerChunks.ReadUInt16LittleEndian();\n var sampleRate = headerChunks.ReadUInt32LittleEndian();\n var avgBytesPerSec = headerChunks.ReadUInt32LittleEndian();\n var blockAlign = headerChunks.ReadUInt16LittleEndian();\n var bitsPerSample = headerChunks.ReadUInt16LittleEndian();\n\n if ( formatTag != 1 && formatTag != 0xFFFE ) // PCM or WAVE_FORMAT_EXTENSIBLE\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n\n ushort? cbSize = null;\n ushort? validBitsPerSample = null;\n uint? channelMask = null;\n if ( formatTag == 0xFFFE )\n {\n // WAVE_FORMAT_EXTENSIBLE\n if ( chunkSize < 40 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n cbSize = headerChunks.ReadUInt16LittleEndian();\n validBitsPerSample = headerChunks.ReadUInt16LittleEndian();\n channelMask = headerChunks.ReadUInt32LittleEndian();\n var subFormatChunk = headerChunks.GetChunk(16);\n\n if ( !subFormatChunk.Span.SequenceEqual(ExpectedSubFormatForPcm) )\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n }\n\n if ( channels == 0 )\n {\n return HeaderParseResult.NotSupported(\"Cannot read wave file with 0 channels.\");\n }\n\n // Skip any remaining bytes in fmt chunk\n var remainingBytes = chunkSize - (formatTag == 1 ? 16u : 40u);\n if ( !SkipData(headerChunks, remainingBytes, stream) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n header = new AudioSourceHeader { Channels = channels, SampleRate = sampleRate, BitsPerSample = bitsPerSample };\n }\n else if ( chunkType == 0x61746164 /*'data'*/ )\n {\n if ( header == null )\n {\n return HeaderParseResult.Corrupt(\"Data chunk found before format chunk.\");\n }\n\n // Found 'data' chunk\n // We can start processing samples after this point\n var dataOffset = (int)(headerChunks.Position - headerChunks.AbsolutePositionOfCurrentChunk);\n\n return HeaderParseResult.Success(header, dataOffset, chunkSize);\n }\n else\n {\n if ( !SkipData(headerChunks, chunkSize, stream) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n }\n }\n }\n catch\n {\n foreach ( var rented in toReturn )\n {\n ArrayPool.Shared.Return(rented, ArrayPoolConfig.ClearOnReturn);\n }\n }\n\n return HeaderParseResult.WaitingForMoreData;\n }\n\n public static HeaderParseResult ParseHeader(MergedMemoryChunks headerChunks)\n {\n if ( headerChunks.Length < 12 )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n AudioSourceHeader? header = null;\n\n var chunkID = headerChunks.ReadUInt32LittleEndian();\n // Skip the file size\n headerChunks.TrySkip(4);\n var riffType = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkID != 0x46464952 /*'RIFF'*/ || riffType != 0x45564157 /*'WAVE'*/ )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file header.\");\n }\n\n // Read chunks until we find 'fmt ' and 'data'\n while ( headerChunks.Position + 8 <= headerChunks.Length )\n {\n var chunkType = headerChunks.ReadUInt32LittleEndian();\n var chunkSize = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkType == 0x20746D66 /*'fmt '*/ )\n {\n if ( chunkSize < 16 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n if ( headerChunks.Position + chunkSize > headerChunks.Length )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n var formatTag = headerChunks.ReadUInt16LittleEndian();\n var channels = headerChunks.ReadUInt16LittleEndian();\n var sampleRate = headerChunks.ReadUInt32LittleEndian();\n headerChunks.TrySkip(6); // avgBytesPerSec + blockAlign\n\n var bitsPerSample = headerChunks.ReadUInt16LittleEndian();\n\n if ( formatTag != 1 && formatTag != 0xFFFE ) // PCM or WAVE_FORMAT_EXTENSIBLE\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n\n if ( formatTag == 0xFFFE )\n {\n // WAVE_FORMAT_EXTENSIBLE\n if ( chunkSize < 40 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n headerChunks.TrySkip(8); // cbSize + validBitsPerSample + channelMask\n var subFormatChunk = headerChunks.GetChunk(16);\n\n if ( !subFormatChunk.Span.SequenceEqual(ExpectedSubFormatForPcm) )\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n }\n\n if ( channels == 0 )\n {\n return HeaderParseResult.NotSupported(\"Cannot read wave file with 0 channels.\");\n }\n\n // Skip any remaining bytes in fmt chunk\n if ( !headerChunks.TrySkip(chunkSize - (formatTag == 1 ? 16u : 40u)) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n header = new AudioSourceHeader { Channels = channels, SampleRate = sampleRate, BitsPerSample = bitsPerSample };\n }\n else if ( chunkType == 0x61746164 /*'data'*/ )\n {\n if ( header == null )\n {\n return HeaderParseResult.Corrupt(\"Data chunk found before format chunk.\");\n }\n\n // Found 'data' chunk\n // We can start processing samples after this point\n var dataOffset = (int)(headerChunks.Position - headerChunks.AbsolutePositionOfCurrentChunk);\n\n return HeaderParseResult.Success(header, dataOffset, chunkSize);\n }\n else\n {\n if ( !headerChunks.TrySkip(chunkSize) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n }\n }\n\n return HeaderParseResult.WaitingForMoreData;\n }\n\n /// \n /// Ensures that the given number of bytes can be read from the memory chunks.\n /// \n /// \n private static async Task HaveEnoughDataAsync(MergedMemoryChunks headerChunks, uint requiredBytes, Stream stream, List returnItems, CancellationToken cancellationToken)\n {\n var extraBytesNeeded = (int)(requiredBytes - (headerChunks.Length - headerChunks.Position));\n if ( extraBytesNeeded <= 0 )\n {\n return true;\n }\n\n // We try to read the next chunk from the stream\n var nextChunk = ArrayPool.Shared.Rent(extraBytesNeeded);\n returnItems.Add(nextChunk);\n var chunkMemory = nextChunk.AsMemory(0, extraBytesNeeded);\n\n var actualReadNext = await stream.ReadAsync(chunkMemory, cancellationToken);\n\n if ( actualReadNext != extraBytesNeeded )\n {\n return false;\n }\n\n headerChunks.AddChunk(chunkMemory);\n\n return true;\n }\n\n private static bool SkipData(MergedMemoryChunks headerChunks, uint skipBytes, Stream stream)\n {\n var extraBytesNeededToSkip = (int)(skipBytes - (headerChunks.Length - headerChunks.Position));\n if ( extraBytesNeededToSkip <= 0 )\n {\n return headerChunks.TrySkip(skipBytes);\n }\n\n // We skip all the bytes we have in the current chunks + the remaining bytes from the stream directly\n if ( !headerChunks.TrySkip((uint)(headerChunks.Length - headerChunks.Position)) )\n {\n return false;\n }\n\n var skipped = stream.Seek(skipBytes, SeekOrigin.Current);\n\n return skipped == extraBytesNeededToSkip;\n }\n\n internal class HeaderParseResult(bool isSuccess, bool isIncomplete, bool isCorrupt, bool isNotSupported, int dataOffset, long dataChunkSize, AudioSourceHeader? header, string? errorMessage)\n {\n public static HeaderParseResult WaitingForMoreData { get; } = new(false, true, false, false, 0, 0, null, \"Not enough data available.\");\n\n public bool IsSuccess { get; } = isSuccess;\n\n public bool IsIncomplete { get; } = isIncomplete;\n\n public bool IsCorrupt { get; } = isCorrupt;\n\n public bool IsNotSupported { get; } = isNotSupported;\n\n public int DataOffset { get; } = dataOffset;\n\n public long DataChunkSize { get; } = dataChunkSize;\n\n public AudioSourceHeader? Header { get; } = header;\n\n public string? ErrorMessage { get; } = errorMessage;\n\n public static HeaderParseResult Corrupt(string message) { return new HeaderParseResult(true, false, true, true, 0, 0, null, message); }\n\n public static HeaderParseResult NotSupported(string message) { return new HeaderParseResult(false, false, false, true, 0, 0, null, message); }\n\n public static HeaderParseResult Success(AudioSourceHeader header, int dataOffset, long dataChunkSize) { return new HeaderParseResult(true, false, false, false, dataOffset, dataChunkSize, header, null); }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppLive2DManager.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// サンプルアプリケーションにおいてCubismModelを管理するクラス\n/// モデル生成と破棄、タップイベントの処理、モデル切り替えを行う。\n/// \n/// \n/// コンストラクタ\n/// \npublic class LAppLive2DManager(LAppDelegate lapp) : IDisposable\n{\n /// \n /// モデルインスタンスのコンテナ\n /// \n private readonly List _models = [];\n\n private readonly CubismMatrix44 _projection = new();\n\n /// \n /// モデル描画に用いるView行列\n /// \n public CubismMatrix44 ViewMatrix { get; } = new();\n\n public void Dispose() { ReleaseAllModel(); }\n\n public event Action? MotionFinished;\n\n /// \n /// 現在のシーンで保持しているモデルを返す\n /// \n /// モデルリストのインデックス値\n /// モデルのインスタンスを返す。インデックス値が範囲外の場合はNULLを返す。\n public LAppModel GetModel(int no) { return _models[no]; }\n\n /// \n /// 現在のシーンで保持しているすべてのモデルを解放する\n /// \n public void ReleaseAllModel()\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n _models[i].Dispose();\n }\n\n _models.Clear();\n }\n\n /// \n /// 画面をドラッグしたときの処理\n /// \n /// 画面のX座標\n /// 画面のY座標\n public void OnDrag(float x, float y)\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n var model = GetModel(i);\n\n model.SetDragging(x, y);\n }\n }\n\n /// \n /// 画面をタップしたときの処理\n /// \n /// 画面のX座標\n /// 画面のY座標\n public void OnTap(float x, float y)\n {\n CubismLog.Debug($\"[Live2D]tap point: x:{x:0.00} y:{y:0.00}\");\n\n for ( var i = 0; i < _models.Count; i++ )\n {\n if ( _models[i].HitTest(LAppDefine.HitAreaNameHead, x, y) )\n {\n CubismLog.Debug($\"[Live2D]hit area: [{LAppDefine.HitAreaNameHead}]\");\n _models[i].SetRandomExpression();\n }\n else if ( _models[i].HitTest(LAppDefine.HitAreaNameBody, x, y) )\n {\n CubismLog.Debug($\"[Live2D]hit area: [{LAppDefine.HitAreaNameBody}]\");\n _models[i].StartRandomMotion(LAppDefine.MotionGroupTapBody, MotionPriority.PriorityNormal, OnFinishedMotion);\n }\n }\n }\n\n private void OnFinishedMotion(CubismModel model, ACubismMotion self)\n {\n CubismLog.Info($\"[Live2D]Motion Finished: {self}\");\n MotionFinished?.Invoke(model, self);\n }\n\n /// \n /// 画面を更新するときの処理\n /// モデルの更新処理および描画処理を行う\n /// \n public void OnUpdate()\n {\n lapp.GL.GetWindowSize(out var width, out var height);\n\n var modelCount = _models.Count;\n foreach ( var model in _models )\n {\n _projection.LoadIdentity();\n\n if ( model.Model.GetCanvasWidth() > 1.0f && width < height )\n {\n // 横に長いモデルを縦長ウィンドウに表示する際モデルの横サイズでscaleを算出する\n model.ModelMatrix.SetWidth(2.0f);\n _projection.Scale(1.0f, (float)width / height);\n }\n else\n {\n _projection.Scale((float)height / width, 1.0f);\n }\n\n // 必要があればここで乗算\n if ( ViewMatrix != null )\n {\n _projection.MultiplyByMatrix(ViewMatrix);\n }\n\n model.Update();\n model.Draw(_projection); // 参照渡しなのでprojectionは変質する\n }\n }\n\n public LAppModel LoadModel(string dir, string name)\n {\n CubismLog.Debug($\"[Live2D]model load: {name}\");\n\n // ModelDir[]に保持したディレクトリ名から\n // model3.jsonのパスを決定する.\n // ディレクトリ名とmodel3.jsonの名前を一致させておくこと.\n if ( !dir.EndsWith('\\\\') && !dir.EndsWith('/') )\n {\n dir = Path.GetFullPath(dir + '/');\n }\n\n var modelJsonName = Path.GetFullPath($\"{dir}{name}\");\n if ( !File.Exists(modelJsonName) )\n {\n modelJsonName = Path.GetFullPath($\"{dir}{name}.model3.json\");\n }\n\n if ( !File.Exists(modelJsonName) )\n {\n dir = Path.GetFullPath(dir + name + '/');\n modelJsonName = Path.GetFullPath($\"{dir}{name}.model3.json\");\n }\n\n if ( !File.Exists(modelJsonName) )\n {\n throw new Exception($\"[Live2D]File not found: {modelJsonName}\");\n }\n\n var model = new LAppModel(lapp, dir, modelJsonName);\n _models.Add(model);\n\n return model;\n }\n\n public void RemoveModel(int index)\n {\n if ( _models.Count > index )\n {\n var model = _models[index];\n _models.RemoveAt(index);\n model.Dispose();\n }\n }\n\n /// \n /// モデル個数を得る\n /// \n /// 所持モデル個数\n public int GetModelNum() { return _models.Count; }\n\n public async void StartSpeaking(string filePath)\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n _models[i]._wavFileHandler.Start(filePath);\n await _models[i]._wavFileHandler.LoadWavFile(filePath);\n _models[i].StartMotion(LAppDefine.MotionGroupIdle, 0, MotionPriority.PriorityIdle, OnFinishedMotion);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/Texture.cs", "using System.Drawing;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\npublic enum TextureCoordinate\n{\n S = TextureParameterName.TextureWrapS,\n\n T = TextureParameterName.TextureWrapT,\n\n R = TextureParameterName.TextureWrapR\n}\n\npublic unsafe class Texture : IDisposable\n{\n public const SizedInternalFormat Srgb8Alpha8 = (SizedInternalFormat)GLEnum.Srgb8Alpha8;\n\n public const SizedInternalFormat Rgb32F = (SizedInternalFormat)GLEnum.Rgb32f;\n\n public const GLEnum MaxTextureMaxAnisotropy = (GLEnum)0x84FF;\n\n public static float? MaxAniso;\n\n private readonly GL _gl;\n\n public readonly uint GlTexture;\n\n public readonly SizedInternalFormat InternalFormat;\n\n public readonly uint MipmapLevels;\n\n public readonly uint Width,\n Height;\n\n public Texture(GL gl, int width, int height, IntPtr data, bool generateMipmaps = false, bool srgb = false)\n {\n _gl = gl;\n MaxAniso ??= gl.GetFloat(MaxTextureMaxAnisotropy);\n Width = (uint)width;\n Height = (uint)height;\n InternalFormat = srgb ? Srgb8Alpha8 : SizedInternalFormat.Rgba8;\n MipmapLevels = (uint)(generateMipmaps == false ? 1 : (int)Math.Floor(Math.Log(Math.Max(Width, Height), 2)));\n\n GlTexture = _gl.GenTexture();\n Bind();\n\n _gl.TexStorage2D(GLEnum.Texture2D, MipmapLevels, InternalFormat, Width, Height);\n _gl.TexSubImage2D(GLEnum.Texture2D, 0, 0, 0, Width, Height, PixelFormat.Bgra, PixelType.UnsignedByte, (void*)data);\n\n if ( generateMipmaps )\n {\n _gl.GenerateTextureMipmap(GlTexture);\n }\n\n SetWrap(TextureCoordinate.S, TextureWrapMode.Repeat);\n SetWrap(TextureCoordinate.T, TextureWrapMode.Repeat);\n\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMaxLevel, MipmapLevels - 1);\n }\n\n public void Dispose()\n {\n _gl.DeleteTexture(GlTexture);\n _gl.CheckError();\n }\n\n public void Bind()\n {\n _gl.BindTexture(GLEnum.Texture2D, GlTexture);\n _gl.CheckError();\n }\n\n public void SetMinFilter(TextureMinFilter filter) { _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMinFilter, (int)filter); }\n\n public void SetMagFilter(TextureMagFilter filter) { _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMagFilter, (int)filter); }\n\n public void SetAnisotropy(float level)\n {\n const TextureParameterName textureMaxAnisotropy = (TextureParameterName)0x84FE;\n _gl.TexParameter(GLEnum.Texture2D, (GLEnum)textureMaxAnisotropy, GlUtility.Clamp(level, 1, MaxAniso.GetValueOrDefault()));\n }\n\n public void SetLod(int @base, int min, int max)\n {\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureLodBias, @base);\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMinLod, min);\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMaxLod, max);\n }\n\n public void SetWrap(TextureCoordinate coord, TextureWrapMode mode) { _gl.TexParameterI(GLEnum.Texture2D, (TextureParameterName)coord, (int)mode); }\n\n public void SetData(Rectangle bounds, byte[] data)\n {\n Bind();\n fixed (byte* ptr = data)\n {\n _gl.TexSubImage2D(\n TextureTarget.Texture2D,\n 0,\n bounds.Left,\n bounds.Top,\n (uint)bounds.Width,\n (uint)bounds.Height,\n PixelFormat.Rgba,\n PixelType.UnsignedByte,\n ptr\n );\n\n _gl.CheckError();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanityDetectorOnnx.cs", "using Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\nusing Microsoft.ML.Tokenizers;\n\nnamespace PersonaEngine.Lib.TTS.Profanity;\n\npublic class ProfanityDetectorOnnx : IDisposable\n{\n private readonly InferenceSession _session;\n\n private readonly Tokenizer _tokenizer;\n\n public ProfanityDetectorOnnx(string? modelPath = null, string? vocabPath = null)\n {\n if ( modelPath == null )\n {\n modelPath = ModelUtils.GetModelPath(ModelType.TinyToxic);\n }\n\n if ( vocabPath == null )\n {\n vocabPath = ModelUtils.GetModelPath(ModelType.TinyToxicVocab);\n }\n\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n using Stream vocabStream = File.OpenRead(vocabPath);\n _tokenizer = BertTokenizer.Create(vocabStream);\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n private IEnumerable Tokenize(string sentence) { return _tokenizer.EncodeToIds(sentence).Select(x => (long)x); }\n\n public float Run(string sentence)\n {\n var inputIds = Tokenize(sentence).ToArray();\n var inputIdsTensor = new DenseTensor(inputIds, new[] { 1, inputIds.Length });\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input_ids\", inputIdsTensor) };\n\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray().Single();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadOnnxModel.cs", "using Microsoft.ML.OnnxRuntime;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroVadOnnxModel : IDisposable\n{\n private static readonly long[] sampleRateInput = [SileroConstants.SampleRate];\n\n private readonly long[] runningInputShape = [1, SileroConstants.BatchSize + SileroConstants.ContextSize];\n\n private readonly RunOptions runOptions;\n\n private readonly InferenceSession session;\n\n private readonly long[] stateShape = [2, 1, 128];\n\n public SileroVadOnnxModel(string modelPath)\n {\n var sessionOptions = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = 1,\n IntraOpNumThreads = 1,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR\n };\n \n sessionOptions.AppendExecutionProvider_CUDA();\n\n session = new InferenceSession(modelPath, sessionOptions);\n runOptions = new RunOptions();\n }\n\n public void Dispose() { session?.Dispose(); }\n\n public SileroInferenceState CreateInferenceState()\n {\n var state = new SileroInferenceState(session.CreateIoBinding());\n\n state.Binding.BindInput(\"state\", OrtValue.CreateTensorValueFromMemory(state.State, stateShape));\n state.Binding.BindInput(\"sr\", OrtValue.CreateTensorValueFromMemory(sampleRateInput, [1]));\n\n state.Binding.BindOutput(\"output\", OrtValue.CreateTensorValueFromMemory(state.Output, [1, SileroConstants.OutputSize]));\n state.Binding.BindOutput(\"stateN\", OrtValue.CreateTensorValueFromMemory(state.PendingState, stateShape));\n\n return state;\n }\n\n public float Call(Memory input, SileroInferenceState state)\n {\n state.Binding.BindInput(\"input\", OrtValue.CreateTensorValueFromMemory(OrtMemoryInfo.DefaultInstance, input, runningInputShape));\n // We need to swap the state and pending state to keep the state for the next inference\n // Zero allocation swap\n (state.State, state.PendingState) = (state.PendingState, state.State);\n\n session.RunWithBinding(runOptions, state.Binding);\n\n return state.Output[0];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionQueueManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーション再生の管理用クラス。CubismMotionモーションなどACubismMotionのサブクラスを再生するために使用する。\n/// 再生中に別のモーションが StartMotion()された場合は、新しいモーションに滑らかに変化し旧モーションは中断する。\n/// 表情用モーション、体用モーションなどを分けてモーション化した場合など、\n/// 複数のモーションを同時に再生させる場合は、複数のCubismMotionQueueManagerインスタンスを使用する。\n/// \npublic class CubismMotionQueueManager\n{\n private readonly List _remove = [];\n\n /// \n /// モーション\n /// \n protected readonly List Motions = [];\n\n /// \n /// コールバック関数ポインタ\n /// \n private CubismMotionEventFunction? _eventCallback;\n\n /// \n /// コールバックに戻されるデータ\n /// \n private CubismUserModel? _eventCustomData;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n protected float UserTimeSeconds;\n\n /// \n /// 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。\n /// \n /// 開始するモーション\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotion(ACubismMotion motion)\n {\n CubismMotionQueueEntry motionQueueEntry;\n\n // 既にモーションがあれば終了フラグを立てる\n for ( var i = 0; i < Motions.Count; ++i )\n {\n motionQueueEntry = Motions[0];\n if ( motionQueueEntry == null )\n {\n continue;\n }\n\n motionQueueEntry.SetFadeout(motionQueueEntry.Motion.FadeOutSeconds);\n }\n\n motionQueueEntry = new CubismMotionQueueEntry { Motion = motion };\n\n Motions.Add(motionQueueEntry);\n\n return motionQueueEntry;\n }\n\n /// \n /// 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。\n /// \n /// 開始するモーション\n /// 再生が終了したモーションのインスタンスを削除するなら true\n /// デルタ時間の積算値[秒]\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n [Obsolete(\"Please use StartMotion(ACubismMotion motion\")]\n public CubismMotionQueueEntry StartMotion(ACubismMotion motion, float userTimeSeconds)\n {\n CubismLog.Warning(\"StartMotion(ACubismMotion motion, float userTimeSeconds) is a deprecated function. Please use StartMotion(ACubismMotion motion).\");\n\n CubismMotionQueueEntry motionQueueEntry;\n\n // 既にモーションがあれば終了フラグを立てる\n for ( var i = 0; i < Motions.Count; ++i )\n {\n motionQueueEntry = Motions[i];\n if ( motionQueueEntry == null )\n {\n continue;\n }\n\n motionQueueEntry.SetFadeout(motionQueueEntry.Motion.FadeOutSeconds);\n }\n\n motionQueueEntry = new CubismMotionQueueEntry { Motion = motion }; // 終了時に破棄する\n\n Motions.Add(motionQueueEntry);\n\n return motionQueueEntry;\n }\n\n /// \n /// すべてのモーションが終了しているかどうか。\n /// \n /// \n /// true すべて終了している\n /// false 終了していない\n /// \n public bool IsFinished()\n {\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n foreach ( var item in Motions )\n {\n // ----- 終了済みの処理があれば削除する ------\n if ( !item.Finished )\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// 指定したモーションが終了しているかどうか。\n /// \n /// モーションの識別番号\n /// \n /// true 指定したモーションは終了している\n /// false 終了していない\n /// \n public bool IsFinished(object motionQueueEntryNumber)\n {\n // 既にモーションがあれば終了フラグを立てる\n\n foreach ( var item in Motions )\n {\n if ( item == null )\n {\n continue;\n }\n\n if ( item == motionQueueEntryNumber && !item.Finished )\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// すべてのモーションを停止する。\n /// \n public void StopAllMotions()\n {\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n\n Motions.Clear();\n }\n\n /// \n /// 指定したCubismMotionQueueEntryを取得する。\n /// \n /// モーションの識別番号\n /// \n /// 指定したCubismMotionQueueEntryへのポインタ\n /// NULL 見つからなかった\n /// \n public CubismMotionQueueEntry? GetCubismMotionQueueEntry(object motionQueueEntryNumber)\n {\n //------- 処理を行う --------\n //既にモーションがあれば終了フラグを立てる\n\n foreach ( var item in Motions )\n {\n if ( item == motionQueueEntryNumber )\n {\n return item;\n }\n }\n\n return null;\n }\n\n /// \n /// イベントを受け取るCallbackの登録をする。\n /// \n /// コールバック関数\n /// コールバックに返されるデータ\n public void SetEventCallback(CubismMotionEventFunction callback, CubismUserModel customData)\n {\n _eventCallback = callback;\n _eventCustomData = customData;\n }\n\n /// \n /// モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間の積算値[秒]\n /// \n /// true モデルへパラメータ値の反映あり\n /// false モデルへパラメータ値の反映なし(モーションの変化なし)\n /// \n public virtual bool DoUpdateMotion(CubismModel model, float userTimeSeconds)\n {\n var updated = false;\n\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n\n _remove.Clear();\n\n for ( var motionIndex = Motions.Count - 1; motionIndex >= 0; motionIndex-- )\n {\n var item = Motions[motionIndex];\n var motion = item.Motion;\n\n // ------ 値を反映する ------\n motion.UpdateParameters(model, item, userTimeSeconds);\n updated = true;\n\n // ------ ユーザトリガーイベントを検査する ----\n var firedList = motion.GetFiredEvent(\n item.LastEventCheckSeconds - item.StartTime,\n userTimeSeconds - item.StartTime);\n\n for ( var i = 0; i < firedList.Count; ++i )\n {\n _eventCallback?.Invoke(_eventCustomData, firedList[i]);\n }\n\n item.LastEventCheckSeconds = userTimeSeconds;\n\n // ----- 終了済みの処理があれば削除する ------\n if ( item.Finished )\n {\n _remove.Add(item); // 削除\n }\n else\n {\n if ( item.IsTriggeredFadeOut )\n {\n item.StartFadeout(item.FadeOutSeconds, userTimeSeconds);\n }\n }\n }\n\n foreach ( var item in _remove )\n {\n Motions.Remove(item);\n }\n\n return updated;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Live2DManager.cs", "using Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.Live2D.Behaviour;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\nusing PersonaEngine.Lib.UI;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.Live2D;\n\npublic class Live2DManager : IRenderComponent\n{\n private readonly IList _live2DAnimationServices;\n\n private readonly IOptionsMonitor _options;\n\n private LAppDelegate? _lapp;\n\n public Live2DManager(IOptionsMonitor options, IEnumerable live2DAnimationServices)\n {\n _options = options;\n _live2DAnimationServices = live2DAnimationServices.ToList();\n }\n\n public bool UseSpout => true;\n\n public string SpoutTarget => \"Live2D\";\n\n public int Priority => 100;\n\n public void Update(float deltaTime) { }\n\n public void Render(float deltaTime)\n {\n if ( _lapp == null )\n {\n return;\n }\n\n _lapp.Update(deltaTime);\n _lapp.Run();\n }\n\n public void Resize() { _lapp?.Resize(); }\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n var config = _options.CurrentValue;\n _lapp = new LAppDelegate(new SilkNetApi(gl, config.Width, config.Height), _ => { }) { BGColor = new CubismTextureColor(0, 0, 0, 0) };\n\n LoadModel(config.ModelPath, config.ModelName);\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n }\n\n /// \n /// Loads a Live2D model from the given path.\n /// \n public void LoadModel(string modelPath, string modelName)\n {\n if ( _lapp == null )\n {\n throw new InvalidOperationException(\"Live2DManager is not initialized.\");\n }\n\n var model = _lapp.Live2dManager.LoadModel(modelPath, modelName);\n model.RandomMotion = false;\n model.CustomValueUpdate = true;\n\n // model.ModelMatrix.Translate(0.0f, -1.8f);\n model.ModelMatrix.ScaleRelative(0.7f, 0.7f);\n\n Resize();\n\n foreach ( var animationService in _live2DAnimationServices )\n {\n model.ValueUpdate += _ => animationService.Update(LAppPal.DeltaTime);\n animationService.Start(model);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TokenContext.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class TokenContext\n{\n public bool? FutureVowel { get; set; }\n\n public bool FutureTo { get; set; }\n\n public static TokenContext UpdateContext(TokenContext ctx, string? phonemes, Token token)\n {\n var vowel = ctx.FutureVowel;\n\n if ( !string.IsNullOrEmpty(phonemes) )\n {\n foreach ( var c in phonemes )\n {\n if ( PhonemizerConstants.Vowels.Contains(c) ||\n PhonemizerConstants.Consonants.Contains(c) ||\n PhonemizerConstants.NonQuotePuncts.Contains(c) )\n {\n vowel = PhonemizerConstants.NonQuotePuncts.Contains(c) ? null : PhonemizerConstants.Vowels.Contains(c);\n\n break;\n }\n }\n }\n\n return new TokenContext { FutureVowel = vowel, FutureTo = token.IsTo() };\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/Texture2DManager.cs", "using System.Drawing;\nusing System.Runtime.InteropServices;\n\nusing FontStashSharp.Interfaces;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\ninternal class Texture2DManager(GL gl) : ITexture2DManager\n{\n public object CreateTexture(int width, int height)\n {\n // Create an empty texture of the specified size\n // Allocate empty memory for the texture (4 bytes per pixel for RGBA format)\n var data = IntPtr.Zero;\n\n try\n {\n // Allocate unmanaged memory for the texture data\n var size = width * height * 4;\n data = Marshal.AllocHGlobal(size);\n\n // Initialize with transparent pixels (optional)\n unsafe\n {\n var ptr = (byte*)data.ToPointer();\n for ( var i = 0; i < size; i++ )\n {\n ptr[i] = 0;\n }\n }\n\n // Create the texture with the empty data\n // generateMipmaps is set to false as this is for UI/text rendering\n return new Texture(gl, width, height, data);\n }\n finally\n {\n // Free the unmanaged memory after the texture is created\n if ( data != IntPtr.Zero )\n {\n Marshal.FreeHGlobal(data);\n }\n }\n }\n\n public Point GetTextureSize(object texture)\n {\n var t = (Texture)texture;\n\n return new Point((int)t.Width, (int)t.Height);\n }\n\n public void SetTextureData(object texture, Rectangle bounds, byte[] data)\n {\n var t = (Texture)texture;\n t.Bind();\n\n unsafe\n {\n fixed (byte* ptr = data)\n {\n gl.TexSubImage2D(\n GLEnum.Texture2D,\n 0, // mipmap level\n bounds.Left, // x offset\n bounds.Top, // y offset\n (uint)bounds.Width, // width\n (uint)bounds.Height, // height\n PixelFormat.Bgra, // format matching the Texture class\n PixelType.UnsignedByte, // data type\n ptr // data pointer\n );\n\n gl.CheckError();\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Vision/VisualQAService.cs", "using System.Text;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.SemanticKernel.Connectors.OpenAI;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.LLM;\n\nnamespace PersonaEngine.Lib.Vision;\n\npublic class VisualQAService : IVisualQAService\n{\n private readonly WindowCaptureService _captureService;\n\n private readonly IVisualChatEngine _chatEngine;\n\n private readonly VisionConfig _config;\n\n private readonly SemaphoreSlim _fileChangeSemaphore = new(1, 1);\n\n private readonly CancellationTokenSource _internalCts = new();\n\n private readonly ILogger _logger;\n\n private DateTimeOffset _lastProcessedTimestamp = DateTimeOffset.MinValue;\n\n public VisualQAService(\n IOptions config,\n WindowCaptureService captureService,\n IVisualChatEngine chatEngine,\n ILogger logger)\n {\n _config = config.Value.Vision;\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n _captureService = captureService;\n _chatEngine = chatEngine;\n\n _captureService.OnCaptureFrame += OnCaptureFrame;\n }\n\n public string? ScreenCaption { get; private set; }\n\n public Task StartAsync(CancellationToken cancellationToken = default)\n {\n if ( !_config.Enabled )\n {\n return Task.CompletedTask;\n }\n\n CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _internalCts.Token);\n _logger.LogDebug(\"Starting Visual QA Service\");\n _captureService.StartAsync(cancellationToken);\n\n return Task.CompletedTask;\n }\n\n public async Task StopAsync()\n {\n _logger.LogDebug(\"Stopping Visual QA Service\");\n await _internalCts.CancelAsync();\n await _captureService.StopAsync();\n }\n\n public async ValueTask DisposeAsync()\n {\n await StopAsync();\n _internalCts.Dispose();\n _fileChangeSemaphore.Dispose();\n _captureService.OnCaptureFrame -= OnCaptureFrame;\n }\n\n private async void OnCaptureFrame(object? sender, CaptureFrameEventArgs e)\n {\n await _fileChangeSemaphore.WaitAsync(_internalCts.Token);\n\n try\n {\n var currentTimestamp = DateTimeOffset.Now;\n if ( (currentTimestamp - _lastProcessedTimestamp).TotalMilliseconds < 100 )\n {\n return;\n }\n\n _lastProcessedTimestamp = currentTimestamp;\n\n var result = await ProcessVisualQAFrame(e.FrameData);\n ScreenCaption = result;\n }\n finally\n {\n _fileChangeSemaphore.Release();\n }\n }\n\n private async Task ProcessVisualQAFrame(ReadOnlyMemory imageData)\n {\n try\n {\n var question = \"Describe the main content of this screenshot objectivly in great detail.\";\n var chatMessage = new VisualChatMessage(question, imageData);\n var caption = new StringBuilder();\n var settings = new OpenAIPromptExecutionSettings { FrequencyPenalty = 1.1, Temperature = 0.1, PresencePenalty = 1.1, MaxTokens = 256 };\n await foreach ( var response in _chatEngine.GetStreamingChatResponseAsync(chatMessage, settings, _internalCts.Token) )\n {\n caption.Append(response);\n }\n\n return caption.ToString();\n }\n catch (Exception e)\n {\n _logger.LogError(e, \"Failed to caption screen frame\");\n\n return null;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Spout/SpoutManager.cs", "using PersonaEngine.Lib.Configuration;\n\nusing Silk.NET.OpenGL;\n\nusing Spout.Interop;\n\nnamespace PersonaEngine.Lib.UI.Spout;\n\n/// \n/// Provides real-time frame sharing via Spout with custom framebuffer support.\n/// \npublic class SpoutManager : IDisposable\n{\n private readonly SpoutConfiguration _config;\n\n private readonly GL _gl;\n\n private readonly SpoutSender _spoutSender;\n\n private uint _colorAttachment;\n\n private uint _customFbo;\n\n private bool _customFboInitialized = false;\n\n private uint _depthAttachment;\n\n public SpoutManager(GL gl, SpoutConfiguration config)\n {\n _gl = gl;\n _config = config;\n _spoutSender = new SpoutSender();\n\n InitializeCustomFramebuffer();\n\n if ( !_spoutSender.CreateSender(config.OutputName, (uint)_config.Width, (uint)_config.Height, 0) )\n {\n _spoutSender.Dispose();\n Console.WriteLine($\"Failed to create Spout Sender '{config.OutputName}'.\");\n }\n }\n\n public void Dispose()\n {\n if ( _customFboInitialized )\n {\n _gl.DeleteTexture(_colorAttachment);\n _gl.DeleteTexture(_depthAttachment);\n _gl.DeleteFramebuffer(_customFbo);\n }\n\n _spoutSender?.Dispose();\n }\n\n private unsafe void InitializeCustomFramebuffer()\n {\n _customFbo = _gl.GenFramebuffer();\n _gl.BindFramebuffer(GLEnum.Framebuffer, _customFbo);\n\n _colorAttachment = _gl.GenTexture();\n _gl.BindTexture(GLEnum.Texture2D, _colorAttachment);\n _gl.TexImage2D(GLEnum.Texture2D, 0, (int)GLEnum.Rgba8,\n (uint)_config.Width, (uint)_config.Height, 0, GLEnum.Rgba, GLEnum.UnsignedByte, null);\n\n _gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureMinFilter, (int)GLEnum.Linear);\n _gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureMagFilter, (int)GLEnum.Linear);\n _gl.FramebufferTexture2D(GLEnum.Framebuffer, GLEnum.ColorAttachment0,\n GLEnum.Texture2D, _colorAttachment, 0);\n\n _depthAttachment = _gl.GenTexture();\n _gl.BindTexture(GLEnum.Texture2D, _depthAttachment);\n _gl.TexImage2D(GLEnum.Texture2D, 0, (int)GLEnum.DepthComponent,\n (uint)_config.Width, (uint)_config.Height, 0, GLEnum.DepthComponent, GLEnum.Float, null);\n\n _gl.FramebufferTexture2D(GLEnum.Framebuffer, GLEnum.DepthAttachment,\n GLEnum.Texture2D, _depthAttachment, 0);\n\n if ( _gl.CheckFramebufferStatus(GLEnum.Framebuffer) != GLEnum.FramebufferComplete )\n {\n Console.WriteLine(\"Custom framebuffer is not complete!\");\n\n return;\n }\n\n _gl.BindFramebuffer(GLEnum.Framebuffer, 0);\n\n _customFboInitialized = true;\n }\n\n /// \n /// Begins rendering to the custom framebuffer\n /// \n public void BeginFrame()\n {\n if ( _customFboInitialized )\n {\n _gl.BindFramebuffer(GLEnum.Framebuffer, _customFbo);\n\n _gl.Viewport(0, 0, (uint)_config.Width, (uint)_config.Height);\n\n var blendEnabled = _gl.IsEnabled(EnableCap.Blend);\n\n // Enable blending for transparency\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n\n // Clear with transparency (RGBA: 0,0,0,0)\n _gl.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n _gl.Clear((uint)(GLEnum.ColorBufferBit | GLEnum.DepthBufferBit));\n\n if ( !blendEnabled )\n {\n _gl.Disable(EnableCap.Blend);\n }\n }\n }\n\n /// \n /// Sends the current frame to Spout and returns to the default framebuffer\n /// \n /// Whether to copy the framebuffer to the screen\n /// Window width if blitting to screen\n /// Window height if blitting to screen\n public void SendFrame(bool blitToScreen = true, int windowWidth = 0, int windowHeight = 0)\n {\n if ( _customFboInitialized )\n {\n _gl.GetInteger(GetPName.UnpackAlignment, out var previousUnpackAlignment);\n _gl.PixelStore(PixelStoreParameter.UnpackAlignment, 1);\n\n _spoutSender.SendFbo(_customFbo, (uint)_config.Width, (uint)_config.Height, true);\n\n _gl.PixelStore(PixelStoreParameter.UnpackAlignment, previousUnpackAlignment);\n\n if ( blitToScreen && windowWidth > 0 && windowHeight > 0 )\n {\n _gl.BindFramebuffer(GLEnum.ReadFramebuffer, _customFbo);\n _gl.BindFramebuffer(GLEnum.DrawFramebuffer, 0); // Default framebuffer\n\n var blendEnabled = _gl.IsEnabled(EnableCap.Blend);\n if ( !blendEnabled )\n {\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n }\n\n _gl.BlitFramebuffer(\n 0, 0, _config.Width, _config.Height,\n 0, 0, windowWidth, windowHeight,\n (uint)GLEnum.ColorBufferBit,\n GLEnum.Linear);\n\n if ( !blendEnabled )\n {\n _gl.Disable(EnableCap.Blend);\n }\n }\n\n _gl.BindFramebuffer(GLEnum.Framebuffer, 0);\n }\n else\n {\n _gl.GetInteger(GetPName.ReadFramebufferBinding, out var fboId);\n _spoutSender.SendFbo((uint)fboId, (uint)_config.Width, (uint)_config.Height, true);\n }\n }\n\n /// \n /// Updates the custom framebuffer dimensions if needed\n /// \n public void ResizeFramebuffer(int width, int height)\n {\n // if ( _config.Width == width && _config.Height == height )\n // {\n // return;\n // }\n\n // _config.Width = width;\n // _config.Height = height;\n\n // if ( _customFboInitialized )\n // {\n // _gl.DeleteTexture(_colorAttachment);\n // _gl.DeleteTexture(_depthAttachment);\n // _gl.DeleteFramebuffer(_customFbo);\n // _customFboInitialized = false;\n // }\n //\n // InitializeCustomFramebuffer();\n //\n // _spoutSender.UpdateSender(_config.OutputName, (uint)width, (uint)height);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Common/CompletionReason.cs", "namespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\npublic enum CompletionReason\n{\n Completed,\n\n Cancelled,\n\n Error\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OpenNlpPosTagger.cs", "using System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nusing OpenNLP.Tools.PosTagger;\nusing OpenNLP.Tools.Tokenize;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of OpenNLP-based POS tagger with spaCy-like currency handling\n/// \npublic partial class OpenNlpPosTagger : IPosTagger\n{\n private readonly Regex _currencySymbolRegex = CurrencyRegex();\n\n private readonly ILogger _logger;\n\n private readonly EnglishMaximumEntropyPosTagger _posTagger;\n\n private readonly EnglishRuleBasedTokenizer _tokenizer;\n\n private bool _disposed;\n\n public OpenNlpPosTagger(string modelPath, ILogger logger)\n {\n if ( string.IsNullOrEmpty(modelPath) )\n {\n throw new ArgumentException(\"Model path cannot be null or empty\", nameof(modelPath));\n }\n\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n try\n {\n _tokenizer = new EnglishRuleBasedTokenizer(false);\n _posTagger = new EnglishMaximumEntropyPosTagger(modelPath);\n _logger.LogInformation(\"Initialized OpenNLP POS tagger from {ModelPath}\", modelPath);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to initialize OpenNLP POS tagger\");\n\n throw;\n }\n }\n\n /// \n /// Tags parts of speech in text using OpenNLP with spaCy-like currency handling\n /// \n public Task> TagAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Task.FromResult>(Array.Empty());\n }\n\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Pre-process text to insert spaces between currency symbols and digits\n // This makes the tokenizer split currency symbols from amounts, similar to spaCy\n var currencyRegex = CurrencyWithNumRegex();\n var processedText = currencyRegex.Replace(text, \"$1 $2\");\n\n // Tokenize pre-processed text\n var tokens = _tokenizer.Tokenize(processedText);\n\n // Get POS tags\n var tags = _posTagger.Tag(tokens);\n\n // Post-process to assign \"$\" tag to currency symbols\n for ( var i = 0; i < tokens.Length; i++ )\n {\n if ( _currencySymbolRegex.IsMatch(tokens[i]) )\n {\n tags[i] = \"$\"; // Assign \"$\" tag to currency symbols (spaCy-like behavior)\n }\n }\n\n // Build result tokens with whitespace\n var result = new List();\n var currentPosition = 0;\n\n for ( var i = 0; i < tokens.Length; i++ )\n {\n var token = tokens[i];\n var tag = tags[i];\n\n // Find token position in processed text\n var tokenPosition = processedText.IndexOf(token, currentPosition, StringComparison.Ordinal);\n\n // Extract whitespace between tokens\n var whitespace = \"\";\n if ( i < tokens.Length - 1 )\n {\n var nextTokenStart = processedText.IndexOf(tokens[i + 1], tokenPosition + token.Length, StringComparison.Ordinal);\n if ( nextTokenStart >= 0 )\n {\n whitespace = processedText.Substring(\n tokenPosition + token.Length,\n nextTokenStart - (tokenPosition + token.Length));\n }\n }\n else\n {\n // Last token - get any remaining whitespace\n whitespace = tokenPosition + token.Length < processedText.Length\n ? processedText[(tokenPosition + token.Length)..]\n : \"\";\n }\n\n result.Add(new PosToken { Text = token, PartOfSpeech = tag, IsWhitespace = whitespace.Contains(\" \") });\n\n currentPosition = tokenPosition + token.Length;\n }\n\n return Task.FromResult>(result);\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"POS tagging was canceled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during POS tagging\");\n\n throw;\n }\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n }\n\n [GeneratedRegex(@\"([\\$\\€\\£\\¥\\₹])(\\d)\")]\n private static partial Regex CurrencyWithNumRegex();\n\n [GeneratedRegex(@\"^[\\$\\€\\£\\¥\\₹]$\")] private static partial Regex CurrencyRegex();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Rust/bindings/rust_lib.cs", "// \n// This file was generated by uniffi-bindgen-cs v0.8.4+v0.25.0\n// See https://github.com/NordSecurity/uniffi-bindgen-cs for more information.\n// \n\n#nullable enable\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nnamespace uniffi.rust_lib;\n\n\n\n// This is a helper for safely working with byte buffers returned from the Rust code.\n// A rust-owned buffer is represented by its capacity, its current length, and a\n// pointer to the underlying data.\n\n[StructLayout(LayoutKind.Sequential)]\ninternal struct RustBuffer {\n public int capacity;\n public int len;\n public IntPtr data;\n\n public static RustBuffer Alloc(int size) {\n return _UniffiHelpers.RustCall((ref RustCallStatus status) => {\n var buffer = _UniFFILib.ffi_rust_lib_rustbuffer_alloc(size, ref status);\n if (buffer.data == IntPtr.Zero) {\n throw new AllocationException($\"RustBuffer.Alloc() returned null data pointer (size={size})\");\n }\n return buffer;\n });\n }\n\n public static void Free(RustBuffer buffer) {\n _UniffiHelpers.RustCall((ref RustCallStatus status) => {\n _UniFFILib.ffi_rust_lib_rustbuffer_free(buffer, ref status);\n });\n }\n\n public static BigEndianStream MemoryStream(IntPtr data, int length) {\n unsafe {\n return new BigEndianStream(new UnmanagedMemoryStream((byte*)data.ToPointer(), length));\n }\n }\n\n public BigEndianStream AsStream() {\n unsafe {\n return new BigEndianStream(new UnmanagedMemoryStream((byte*)data.ToPointer(), len));\n }\n }\n\n public BigEndianStream AsWriteableStream() {\n unsafe {\n return new BigEndianStream(new UnmanagedMemoryStream((byte*)data.ToPointer(), capacity, capacity, FileAccess.Write));\n }\n }\n}\n\n// This is a helper for safely passing byte references into the rust code.\n// It's not actually used at the moment, because there aren't many things that you\n// can take a direct pointer to managed memory, and if we're going to copy something\n// then we might as well copy it into a `RustBuffer`. But it's here for API\n// completeness.\n\n[StructLayout(LayoutKind.Sequential)]\ninternal struct ForeignBytes {\n public int length;\n public IntPtr data;\n}\n\n\n// The FfiConverter interface handles converter types to and from the FFI\n//\n// All implementing objects should be public to support external types. When a\n// type is external we need to import it's FfiConverter.\ninternal abstract class FfiConverter {\n // Convert an FFI type to a C# type\n public abstract CsType Lift(FfiType value);\n\n // Convert C# type to an FFI type\n public abstract FfiType Lower(CsType value);\n\n // Read a C# type from a `ByteBuffer`\n public abstract CsType Read(BigEndianStream stream);\n\n // Calculate bytes to allocate when creating a `RustBuffer`\n //\n // This must return at least as many bytes as the write() function will\n // write. It can return more bytes than needed, for example when writing\n // Strings we can't know the exact bytes needed until we the UTF-8\n // encoding, so we pessimistically allocate the largest size possible (3\n // bytes per codepoint). Allocating extra bytes is not really a big deal\n // because the `RustBuffer` is short-lived.\n public abstract int AllocationSize(CsType value);\n\n // Write a C# type to a `ByteBuffer`\n public abstract void Write(CsType value, BigEndianStream stream);\n\n // Lower a value into a `RustBuffer`\n //\n // This method lowers a value into a `RustBuffer` rather than the normal\n // FfiType. It's used by the callback interface code. Callback interface\n // returns are always serialized into a `RustBuffer` regardless of their\n // normal FFI type.\n public RustBuffer LowerIntoRustBuffer(CsType value) {\n var rbuf = RustBuffer.Alloc(AllocationSize(value));\n try {\n var stream = rbuf.AsWriteableStream();\n Write(value, stream);\n rbuf.len = Convert.ToInt32(stream.Position);\n return rbuf;\n } catch {\n RustBuffer.Free(rbuf);\n throw;\n }\n }\n\n // Lift a value from a `RustBuffer`.\n //\n // This here mostly because of the symmetry with `lowerIntoRustBuffer()`.\n // It's currently only used by the `FfiConverterRustBuffer` class below.\n protected CsType LiftFromRustBuffer(RustBuffer rbuf) {\n var stream = rbuf.AsStream();\n try {\n var item = Read(stream);\n if (stream.HasRemaining()) {\n throw new InternalException(\"junk remaining in buffer after lifting, something is very wrong!!\");\n }\n return item;\n } finally {\n RustBuffer.Free(rbuf);\n }\n }\n}\n\n// FfiConverter that uses `RustBuffer` as the FfiType\ninternal abstract class FfiConverterRustBuffer: FfiConverter {\n public override CsType Lift(RustBuffer value) {\n return LiftFromRustBuffer(value);\n }\n public override RustBuffer Lower(CsType value) {\n return LowerIntoRustBuffer(value);\n }\n}\n\n\n// A handful of classes and functions to support the generated data structures.\n// This would be a good candidate for isolating in its own ffi-support lib.\n// Error runtime.\n[StructLayout(LayoutKind.Sequential)]\nstruct RustCallStatus {\n public sbyte code;\n public RustBuffer error_buf;\n\n public bool IsSuccess() {\n return code == 0;\n }\n\n public bool IsError() {\n return code == 1;\n }\n\n public bool IsPanic() {\n return code == 2;\n }\n}\n\n// Base class for all uniffi exceptions\ninternal class UniffiException: System.Exception {\n public UniffiException(): base() {}\n public UniffiException(string message): base(message) {}\n}\n\ninternal class UndeclaredErrorException: UniffiException {\n public UndeclaredErrorException(string message): base(message) {}\n}\n\ninternal class PanicException: UniffiException {\n public PanicException(string message): base(message) {}\n}\n\ninternal class AllocationException: UniffiException {\n public AllocationException(string message): base(message) {}\n}\n\ninternal class InternalException: UniffiException {\n public InternalException(string message): base(message) {}\n}\n\ninternal class InvalidEnumException: InternalException {\n public InvalidEnumException(string message): base(message) {\n }\n}\n\ninternal class UniffiContractVersionException: UniffiException {\n public UniffiContractVersionException(string message): base(message) {\n }\n}\n\ninternal class UniffiContractChecksumException: UniffiException {\n public UniffiContractChecksumException(string message): base(message) {\n }\n}\n\n// Each top-level error class has a companion object that can lift the error from the call status's rust buffer\ninterface CallStatusErrorHandler where E: System.Exception {\n E Lift(RustBuffer error_buf);\n}\n\n// CallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR\nclass NullCallStatusErrorHandler: CallStatusErrorHandler {\n public static NullCallStatusErrorHandler INSTANCE = new NullCallStatusErrorHandler();\n\n public UniffiException Lift(RustBuffer error_buf) {\n RustBuffer.Free(error_buf);\n return new UndeclaredErrorException(\"library has returned an error not declared in UNIFFI interface file\");\n }\n}\n\n// Helpers for calling Rust\n// In practice we usually need to be synchronized to call this safely, so it doesn't\n// synchronize itself\nclass _UniffiHelpers {\n public delegate void RustCallAction(ref RustCallStatus status);\n public delegate U RustCallFunc(ref RustCallStatus status);\n\n // Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err\n public static U RustCallWithError(CallStatusErrorHandler errorHandler, RustCallFunc callback)\n where E: UniffiException\n {\n var status = new RustCallStatus();\n var return_value = callback(ref status);\n if (status.IsSuccess()) {\n return return_value;\n } else if (status.IsError()) {\n throw errorHandler.Lift(status.error_buf);\n } else if (status.IsPanic()) {\n // when the rust code sees a panic, it tries to construct a rustbuffer\n // with the message. but if that code panics, then it just sends back\n // an empty buffer.\n if (status.error_buf.len > 0) {\n throw new PanicException(FfiConverterString.INSTANCE.Lift(status.error_buf));\n } else {\n throw new PanicException(\"Rust panic\");\n }\n } else {\n throw new InternalException($\"Unknown rust call status: {status.code}\");\n }\n }\n\n // Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err\n public static void RustCallWithError(CallStatusErrorHandler errorHandler, RustCallAction callback)\n where E: UniffiException\n {\n _UniffiHelpers.RustCallWithError(errorHandler, (ref RustCallStatus status) => {\n callback(ref status);\n return 0;\n });\n }\n\n // Call a rust function that returns a plain value\n public static U RustCall(RustCallFunc callback) {\n return _UniffiHelpers.RustCallWithError(NullCallStatusErrorHandler.INSTANCE, callback);\n }\n\n // Call a rust function that returns a plain value\n public static void RustCall(RustCallAction callback) {\n _UniffiHelpers.RustCall((ref RustCallStatus status) => {\n callback(ref status);\n return 0;\n });\n }\n}\n\nstatic class FFIObjectUtil {\n public static void DisposeAll(params Object?[] list) {\n foreach (var obj in list) {\n Dispose(obj);\n }\n }\n\n // Dispose is implemented by recursive type inspection at runtime. This is because\n // generating correct Dispose calls for recursive complex types, e.g. List>\n // is quite cumbersome.\n private static void Dispose(dynamic? obj) {\n if (obj == null) {\n return;\n }\n\n if (obj is IDisposable disposable) {\n disposable.Dispose();\n return;\n }\n\n var type = obj.GetType();\n if (type != null) {\n if (type.IsGenericType) {\n if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) {\n foreach (var value in obj) {\n Dispose(value);\n }\n } else if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>))) {\n foreach (var value in obj.Values) {\n Dispose(value);\n }\n }\n }\n }\n }\n}\n\n\n// Big endian streams are not yet available in dotnet :'(\n// https://github.com/dotnet/runtime/issues/26904\n\nclass StreamUnderflowException: System.Exception {\n public StreamUnderflowException() {\n }\n}\n\nclass BigEndianStream {\n Stream stream;\n public BigEndianStream(Stream stream) {\n this.stream = stream;\n }\n\n public bool HasRemaining() {\n return (stream.Length - stream.Position) > 0;\n }\n\n public long Position {\n get => stream.Position;\n set => stream.Position = value;\n }\n\n public void WriteBytes(byte[] value) {\n stream.Write(value, 0, value.Length);\n }\n\n public void WriteByte(byte value) {\n stream.WriteByte(value);\n }\n\n public void WriteUShort(ushort value) {\n stream.WriteByte((byte)(value >> 8));\n stream.WriteByte((byte)value);\n }\n\n public void WriteUInt(uint value) {\n stream.WriteByte((byte)(value >> 24));\n stream.WriteByte((byte)(value >> 16));\n stream.WriteByte((byte)(value >> 8));\n stream.WriteByte((byte)value);\n }\n\n public void WriteULong(ulong value) {\n WriteUInt((uint)(value >> 32));\n WriteUInt((uint)value);\n }\n\n public void WriteSByte(sbyte value) {\n stream.WriteByte((byte)value);\n }\n\n public void WriteShort(short value) {\n WriteUShort((ushort)value);\n }\n\n public void WriteInt(int value) {\n WriteUInt((uint)value);\n }\n\n public void WriteFloat(float value) {\n unsafe {\n WriteInt(*((int*)&value));\n }\n }\n\n public void WriteLong(long value) {\n WriteULong((ulong)value);\n }\n\n public void WriteDouble(double value) {\n WriteLong(BitConverter.DoubleToInt64Bits(value));\n }\n\n public byte[] ReadBytes(int length) {\n CheckRemaining(length);\n byte[] result = new byte[length];\n stream.Read(result, 0, length);\n return result;\n }\n\n public byte ReadByte() {\n CheckRemaining(1);\n return Convert.ToByte(stream.ReadByte());\n }\n\n public ushort ReadUShort() {\n CheckRemaining(2);\n return (ushort)(stream.ReadByte() << 8 | stream.ReadByte());\n }\n\n public uint ReadUInt() {\n CheckRemaining(4);\n return (uint)(stream.ReadByte() << 24\n | stream.ReadByte() << 16\n | stream.ReadByte() << 8\n | stream.ReadByte());\n }\n\n public ulong ReadULong() {\n return (ulong)ReadUInt() << 32 | (ulong)ReadUInt();\n }\n\n public sbyte ReadSByte() {\n return (sbyte)ReadByte();\n }\n\n public short ReadShort() {\n return (short)ReadUShort();\n }\n\n public int ReadInt() {\n return (int)ReadUInt();\n }\n\n public float ReadFloat() {\n unsafe {\n int value = ReadInt();\n return *((float*)&value);\n }\n }\n\n public long ReadLong() {\n return (long)ReadULong();\n }\n\n public double ReadDouble() {\n return BitConverter.Int64BitsToDouble(ReadLong());\n }\n\n private void CheckRemaining(int length) {\n if (stream.Length - stream.Position < length) {\n throw new StreamUnderflowException();\n }\n }\n}\n\n// Contains loading, initialization code,\n// and the FFI Function declarations in a com.sun.jna.Library.\n\n\n// This is an implementation detail which will be called internally by the public API.\nstatic class _UniFFILib {\n static _UniFFILib() {\n _UniFFILib.uniffiCheckContractApiVersion();\n _UniFFILib.uniffiCheckApiChecksums();\n \n }\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_fullscreen(ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_monitor(RustBuffer @name,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_rect(uint @x,uint @y,uint @width,uint @height,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_window(uint @x,uint @y,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_window_by_title(RustBuffer @name,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_monitor(uint @x,uint @y,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_primary_monitor(ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_screen_dimensions(RustBuffer @name,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_working_area(ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rustbuffer_alloc(int @size,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rustbuffer_from_bytes(ForeignBytes @bytes,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rustbuffer_free(RustBuffer @buf,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rustbuffer_reserve(RustBuffer @buf,int @additional,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_continuation_callback_set(IntPtr @callback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u8(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern byte ffi_rust_lib_rust_future_complete_u8(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i8(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern sbyte ffi_rust_lib_rust_future_complete_i8(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u16(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort ffi_rust_lib_rust_future_complete_u16(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i16(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern short ffi_rust_lib_rust_future_complete_i16(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u32(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern uint ffi_rust_lib_rust_future_complete_u32(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i32(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern int ffi_rust_lib_rust_future_complete_i32(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u64(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ulong ffi_rust_lib_rust_future_complete_u64(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i64(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern long ffi_rust_lib_rust_future_complete_i64(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_f32(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_f32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_f32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern float ffi_rust_lib_rust_future_complete_f32(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_f64(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_f64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_f64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern double ffi_rust_lib_rust_future_complete_f64(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_pointer(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_pointer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_pointer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern IntPtr ffi_rust_lib_rust_future_complete_pointer(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_rust_buffer(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_rust_buffer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_rust_buffer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rust_future_complete_rust_buffer(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_void(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_void(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_void(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_complete_void(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_fullscreen(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_monitor(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_rect(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_window(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_window_by_title(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_monitor(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_primary_monitor(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_screen_dimensions(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_working_area(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern uint ffi_rust_lib_uniffi_contract_version(\n );\n\n \n\n static void uniffiCheckContractApiVersion() {\n var scaffolding_contract_version = _UniFFILib.ffi_rust_lib_uniffi_contract_version();\n if (24 != scaffolding_contract_version) {\n throw new UniffiContractVersionException($\"uniffi.rust_lib: uniffi bindings expected version `24`, library returned `{scaffolding_contract_version}`\");\n }\n }\n\n static void uniffiCheckApiChecksums() {\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_fullscreen();\n if (checksum != 57650) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_fullscreen` checksum `57650`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_monitor();\n if (checksum != 7847) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_monitor` checksum `7847`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_rect();\n if (checksum != 28248) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_rect` checksum `28248`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_window();\n if (checksum != 33381) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_window` checksum `33381`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_window_by_title();\n if (checksum != 11081) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_window_by_title` checksum `11081`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_monitor();\n if (checksum != 29961) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_monitor` checksum `29961`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_primary_monitor();\n if (checksum != 2303) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_primary_monitor` checksum `2303`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_screen_dimensions();\n if (checksum != 2379) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_screen_dimensions` checksum `2379`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_working_area();\n if (checksum != 50016) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_working_area` checksum `50016`, library returned `{checksum}`\");\n }\n }\n }\n}\n\n// Public interface members begin here.\n\n#pragma warning disable 8625\n\n\n\n\nclass FfiConverterUInt32: FfiConverter {\n public static FfiConverterUInt32 INSTANCE = new FfiConverterUInt32();\n\n public override uint Lift(uint value) {\n return value;\n }\n\n public override uint Read(BigEndianStream stream) {\n return stream.ReadUInt();\n }\n\n public override uint Lower(uint value) {\n return value;\n }\n\n public override int AllocationSize(uint value) {\n return 4;\n }\n\n public override void Write(uint value, BigEndianStream stream) {\n stream.WriteUInt(value);\n }\n}\n\n\n\nclass FfiConverterInt32: FfiConverter {\n public static FfiConverterInt32 INSTANCE = new FfiConverterInt32();\n\n public override int Lift(int value) {\n return value;\n }\n\n public override int Read(BigEndianStream stream) {\n return stream.ReadInt();\n }\n\n public override int Lower(int value) {\n return value;\n }\n\n public override int AllocationSize(int value) {\n return 4;\n }\n\n public override void Write(int value, BigEndianStream stream) {\n stream.WriteInt(value);\n }\n}\n\n\n\nclass FfiConverterString: FfiConverter {\n public static FfiConverterString INSTANCE = new FfiConverterString();\n\n // Note: we don't inherit from FfiConverterRustBuffer, because we use a\n // special encoding when lowering/lifting. We can use `RustBuffer.len` to\n // store our length and avoid writing it out to the buffer.\n public override string Lift(RustBuffer value) {\n try {\n var bytes = value.AsStream().ReadBytes(value.len);\n return System.Text.Encoding.UTF8.GetString(bytes);\n } finally {\n RustBuffer.Free(value);\n }\n }\n\n public override string Read(BigEndianStream stream) {\n var length = stream.ReadInt();\n var bytes = stream.ReadBytes(length);\n return System.Text.Encoding.UTF8.GetString(bytes);\n }\n\n public override RustBuffer Lower(string value) {\n var bytes = System.Text.Encoding.UTF8.GetBytes(value);\n var rbuf = RustBuffer.Alloc(bytes.Length);\n rbuf.AsWriteableStream().WriteBytes(bytes);\n return rbuf;\n }\n\n // TODO(CS)\n // We aren't sure exactly how many bytes our string will be once it's UTF-8\n // encoded. Allocate 3 bytes per unicode codepoint which will always be\n // enough.\n public override int AllocationSize(string value) {\n const int sizeForLength = 4;\n var sizeForString = value.Length * 3;\n return sizeForLength + sizeForString;\n }\n\n public override void Write(string value, BigEndianStream stream) {\n var bytes = System.Text.Encoding.UTF8.GetBytes(value);\n stream.WriteInt(bytes.Length);\n stream.WriteBytes(bytes);\n }\n}\n\n\n\n\nclass FfiConverterByteArray: FfiConverterRustBuffer {\n public static FfiConverterByteArray INSTANCE = new FfiConverterByteArray();\n\n public override byte[] Read(BigEndianStream stream) {\n var length = stream.ReadInt();\n return stream.ReadBytes(length);\n }\n\n public override int AllocationSize(byte[] value) {\n return 4 + value.Length;\n }\n\n public override void Write(byte[] value, BigEndianStream stream) {\n stream.WriteInt(value.Length);\n stream.WriteBytes(value);\n }\n}\n\n\n\ninternal record ImageData (\n byte[]? @image, \n uint @width, \n uint @height\n) {\n}\n\nclass FfiConverterTypeImageData: FfiConverterRustBuffer {\n public static FfiConverterTypeImageData INSTANCE = new FfiConverterTypeImageData();\n\n public override ImageData Read(BigEndianStream stream) {\n return new ImageData(\n @image: FfiConverterOptionalByteArray.INSTANCE.Read(stream),\n @width: FfiConverterUInt32.INSTANCE.Read(stream),\n @height: FfiConverterUInt32.INSTANCE.Read(stream)\n );\n }\n\n public override int AllocationSize(ImageData value) {\n return 0\n + FfiConverterOptionalByteArray.INSTANCE.AllocationSize(value.@image)\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@width)\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@height);\n }\n\n public override void Write(ImageData value, BigEndianStream stream) {\n FfiConverterOptionalByteArray.INSTANCE.Write(value.@image, stream);\n FfiConverterUInt32.INSTANCE.Write(value.@width, stream);\n FfiConverterUInt32.INSTANCE.Write(value.@height, stream);\n }\n}\n\n\n\ninternal record MonitorData (\n uint @width, \n uint @height, \n int @x, \n int @y, \n String @name\n) {\n}\n\nclass FfiConverterTypeMonitorData: FfiConverterRustBuffer {\n public static FfiConverterTypeMonitorData INSTANCE = new FfiConverterTypeMonitorData();\n\n public override MonitorData Read(BigEndianStream stream) {\n return new MonitorData(\n @width: FfiConverterUInt32.INSTANCE.Read(stream),\n @height: FfiConverterUInt32.INSTANCE.Read(stream),\n @x: FfiConverterInt32.INSTANCE.Read(stream),\n @y: FfiConverterInt32.INSTANCE.Read(stream),\n @name: FfiConverterString.INSTANCE.Read(stream)\n );\n }\n\n public override int AllocationSize(MonitorData value) {\n return 0\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@width)\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@height)\n + FfiConverterInt32.INSTANCE.AllocationSize(value.@x)\n + FfiConverterInt32.INSTANCE.AllocationSize(value.@y)\n + FfiConverterString.INSTANCE.AllocationSize(value.@name);\n }\n\n public override void Write(MonitorData value, BigEndianStream stream) {\n FfiConverterUInt32.INSTANCE.Write(value.@width, stream);\n FfiConverterUInt32.INSTANCE.Write(value.@height, stream);\n FfiConverterInt32.INSTANCE.Write(value.@x, stream);\n FfiConverterInt32.INSTANCE.Write(value.@y, stream);\n FfiConverterString.INSTANCE.Write(value.@name, stream);\n }\n}\n\n\n\n\n\ninternal class CaptureException: UniffiException {\n CaptureException(string message): base(message) {}\n\n // Each variant is a nested class\n // Flat enums carries a string error message, so no special implementation is necessary.\n \n public class Failed: CaptureException {\n public Failed(string message): base(message) {}\n }\n \n}\n\nclass FfiConverterTypeCaptureException : FfiConverterRustBuffer, CallStatusErrorHandler {\n public static FfiConverterTypeCaptureException INSTANCE = new FfiConverterTypeCaptureException();\n\n public override CaptureException Read(BigEndianStream stream) {\n var value = stream.ReadInt();\n switch (value) {\n case 1: return new CaptureException.Failed(FfiConverterString.INSTANCE.Read(stream));\n default:\n throw new InternalException(String.Format(\"invalid error value '{0}' in FfiConverterTypeCaptureException.Read()\", value));\n }\n }\n\n public override int AllocationSize(CaptureException value) {\n return 4 + FfiConverterString.INSTANCE.AllocationSize(value.Message);\n }\n\n public override void Write(CaptureException value, BigEndianStream stream) {\n switch (value) {\n case CaptureException.Failed:\n stream.WriteInt(1);\n break;\n default:\n throw new InternalException(String.Format(\"invalid error value '{0}' in FfiConverterTypeCaptureException.Write()\", value));\n }\n }\n}\n\n\n\n\nclass FfiConverterOptionalByteArray: FfiConverterRustBuffer {\n public static FfiConverterOptionalByteArray INSTANCE = new FfiConverterOptionalByteArray();\n\n public override byte[]? Read(BigEndianStream stream) {\n if (stream.ReadByte() == 0) {\n return null;\n }\n return FfiConverterByteArray.INSTANCE.Read(stream);\n }\n\n public override int AllocationSize(byte[]? value) {\n if (value == null) {\n return 1;\n } else {\n return 1 + FfiConverterByteArray.INSTANCE.AllocationSize((byte[])value);\n }\n }\n\n public override void Write(byte[]? value, BigEndianStream stream) {\n if (value == null) {\n stream.WriteByte(0);\n } else {\n stream.WriteByte(1);\n FfiConverterByteArray.INSTANCE.Write((byte[])value, stream);\n }\n }\n}\n#pragma warning restore 8625\ninternal static class RustLibMethods {\n public static ImageData CaptureFullscreen() {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_fullscreen( ref _status)\n));\n }\n\n\n public static ImageData CaptureMonitor(String @name) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_monitor(FfiConverterString.INSTANCE.Lower(@name), ref _status)\n));\n }\n\n\n public static ImageData CaptureRect(uint @x, uint @y, uint @width, uint @height) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_rect(FfiConverterUInt32.INSTANCE.Lower(@x), FfiConverterUInt32.INSTANCE.Lower(@y), FfiConverterUInt32.INSTANCE.Lower(@width), FfiConverterUInt32.INSTANCE.Lower(@height), ref _status)\n));\n }\n\n\n public static ImageData CaptureWindow(uint @x, uint @y) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_window(FfiConverterUInt32.INSTANCE.Lower(@x), FfiConverterUInt32.INSTANCE.Lower(@y), ref _status)\n));\n }\n\n\n /// \n public static ImageData CaptureWindowByTitle(String @name) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCallWithError(FfiConverterTypeCaptureException.INSTANCE, (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_window_by_title(FfiConverterString.INSTANCE.Lower(@name), ref _status)\n));\n }\n\n\n public static MonitorData GetMonitor(uint @x, uint @y) {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_monitor(FfiConverterUInt32.INSTANCE.Lower(@x), FfiConverterUInt32.INSTANCE.Lower(@y), ref _status)\n));\n }\n\n\n public static MonitorData GetPrimaryMonitor() {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_primary_monitor( ref _status)\n));\n }\n\n\n public static MonitorData GetScreenDimensions(String @name) {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_screen_dimensions(FfiConverterString.INSTANCE.Lower(@name), ref _status)\n));\n }\n\n\n public static MonitorData GetWorkingArea() {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_working_area( ref _status)\n));\n }\n\n\n}\n\n"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/RouletteWheel.Lifecycle.cs", "namespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic partial class RouletteWheel\n{\n /// \n /// Defines the animation state for the wheel visibility transitions.\n /// \n public enum AnimationState\n {\n /// \n /// Wheel is idle and not animating.\n /// \n Idle,\n\n /// \n /// Wheel is animating to an enabled state.\n /// \n AnimatingIn,\n\n /// \n /// Wheel is animating to a disabled state.\n /// \n AnimatingOut\n }\n\n private float _animationCurrentScale = 1.0f;\n\n private float _animationDuration = 0.3f; // Animation duration in seconds\n\n private float _animationStartScale = 1.0f;\n\n private float _animationStartTime = 0f;\n\n private float _animationTargetScale = 1.0f;\n\n /// \n /// Gets whether the wheel is currently enabled.\n /// \n public bool IsEnabled { get; private set; } = true;\n\n /// \n /// Gets the current animation state of the wheel.\n /// \n public AnimationState CurrentAnimationState { get; private set; } = AnimationState.Idle;\n\n /// \n /// Gets whether the wheel is currently animating.\n /// \n public bool IsAnimating => CurrentAnimationState != AnimationState.Idle;\n\n /// \n /// Enables the wheel with an optional animation.\n /// \n public void Enable()\n {\n if ( IsEnabled && CurrentAnimationState == AnimationState.Idle )\n {\n return;\n }\n\n IsEnabled = true;\n\n if ( !_config.CurrentValue.AnimateToggle )\n {\n CurrentAnimationState = AnimationState.Idle;\n _animationCurrentScale = 1.0f;\n\n return;\n }\n\n CurrentAnimationState = AnimationState.AnimatingIn;\n _animationStartTime = _time;\n _animationDuration = _config.CurrentValue.AnimationDuration;\n _animationStartScale = _animationCurrentScale;\n _animationTargetScale = 1.0f;\n }\n\n /// \n /// Disables the wheel with an optional animation.\n /// \n public void Disable()\n {\n if ( !IsEnabled && CurrentAnimationState == AnimationState.Idle )\n {\n return;\n }\n\n IsEnabled = false;\n\n if ( !_config.CurrentValue.AnimateToggle )\n {\n CurrentAnimationState = AnimationState.Idle;\n _animationCurrentScale = 0.0f;\n\n return;\n }\n\n CurrentAnimationState = AnimationState.AnimatingOut;\n _animationStartTime = _time;\n _animationDuration = _config.CurrentValue.AnimationDuration;\n _animationStartScale = _animationCurrentScale;\n _animationTargetScale = 0.0f;\n }\n\n /// \n /// Toggles the wheel's enabled state with an optional animation.\n /// \n /// Whether to animate the transition.\n /// Duration of the animation in seconds.\n public void Toggle()\n {\n if ( IsEnabled )\n {\n Disable();\n }\n else\n {\n Enable();\n }\n }\n\n private void UpdateVisibilityAnimation()\n {\n if ( CurrentAnimationState == AnimationState.Idle )\n {\n return;\n }\n\n var elapsed = _time - _animationStartTime;\n var progress = Math.Min(elapsed / _animationDuration, 1.0f);\n\n // Apply easing function to the progress\n var easedProgress = EaseOutBack(progress);\n\n // Calculate current scale based on progress\n _animationCurrentScale = _animationStartScale + (_animationTargetScale - _animationStartScale) * easedProgress;\n\n // Check if animation is complete\n if ( progress >= 1.0f )\n {\n CurrentAnimationState = AnimationState.Idle;\n _animationCurrentScale = _animationTargetScale;\n }\n }\n\n private static float EaseOutBack(float t)\n {\n const float c1 = 1.70158f;\n const float c3 = c1 + 1;\n\n return 1 + c3 * MathF.Pow(t - 1, 3) + c1 * MathF.Pow(t - 1, 2);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/LexiconEntryJsonConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Custom JSON converter for lexicon entries\n/// \npublic class LexiconEntryJsonConverter : JsonConverter\n{\n public override LexiconEntry Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n var entry = new LexiconEntry();\n\n if ( reader.TokenType == JsonTokenType.String )\n {\n entry.Simple = reader.GetString();\n }\n else if ( reader.TokenType == JsonTokenType.StartObject )\n {\n entry.ByTag = JsonSerializer.Deserialize>(ref reader, options);\n }\n else\n {\n throw new JsonException($\"Unexpected token {reader.TokenType} when deserializing lexicon entry\");\n }\n\n return entry;\n }\n\n public override void Write(Utf8JsonWriter writer, LexiconEntry value, JsonSerializerOptions options)\n {\n if ( value.IsSimple )\n {\n writer.WriteStringValue(value.Simple);\n }\n else\n {\n JsonSerializer.Serialize(writer, value.ByTag, options);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppDelegate.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// アプリケーションクラス。\n/// Cubism SDK の管理を行う。\n/// \npublic class LAppDelegate : IDisposable\n{\n /// \n /// Cubism SDK Allocator\n /// \n private readonly LAppAllocator _cubismAllocator;\n\n /// \n /// Cubism SDK Option\n /// \n private readonly Option _cubismOption;\n\n /// \n /// クリックしているか\n /// \n private bool _captured;\n\n /// \n /// マウスX座標\n /// \n private float _mouseX;\n\n /// \n /// マウスY座標\n /// \n private float _mouseY;\n\n /// \n /// Initialize関数で設定したウィンドウ高さ\n /// \n private int _windowHeight;\n\n /// \n /// Initialize関数で設定したウィンドウ幅\n /// \n private int _windowWidth;\n\n public LAppDelegate(OpenGLApi gl, LogFunction log)\n {\n GL = gl;\n\n View = new LAppView(this);\n TextureManager = new LAppTextureManager(this);\n _cubismAllocator = new LAppAllocator();\n\n //テクスチャサンプリング設定\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);\n\n //透過設定\n GL.Enable(GL.GL_BLEND);\n GL.BlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);\n\n // ウィンドウサイズ記憶\n GL.GetWindowSize(out _windowWidth, out _windowHeight);\n\n //AppViewの初期化\n View.Initialize();\n\n // Cubism SDK の初期化\n _cubismOption = new Option { LogFunction = log, LoggingLevel = LAppDefine.CubismLoggingLevel };\n CubismFramework.StartUp(_cubismAllocator, _cubismOption);\n\n //Initialize cubism\n CubismFramework.Initialize();\n\n //load model\n Live2dManager = new LAppLive2DManager(this);\n\n LAppPal.DeltaTime = 0;\n }\n\n /// \n /// テクスチャマネージャー\n /// \n public LAppTextureManager TextureManager { get; private set; }\n\n public LAppLive2DManager Live2dManager { get; private set; }\n\n public OpenGLApi GL { get; }\n\n /// \n /// View情報\n /// \n public LAppView View { get; private set; }\n\n public CubismTextureColor BGColor { get; set; } = new(0, 0, 0, 0);\n\n /// \n /// 解放する。\n /// \n public void Dispose()\n {\n // リソースを解放\n Live2dManager.Dispose();\n\n //Cubism SDK の解放\n CubismFramework.Dispose();\n\n GC.SuppressFinalize(this);\n }\n\n public void Resize()\n {\n GL.GetWindowSize(out var width, out var height);\n if ( (_windowWidth != width || _windowHeight != height) && width > 0 && height > 0 )\n {\n //AppViewの初期化\n View.Initialize();\n // サイズを保存しておく\n _windowWidth = width;\n _windowHeight = height;\n }\n }\n\n public void Update(float tick)\n {\n // 時間更新\n LAppPal.DeltaTime = tick;\n }\n\n /// \n /// 実行処理。\n /// \n public void Run()\n {\n // 画面の初期化\n GL.ClearColor(BGColor.R, BGColor.G, BGColor.B, BGColor.A);\n GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n GL.ClearDepthf(1.0f);\n\n //描画更新\n View.Render();\n }\n\n /// \n /// OpenGL用 glfwSetMouseButtonCallback用関数。\n /// \n /// ボタン種類\n /// 実行結果\n public void OnMouseCallBack(bool press)\n {\n if ( press )\n {\n _captured = true;\n View.OnTouchesBegan(_mouseX, _mouseY);\n }\n else\n {\n if ( _captured )\n {\n _captured = false;\n View.OnTouchesEnded(_mouseX, _mouseY);\n }\n }\n }\n\n /// \n /// OpenGL用 glfwSetCursorPosCallback用関数。\n /// \n /// x座標\n /// x座標\n public void OnMouseCallBack(float x, float y)\n {\n if ( !_captured )\n {\n return;\n }\n\n _mouseX = x;\n _mouseY = y;\n\n View.OnTouchesMoved(_mouseX, _mouseY);\n }\n\n public void StartSpeaking(string filePath) { Live2dManager.StartSpeaking(filePath); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/InteractionTurn.cs", "using OpenAI.Chat;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic class InteractionTurn\n{\n public InteractionTurn(Guid turnId, IEnumerable participantIds, DateTimeOffset startTime, DateTimeOffset? endTime, IEnumerable messages, bool wasInterrupted)\n {\n TurnId = turnId;\n ParticipantIds = participantIds.ToList().AsReadOnly();\n StartTime = startTime;\n EndTime = endTime;\n Messages = messages.ToList();\n WasInterrupted = wasInterrupted;\n }\n\n private InteractionTurn(Guid turnId, IEnumerable participantIds, DateTimeOffset startTime, IEnumerable messages)\n {\n TurnId = turnId;\n ParticipantIds = participantIds.ToList().AsReadOnly();\n StartTime = startTime;\n EndTime = null;\n Messages = messages.Select(m => new ChatMessage(m.MessageId, m.ParticipantId, m.ParticipantName, m.Text, m.Timestamp, m.IsPartial, m.Role)).ToList();\n WasInterrupted = false;\n }\n\n public Guid TurnId { get; }\n\n public IReadOnlyList ParticipantIds { get; }\n\n public DateTimeOffset StartTime { get; }\n\n public DateTimeOffset? EndTime { get; internal set; }\n\n public List Messages { get; }\n\n public bool WasInterrupted { get; internal set; }\n\n internal InteractionTurn CreateSnapshot() { return new InteractionTurn(TurnId, ParticipantIds, StartTime, Messages); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TextNormalizer.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Normalizes text for better TTS pronunciation\n/// \npublic class TextNormalizer : ITextNormalizer\n{\n // Whitespace normalization\n private static readonly Regex NonStandardWhitespaceRegex = new(@\"[^\\S \\n]\", RegexOptions.Compiled);\n\n private static readonly Regex MultipleSpacesRegex = new(@\" {2,}\", RegexOptions.Compiled);\n\n private static readonly Regex SpaceBeforePunctuationRegex = new(@\"\\s+([.,;:?!])\", RegexOptions.Compiled);\n\n // Quotation marks\n private static readonly Regex CurlyQuotesRegex = new(@\"[\\u2018\\u2019\\u201C\\u201D]\", RegexOptions.Compiled);\n\n // Abbreviations\n private static readonly Dictionary CommonAbbreviations = new() {\n { new Regex(@\"\\bDr\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Doctor\" },\n { new Regex(@\"\\bMr\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Mister\" },\n { new Regex(@\"\\bMs\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Miss\" },\n { new Regex(@\"\\bMrs\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Missus\" },\n { new Regex(@\"\\betc\\.(?!\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"etcetera\" },\n { new Regex(@\"\\bSt\\.(?=\\s+)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Street\" },\n { new Regex(@\"\\bAve\\.(?=\\s+)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Avenue\" },\n { new Regex(@\"\\bRd\\.(?=\\s+)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Road\" },\n { new Regex(@\"\\bPh\\.D\\.(?=\\s+|\\b)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"PhD\" }\n };\n\n // Number regex for finding numeric patterns\n private static readonly Regex NumberRegex = new(@\"(? _logger;\n\n public TextNormalizer(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }\n\n /// \n /// Normalizes text for TTS synthesis\n /// \n public string Normalize(string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n return string.Empty;\n }\n\n try\n {\n text = text.Normalize(NormalizationForm.FormC);\n\n text = CleanupLines(text);\n\n text = NormalizeCharacters(text);\n\n text = ProcessUrlsAndEmails(text);\n\n text = ExpandAbbreviations(text);\n\n text = NormalizeWhitespaceAndPunctuation(text);\n\n text = RemoveInvalidSurrogates(text);\n\n return text.Trim();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during text normalization\");\n\n return text;\n }\n }\n\n private string CleanupLines(string text)\n {\n // Split by line, trim each line, and remove empty ones\n var lines = text.Split('\\n');\n var nonEmptyLines = new List();\n\n foreach ( var line in lines )\n {\n var trimmedLine = line.Trim();\n if ( !string.IsNullOrEmpty(trimmedLine) )\n {\n nonEmptyLines.Add(trimmedLine);\n }\n }\n\n return string.Join(\"\\n\", nonEmptyLines);\n }\n\n private string NormalizeCharacters(string text)\n {\n // Convert curly quotes to straight quotes\n text = CurlyQuotesRegex.Replace(text, match =>\n {\n return match.Value switch {\n \"\\u2018\" or \"\\u2019\" => \"'\",\n \"\\u201C\" or \"\\u201D\" => \"\\\"\",\n _ => match.Value\n };\n });\n\n // Replace other special characters\n text = text\n .Replace(\"…\", \"...\")\n .Replace(\"–\", \"-\")\n .Replace(\"—\", \" - \")\n .Replace(\"•\", \"*\")\n .Replace(\"®\", \" registered \")\n .Replace(\"©\", \" copyright \")\n .Replace(\"™\", \" trademark \");\n\n // Convert Unicode fractions to text\n text = text\n .Replace(\"½\", \" one half \")\n .Replace(\"¼\", \" one quarter \")\n .Replace(\"¾\", \" three quarters \");\n\n return text;\n }\n\n private string RemoveInvalidSurrogates(string input)\n {\n var sb = new StringBuilder();\n for ( var i = 0; i < input.Length; i++ )\n {\n if ( char.IsHighSurrogate(input[i]) )\n {\n // Check if there's a valid low surrogate following\n if ( i + 1 < input.Length && char.IsLowSurrogate(input[i + 1]) )\n {\n sb.Append(input[i]);\n sb.Append(input[i + 1]);\n i++; // Skip the next character as we've already handled it\n }\n // Otherwise, skip the invalid high surrogate\n }\n else if ( !char.IsLowSurrogate(input[i]) )\n {\n // Keep normal characters, skip orphaned low surrogates\n sb.Append(input[i]);\n }\n }\n\n return sb.ToString();\n }\n\n private bool IsValidUtf16(string input)\n {\n for ( var i = 0; i < input.Length; i++ )\n {\n if ( char.IsHighSurrogate(input[i]) )\n {\n if ( i + 1 >= input.Length || !char.IsLowSurrogate(input[i + 1]) )\n {\n return false;\n }\n\n i++; // Skip the low surrogate\n }\n else if ( char.IsLowSurrogate(input[i]) )\n {\n return false; // Unexpected low surrogate\n }\n }\n\n return true;\n }\n\n private string ProcessUrlsAndEmails(string text)\n {\n // Replace URLs with placeholder text\n text = UrlRegex.Replace(text, match => \" URL \");\n\n // Replace email addresses with readable text\n text = EmailRegex.Replace(text, match =>\n {\n var parts = match.Value.Split('@');\n if ( parts.Length != 2 )\n {\n return \" email address \";\n }\n\n var username = string.Join(\" \", SplitCamelCase(parts[0]));\n var domain = parts[1].Replace(\".\", \" dot \");\n\n return $\" {username} at {domain} \";\n });\n\n return text;\n }\n\n private IEnumerable SplitCamelCase(string text)\n {\n var buffer = new StringBuilder();\n\n foreach ( var c in text )\n {\n if ( char.IsUpper(c) && buffer.Length > 0 )\n {\n yield return buffer.ToString();\n buffer.Clear();\n }\n\n buffer.Append(char.ToLower(c));\n }\n\n if ( buffer.Length > 0 )\n {\n yield return buffer.ToString();\n }\n }\n\n private string ExpandAbbreviations(string text)\n {\n foreach ( var kvp in CommonAbbreviations )\n {\n text = kvp.Key.Replace(text, kvp.Value);\n }\n\n return text;\n }\n\n private string NormalizeWhitespaceAndPunctuation(string text)\n {\n // Replace non-standard whitespace with normal spaces\n text = NonStandardWhitespaceRegex.Replace(text, \" \");\n\n // Collapse multiple spaces into one\n text = MultipleSpacesRegex.Replace(text, \" \");\n\n // Fix spacing around punctuation\n text = SpaceBeforePunctuationRegex.Replace(text, \"$1\");\n\n return text;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ContextualPhonemeEntry.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record ContextualPhonemeEntry(IReadOnlyDictionary Forms) : PhonemeEntry\n{\n public string? GetForm(string? tag, TokenContext? ctx)\n {\n // First try exact tag match\n if ( tag != null && Forms.TryGetValue(tag, out var exactMatch) )\n {\n return exactMatch;\n }\n\n // Try context-specific form\n if ( ctx?.FutureVowel == null && Forms.TryGetValue(\"None\", out var noneForm) )\n {\n return noneForm;\n }\n\n // Try parent tag\n var parentTag = LexiconUtils.GetParentTag(tag);\n if ( parentTag != null && Forms.TryGetValue(parentTag, out var parentMatch) )\n {\n return parentMatch;\n }\n\n // Finally, use default\n return Forms.TryGetValue(\"DEFAULT\", out var defaultForm) ? defaultForm : null;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/WavUtils.cs", "namespace PersonaEngine.Lib.Utils;\n\npublic class WavUtils\n{\n private const int RIFF_CHUNK_ID = 0x46464952; // \"RIFF\" in ASCII\n\n private const int WAVE_FORMAT = 0x45564157; // \"WAVE\" in ASCII\n\n private const int FMT_CHUNK_ID = 0x20746D66; // \"fmt \" in ASCII\n\n private const int DATA_CHUNK_ID = 0x61746164; // \"data\" in ASCII\n\n private const int PCM_FORMAT = 1; // PCM audio format\n\n public static void SaveToWav(Memory samples, string filePath, int sampleRate = 44100, int channels = 1)\n {\n using (var writer = new BinaryWriter(File.OpenWrite(filePath)))\n {\n WriteWavFile(writer, samples, sampleRate, channels);\n }\n }\n\n public static void AppendToWav(Memory samples, string filePath)\n {\n // First, read the existing WAV file header\n WavHeader header;\n long dataPosition;\n using (var reader = new BinaryReader(File.OpenRead(filePath)))\n {\n header = ReadWavHeader(reader);\n dataPosition = reader.BaseStream.Position;\n }\n\n // Open file for writing and seek to end of data\n using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))\n using (var writer = new BinaryWriter(stream))\n {\n stream.Seek(0, SeekOrigin.End);\n\n // Write new samples\n var span = samples.Span;\n for ( var i = 0; i < span.Length; i++ )\n {\n var pcm = (short)(span[i] * short.MaxValue);\n writer.Write(pcm);\n }\n\n // Update file size in header\n var newDataSize = header.DataSize + samples.Length * sizeof(short);\n var newFileSize = newDataSize + 44 - 8; // 44 is header size, subtract 8 for RIFF header\n\n stream.Seek(4, SeekOrigin.Begin);\n writer.Write(newFileSize);\n\n // Update data chunk size\n stream.Seek(dataPosition - 4, SeekOrigin.Begin);\n writer.Write(newDataSize);\n }\n }\n\n private static void WriteWavFile(BinaryWriter writer, Memory samples, int sampleRate, int channels)\n {\n var bytesPerSample = sizeof(short); // We'll convert float to 16-bit PCM\n var dataSize = samples.Length * bytesPerSample;\n var headerSize = 44; // Standard WAV header size\n var fileSize = headerSize + dataSize - 8; // Total file size - 8 bytes\n\n // Write WAV header\n writer.Write(RIFF_CHUNK_ID); // \"RIFF\" chunk\n writer.Write(fileSize); // File size - 8\n writer.Write(WAVE_FORMAT); // \"WAVE\" format\n\n // Write format chunk\n writer.Write(FMT_CHUNK_ID); // \"fmt \" chunk\n writer.Write(16); // Format chunk size (16 for PCM)\n writer.Write((short)PCM_FORMAT); // Audio format (1 for PCM)\n writer.Write((short)channels); // Number of channels\n writer.Write(sampleRate); // Sample rate\n writer.Write(sampleRate * channels * bytesPerSample); // Byte rate\n writer.Write((short)(channels * bytesPerSample)); // Block align\n writer.Write((short)(bytesPerSample * 8)); // Bits per sample\n\n // Write data chunk\n writer.Write(DATA_CHUNK_ID); // \"data\" chunk\n writer.Write(dataSize); // Data size\n\n // Write audio samples\n var span = samples.Span;\n for ( var i = 0; i < span.Length; i++ )\n {\n var pcm = (short)(span[i] * short.MaxValue);\n writer.Write(pcm);\n }\n }\n\n private static WavHeader ReadWavHeader(BinaryReader reader)\n {\n // Verify RIFF header\n if ( reader.ReadInt32() != RIFF_CHUNK_ID )\n {\n throw new InvalidDataException(\"Not a valid RIFF file\");\n }\n\n var header = new WavHeader { FileSize = reader.ReadInt32() };\n\n // Verify WAVE format\n if ( reader.ReadInt32() != WAVE_FORMAT )\n {\n throw new InvalidDataException(\"Not a valid WAVE file\");\n }\n\n // Read format chunk\n if ( reader.ReadInt32() != FMT_CHUNK_ID )\n {\n throw new InvalidDataException(\"Missing format chunk\");\n }\n\n var fmtSize = reader.ReadInt32();\n if ( reader.ReadInt16() != PCM_FORMAT )\n {\n throw new InvalidDataException(\"Unsupported audio format (must be PCM)\");\n }\n\n header.Channels = reader.ReadInt16();\n header.SampleRate = reader.ReadInt32();\n header.ByteRate = reader.ReadInt32();\n header.BlockAlign = reader.ReadInt16();\n header.BitsPerSample = reader.ReadInt16();\n\n // Skip any extra format bytes\n if ( fmtSize > 16 )\n {\n reader.BaseStream.Seek(fmtSize - 16, SeekOrigin.Current);\n }\n\n // Find data chunk\n while ( true )\n {\n var chunkId = reader.ReadInt32();\n var chunkSize = reader.ReadInt32();\n\n if ( chunkId == DATA_CHUNK_ID )\n {\n header.DataSize = chunkSize;\n\n break;\n }\n\n reader.BaseStream.Seek(chunkSize, SeekOrigin.Current);\n\n if ( reader.BaseStream.Position >= reader.BaseStream.Length )\n {\n throw new InvalidDataException(\"Missing data chunk\");\n }\n }\n\n return header;\n }\n\n public static bool ValidateWavFile(string filePath)\n {\n try\n {\n using (var reader = new BinaryReader(File.OpenRead(filePath)))\n {\n ReadWavHeader(reader);\n\n return true;\n }\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n private struct WavHeader\n {\n public int FileSize;\n\n public int Channels;\n\n public int SampleRate;\n\n public int ByteRate;\n\n public short BlockAlign;\n\n public short BitsPerSample;\n\n public int DataSize;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiThemeManager.cs", "using Hexa.NET.ImGui;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements UI theming management\n/// \npublic class UiThemeManager : IUiThemeManager\n{\n private UiTheme _currentTheme = new();\n\n public void ApplyTheme()\n {\n var style = ImGui.GetStyle();\n\n style.Colors[(int)ImGuiCol.Text] = _currentTheme.TextColor;\n style.Colors[(int)ImGuiCol.TextDisabled] = _currentTheme.TextDisabledColor;\n style.Colors[(int)ImGuiCol.WindowBg] = _currentTheme.WindowBgColor;\n style.Colors[(int)ImGuiCol.ChildBg] = _currentTheme.ChildBgColor;\n style.Colors[(int)ImGuiCol.PopupBg] = _currentTheme.PopupBgColor;\n style.Colors[(int)ImGuiCol.Border] = _currentTheme.BorderColor;\n style.Colors[(int)ImGuiCol.BorderShadow] = _currentTheme.BorderShadowColor;\n style.Colors[(int)ImGuiCol.FrameBg] = _currentTheme.FrameBgColor;\n style.Colors[(int)ImGuiCol.FrameBgHovered] = _currentTheme.FrameBgHoveredColor;\n style.Colors[(int)ImGuiCol.FrameBgActive] = _currentTheme.FrameBgActiveColor;\n style.Colors[(int)ImGuiCol.TitleBg] = _currentTheme.TitleBgColor;\n style.Colors[(int)ImGuiCol.TitleBgActive] = _currentTheme.TitleBgActiveColor;\n style.Colors[(int)ImGuiCol.TitleBgCollapsed] = _currentTheme.TitleBgCollapsedColor;\n style.Colors[(int)ImGuiCol.MenuBarBg] = _currentTheme.MenuBarBgColor;\n style.Colors[(int)ImGuiCol.ScrollbarBg] = _currentTheme.ScrollbarBgColor;\n style.Colors[(int)ImGuiCol.ScrollbarGrab] = _currentTheme.ScrollbarGrabColor;\n style.Colors[(int)ImGuiCol.ScrollbarGrabHovered] = _currentTheme.ScrollbarGrabHoveredColor;\n style.Colors[(int)ImGuiCol.ScrollbarGrabActive] = _currentTheme.ScrollbarGrabActiveColor;\n style.Colors[(int)ImGuiCol.CheckMark] = _currentTheme.CheckMarkColor;\n style.Colors[(int)ImGuiCol.SliderGrab] = _currentTheme.SliderGrabColor;\n style.Colors[(int)ImGuiCol.SliderGrabActive] = _currentTheme.SliderGrabActiveColor;\n style.Colors[(int)ImGuiCol.Button] = _currentTheme.ButtonColor;\n style.Colors[(int)ImGuiCol.ButtonHovered] = _currentTheme.ButtonHoveredColor;\n style.Colors[(int)ImGuiCol.ButtonActive] = _currentTheme.ButtonActiveColor;\n style.Colors[(int)ImGuiCol.Header] = _currentTheme.HeaderColor;\n style.Colors[(int)ImGuiCol.HeaderHovered] = _currentTheme.HeaderHoveredColor;\n style.Colors[(int)ImGuiCol.HeaderActive] = _currentTheme.HeaderActiveColor;\n style.Colors[(int)ImGuiCol.Separator] = _currentTheme.SeparatorColor;\n style.Colors[(int)ImGuiCol.SeparatorHovered] = _currentTheme.SeparatorHoveredColor;\n style.Colors[(int)ImGuiCol.SeparatorActive] = _currentTheme.SeparatorActiveColor;\n style.Colors[(int)ImGuiCol.ResizeGrip] = _currentTheme.ResizeGripColor;\n style.Colors[(int)ImGuiCol.ResizeGripHovered] = _currentTheme.ResizeGripHoveredColor;\n style.Colors[(int)ImGuiCol.ResizeGripActive] = _currentTheme.ResizeGripActiveColor;\n style.Colors[(int)ImGuiCol.Tab] = _currentTheme.TabColor;\n style.Colors[(int)ImGuiCol.TabHovered] = _currentTheme.TabHoveredColor;\n style.Colors[(int)ImGuiCol.TabSelected] = _currentTheme.TabActiveColor;\n style.Colors[(int)ImGuiCol.TabDimmed] = _currentTheme.TabUnfocusedColor;\n style.Colors[(int)ImGuiCol.TabDimmedSelected] = _currentTheme.TabUnfocusedActiveColor;\n style.Colors[(int)ImGuiCol.PlotLines] = _currentTheme.PlotLinesColor;\n style.Colors[(int)ImGuiCol.PlotLinesHovered] = _currentTheme.PlotLinesHoveredColor;\n style.Colors[(int)ImGuiCol.PlotHistogram] = _currentTheme.PlotHistogramColor;\n style.Colors[(int)ImGuiCol.PlotHistogramHovered] = _currentTheme.PlotHistogramHoveredColor;\n style.Colors[(int)ImGuiCol.TableHeaderBg] = _currentTheme.TableHeaderBgColor;\n style.Colors[(int)ImGuiCol.TableBorderStrong] = _currentTheme.TableBorderStrongColor;\n style.Colors[(int)ImGuiCol.TableBorderLight] = _currentTheme.TableBorderLightColor;\n style.Colors[(int)ImGuiCol.TableRowBg] = _currentTheme.TableRowBgColor;\n style.Colors[(int)ImGuiCol.TableRowBgAlt] = _currentTheme.TableRowBgAltColor;\n style.Colors[(int)ImGuiCol.TextSelectedBg] = _currentTheme.TextSelectedBgColor;\n style.Colors[(int)ImGuiCol.DragDropTarget] = _currentTheme.DragDropTargetColor;\n style.Colors[(int)ImGuiCol.NavWindowingHighlight] = _currentTheme.NavWindowingHighlightColor;\n style.Colors[(int)ImGuiCol.NavWindowingDimBg] = _currentTheme.NavWindowingDimBgColor;\n style.Colors[(int)ImGuiCol.ModalWindowDimBg] = _currentTheme.ModalWindowDimBgColor;\n\n // Set style properties\n style.Alpha = _currentTheme.Alpha;\n style.DisabledAlpha = _currentTheme.DisabledAlpha;\n style.WindowRounding = _currentTheme.WindowRounding;\n style.WindowBorderSize = _currentTheme.WindowBorderSize;\n style.WindowMinSize = _currentTheme.WindowMinSize;\n style.WindowTitleAlign = _currentTheme.WindowTitleAlign;\n\n // Handle WindowMenuButtonPosition\n if ( _currentTheme.WindowMenuButtonPosition == \"Left\" )\n {\n style.WindowMenuButtonPosition = ImGuiDir.Left;\n }\n else if ( _currentTheme.WindowMenuButtonPosition == \"Right\" )\n {\n style.WindowMenuButtonPosition = ImGuiDir.Right;\n }\n\n style.ChildRounding = _currentTheme.ChildRounding;\n style.ChildBorderSize = _currentTheme.ChildBorderSize;\n style.PopupRounding = _currentTheme.PopupRounding;\n style.PopupBorderSize = _currentTheme.PopupBorderSize;\n style.FrameRounding = _currentTheme.FrameRounding;\n style.FrameBorderSize = _currentTheme.FrameBorderSize;\n style.ItemSpacing = _currentTheme.ItemSpacing;\n style.ItemInnerSpacing = _currentTheme.ItemInnerSpacing;\n style.CellPadding = _currentTheme.CellPadding;\n style.IndentSpacing = _currentTheme.IndentSpacing;\n style.ColumnsMinSpacing = _currentTheme.ColumnsMinSpacing;\n style.ScrollbarSize = _currentTheme.ScrollbarSize;\n style.ScrollbarRounding = _currentTheme.ScrollbarRounding;\n style.GrabMinSize = _currentTheme.GrabMinSize;\n style.GrabRounding = _currentTheme.GrabRounding;\n style.TabRounding = _currentTheme.TabRounding;\n style.TabBorderSize = _currentTheme.TabBorderSize;\n style.TabCloseButtonMinWidthSelected = _currentTheme.TabCloseButtonMinWidthSelected;\n style.TabCloseButtonMinWidthUnselected = _currentTheme.TabCloseButtonMinWidthUnselected;\n\n // Handle ColorButtonPosition\n if ( _currentTheme.ColorButtonPosition == \"Left\" )\n {\n style.ColorButtonPosition = ImGuiDir.Left;\n }\n else if ( _currentTheme.ColorButtonPosition == \"Right\" )\n {\n style.ColorButtonPosition = ImGuiDir.Right;\n }\n\n style.ButtonTextAlign = _currentTheme.ButtonTextAlign;\n style.SelectableTextAlign = _currentTheme.SelectableTextAlign;\n style.WindowPadding = _currentTheme.WindowPadding;\n style.FramePadding = _currentTheme.FramePadding;\n }\n\n public void SetTheme(UiTheme theme)\n {\n _currentTheme = theme;\n ApplyTheme();\n }\n\n public UiTheme GetCurrentTheme() { return _currentTheme; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/ACubismMotion.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションの抽象基底クラス。MotionQueueManagerによってモーションの再生を管理する。\n/// \npublic abstract class ACubismMotion\n{\n protected readonly List FiredEventValues = [];\n\n /// \n /// コンストラクタ。\n /// \n public ACubismMotion()\n {\n FadeInSeconds = -1.0f;\n FadeOutSeconds = -1.0f;\n Weight = 1.0f;\n }\n\n /// \n /// フェードインにかかる時間[秒]\n /// \n public float FadeInSeconds { get; set; }\n\n /// \n /// フェードアウトにかかる時間[秒]\n /// \n public float FadeOutSeconds { get; set; }\n\n /// \n /// モーションの重み\n /// \n public float Weight { get; set; }\n\n /// \n /// モーション再生の開始時刻[秒]\n /// \n public float OffsetSeconds { get; set; }\n\n // モーション再生終了コールバック関数\n public FinishedMotionCallback? OnFinishedMotion { get; set; }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// CubismMotionQueueManagerで管理されているモーション\n /// デルタ時間の積算値[秒]\n public void UpdateParameters(CubismModel model, CubismMotionQueueEntry motionQueueEntry, float userTimeSeconds)\n {\n if ( !motionQueueEntry.Available || motionQueueEntry.Finished )\n {\n return;\n }\n\n SetupMotionQueueEntry(motionQueueEntry, userTimeSeconds);\n\n var fadeWeight = UpdateFadeWeight(motionQueueEntry, userTimeSeconds);\n\n //---- 全てのパラメータIDをループする ----\n DoUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry);\n\n //後処理\n //終了時刻を過ぎたら終了フラグを立てる(CubismMotionQueueManager)\n if ( motionQueueEntry.EndTime > 0 && motionQueueEntry.EndTime < userTimeSeconds )\n {\n motionQueueEntry.Finished = true; //終了\n }\n }\n\n /// \n /// モーションの再生を開始するためのセットアップを行う。\n /// \n /// CubismMotionQueueManagerによって管理されるモーション\n /// 総再生時間(秒)\n public void SetupMotionQueueEntry(CubismMotionQueueEntry motionQueueEntry, float userTimeSeconds)\n {\n if ( !motionQueueEntry.Available || motionQueueEntry.Finished )\n {\n return;\n }\n\n if ( motionQueueEntry.Started )\n {\n return;\n }\n\n motionQueueEntry.Started = true;\n motionQueueEntry.StartTime = userTimeSeconds - OffsetSeconds; //モーションの開始時刻を記録\n motionQueueEntry.FadeInStartTime = userTimeSeconds; //フェードインの開始時刻\n\n var duration = GetDuration();\n\n if ( motionQueueEntry.EndTime < 0 )\n {\n //開始していないうちに終了設定している場合がある。\n motionQueueEntry.EndTime = duration <= 0 ? -1 : motionQueueEntry.StartTime + duration;\n //duration == -1 の場合はループする\n }\n }\n\n /// \n /// モーションのウェイトを更新する。\n /// \n /// CubismMotionQueueManagerで管理されているモーション\n /// デルタ時間の積算値[秒]\n /// \n /// \n public float UpdateFadeWeight(CubismMotionQueueEntry? motionQueueEntry, float userTimeSeconds)\n {\n if ( motionQueueEntry == null )\n {\n CubismLog.Error(\"motionQueueEntry is null.\");\n\n return 0;\n }\n\n var fadeWeight = Weight; //現在の値と掛け合わせる割合\n\n //---- フェードイン・アウトの処理 ----\n //単純なサイン関数でイージングする\n var fadeIn = FadeInSeconds == 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((userTimeSeconds - motionQueueEntry.FadeInStartTime) / FadeInSeconds);\n\n var fadeOut = FadeOutSeconds == 0.0f || motionQueueEntry.EndTime < 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((motionQueueEntry.EndTime - userTimeSeconds) / FadeOutSeconds);\n\n fadeWeight = fadeWeight * fadeIn * fadeOut;\n\n motionQueueEntry.SetState(userTimeSeconds, fadeWeight);\n\n if ( 0.0f > fadeWeight || fadeWeight > 1.0f )\n {\n throw new Exception(\"fadeWeight out of range\");\n }\n\n return fadeWeight;\n }\n\n /// \n /// モーションの長さを取得する。\n /// ループのときは「-1」。\n /// ループではない場合は、オーバーライドする。\n /// 正の値の時は取得される時間で終了する。\n /// 「-1」のときは外部から停止命令が無い限り終わらない処理となる。\n /// \n /// モーションの長さ[秒]\n public virtual float GetDuration() { return -1.0f; }\n\n /// \n /// モーションのループ1回分の長さを取得する。\n /// ループしない場合は GetDuration()と同じ値を返す。\n /// ループ一回分の長さが定義できない場合(プログラム的に動き続けるサブクラスなど)の場合は「-1」を返す\n /// \n /// モーションのループ1回分の長さ[秒]\n public virtual float GetLoopDuration() { return -1.0f; }\n\n /// \n /// イベント発火のチェック。\n /// 入力する時間は呼ばれるモーションタイミングを0とした秒数で行う。\n /// \n /// 前回のイベントチェック時間[秒]\n /// 今回の再生時間[秒]\n /// \n public virtual List GetFiredEvent(float beforeCheckTimeSeconds, float motionTimeSeconds) { return FiredEventValues; }\n\n /// \n /// 透明度のカーブが存在するかどうかを確認する\n /// \n /// \n /// true . キーが存在する\n /// false . キーが存在しない\n /// \n public virtual bool IsExistModelOpacity() { return false; }\n\n /// \n /// 透明度のカーブのインデックスを返す\n /// \n /// success:透明度のカーブのインデックス\n public virtual int GetModelOpacityIndex() { return -1; }\n\n /// \n /// 透明度のIdを返す\n /// \n /// 透明度のId\n public virtual string? GetModelOpacityId(int index) { return \"\"; }\n\n public virtual float GetModelOpacityValue() { return 1.0f; }\n\n public abstract void DoUpdateParameters(CubismModel model, float userTimeSeconds, float weight, CubismMotionQueueEntry motionQueueEntry);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserData.cs", "using System.Text.Json;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// ユーザデータをロード、管理、検索インターフェイス、解放までを行う。\n/// \npublic class CubismModelUserData\n{\n public const string ArtMesh = \"ArtMesh\";\n\n public const string Meta = \"Meta\";\n\n public const string UserDataCount = \"UserDataCount\";\n\n public const string TotalUserDataSize = \"TotalUserDataSize\";\n\n public const string UserData = \"UserData\";\n\n public const string Target = \"Target\";\n\n public const string Id = \"Id\";\n\n public const string Value = \"Value\";\n\n /// \n /// ユーザデータ構造体配列\n /// \n private readonly List _userDataNodes = [];\n\n /// \n /// 閲覧リスト保持\n /// \n public readonly List ArtMeshUserDataNodes = [];\n\n /// \n /// userdata3.jsonをパースする。\n /// \n /// userdata3.jsonが読み込まれいるバッファ\n public CubismModelUserData(string data)\n {\n using var stream = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismModelUserDataObjContext.Default.CubismModelUserDataObj)\n ?? throw new Exception(\"Load UserData error\");\n\n var typeOfArtMesh = CubismFramework.CubismIdManager.GetId(ArtMesh);\n\n var nodeCount = obj.Meta.UserDataCount;\n\n for ( var i = 0; i < nodeCount; i++ )\n {\n var node = obj.UserData[i];\n CubismModelUserDataNode addNode = new() { TargetId = CubismFramework.CubismIdManager.GetId(node.Id), TargetType = CubismFramework.CubismIdManager.GetId(node.Target), Value = CubismFramework.CubismIdManager.GetId(node.Value) };\n _userDataNodes.Add(addNode);\n\n if ( addNode.TargetType == typeOfArtMesh )\n {\n ArtMeshUserDataNodes.Add(addNode);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/TextRenderer.cs", "using System.Numerics;\n\nusing FontStashSharp.Interfaces;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\ninternal class TextRenderer : IFontStashRenderer2, IDisposable\n{\n private const int MAX_SPRITES = 2048;\n\n private const int MAX_VERTICES = MAX_SPRITES * 4;\n\n private const int MAX_INDICES = MAX_SPRITES * 6;\n\n private static readonly short[] indexData = GenerateIndexArray();\n\n private readonly GL _gl;\n\n private readonly BufferObject _indexBuffer;\n\n private readonly Shader _shader;\n\n private readonly Texture2DManager _textureManager;\n\n private readonly VertexArrayObject _vao;\n\n private readonly BufferObject _vertexBuffer;\n\n private readonly VertexPositionColorTexture[] _vertexData = new VertexPositionColorTexture[MAX_VERTICES];\n\n private object _lastTexture;\n\n private int _vertexIndex = 0;\n\n private int _viewportHeight = 800;\n\n private int _viewportWidth = 1200;\n\n public unsafe TextRenderer(GL glApi)\n {\n _gl = glApi;\n\n _textureManager = new Texture2DManager(_gl);\n\n _vertexBuffer = new BufferObject(_gl, MAX_VERTICES, BufferTargetARB.ArrayBuffer, true);\n _indexBuffer = new BufferObject(_gl, indexData.Length, BufferTargetARB.ElementArrayBuffer, false);\n _indexBuffer.SetData(indexData, 0, indexData.Length);\n\n var vertSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"t_shader.vert\"));\n var fragSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"t_shader.frag\"));\n _shader = new Shader(_gl, vertSrc, fragSrc);\n _shader.Use();\n\n _vao = new VertexArrayObject(_gl, sizeof(VertexPositionColorTexture));\n _vao.Bind();\n\n var location = _shader.GetAttribLocation(\"a_position\");\n _vao.VertexAttribPointer(location, 3, VertexAttribPointerType.Float, false, 0);\n\n location = _shader.GetAttribLocation(\"a_color\");\n _vao.VertexAttribPointer(location, 4, VertexAttribPointerType.UnsignedByte, true, 12);\n\n location = _shader.GetAttribLocation(\"a_texCoords0\");\n _vao.VertexAttribPointer(location, 2, VertexAttribPointerType.Float, false, 16);\n }\n\n public void Dispose() { Dispose(true); }\n\n public ITexture2DManager TextureManager => _textureManager;\n\n public void DrawQuad(object texture, ref VertexPositionColorTexture topLeft, ref VertexPositionColorTexture topRight, ref VertexPositionColorTexture bottomLeft, ref VertexPositionColorTexture bottomRight)\n {\n if ( _lastTexture != texture )\n {\n FlushBuffer();\n }\n\n _vertexData[_vertexIndex++] = topLeft;\n _vertexData[_vertexIndex++] = topRight;\n _vertexData[_vertexIndex++] = bottomLeft;\n _vertexData[_vertexIndex++] = bottomRight;\n\n _lastTexture = texture;\n }\n\n ~TextRenderer() { Dispose(false); }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( !disposing )\n {\n return;\n }\n\n _vao.Dispose();\n _vertexBuffer.Dispose();\n _indexBuffer.Dispose();\n _shader.Dispose();\n }\n\n public void Begin()\n {\n _gl.Disable(EnableCap.DepthTest);\n _gl.CheckError();\n _gl.Enable(EnableCap.Blend);\n _gl.CheckError();\n _gl.BlendFunc(BlendingFactor.One, BlendingFactor.OneMinusSrcAlpha);\n _gl.CheckError();\n\n _shader.Use();\n _shader.SetUniform(\"TextureSampler\", 0);\n\n var transform = Matrix4x4.CreateOrthographicOffCenter(0, _viewportWidth, _viewportHeight, 0, 0, -1);\n _shader.SetUniform(\"MatrixTransform\", transform);\n\n _vao.Bind();\n _indexBuffer.Bind();\n _vertexBuffer.Bind();\n }\n\n public void End() { FlushBuffer(); }\n\n private void FlushBuffer()\n {\n unsafe\n {\n if ( _vertexIndex == 0 || _lastTexture == null )\n {\n return;\n }\n\n _vertexBuffer.SetData(_vertexData, 0, _vertexIndex);\n\n var texture = (Texture)_lastTexture;\n texture.Bind();\n\n _gl.DrawElements(PrimitiveType.Triangles, (uint)(_vertexIndex * 6 / 4), DrawElementsType.UnsignedShort, null);\n _vertexIndex = 0;\n }\n }\n\n private static short[] GenerateIndexArray()\n {\n var result = new short[MAX_INDICES];\n for ( int i = 0,\n j = 0; i < MAX_INDICES; i += 6, j += 4 )\n {\n result[i] = (short)j;\n result[i + 1] = (short)(j + 1);\n result[i + 2] = (short)(j + 2);\n result[i + 3] = (short)(j + 3);\n result[i + 4] = (short)(j + 2);\n result[i + 5] = (short)(j + 1);\n }\n\n return result;\n }\n\n public void OnViewportChanged(int width, int height)\n {\n _viewportWidth = width;\n _viewportHeight = height;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppTextureManager.cs", "using System.Runtime.InteropServices;\n\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.PixelFormats;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 画像読み込み、管理を行うクラス。\n/// \npublic class LAppTextureManager(LAppDelegate lapp)\n{\n private readonly List _textures = [];\n\n /// \n /// 画像読み込み\n /// \n /// 読み込む画像ファイルパス名\n /// 画像情報。読み込み失敗時はNULLを返す\n public TextureInfo CreateTextureFromPngFile(string fileName)\n {\n //search loaded texture already.\n var item = _textures.FirstOrDefault(a => a.FileName == fileName);\n if ( item != null )\n {\n return item;\n }\n\n // Using SixLabors.ImageSharp to load the image\n using var image = Image.Load(fileName);\n var GL = lapp.GL;\n\n // OpenGL用のテクスチャを生成する\n var textureId = GL.GenTexture();\n GL.BindTexture(GL.GL_TEXTURE_2D, textureId);\n\n // Create a byte array to hold image data\n var pixelData = new byte[4 * image.Width * image.Height]; // 4 bytes per pixel (RGBA)\n\n // Access the pixel data\n image.ProcessPixelRows(accessor =>\n {\n // For each row\n for ( var y = 0; y < accessor.Height; y++ )\n {\n // Get the pixel row span\n var row = accessor.GetRowSpan(y);\n\n // For each pixel in the row\n for ( var x = 0; x < row.Length; x++ )\n {\n // Calculate the position in our byte array\n var arrayPos = (y * accessor.Width + x) * 4;\n\n // Copy RGBA components\n pixelData[arrayPos + 0] = row[x].R;\n pixelData[arrayPos + 1] = row[x].G;\n pixelData[arrayPos + 2] = row[x].B;\n pixelData[arrayPos + 3] = row[x].A;\n }\n }\n });\n\n // Pin the byte array in memory so we can pass a pointer to OpenGL\n var pinnedArray = GCHandle.Alloc(pixelData, GCHandleType.Pinned);\n try\n {\n // Get the address of the first byte in the array\n var pointer = pinnedArray.AddrOfPinnedObject();\n\n // Pass the pointer to OpenGL\n GL.TexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, image.Width, image.Height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pointer);\n GL.GenerateMipmap(GL.GL_TEXTURE_2D);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);\n }\n finally\n {\n // Free the pinned array\n pinnedArray.Free();\n }\n\n GL.BindTexture(GL.GL_TEXTURE_2D, 0);\n\n var info = new TextureInfo { FileName = fileName, Width = image.Width, Height = image.Height, ID = textureId };\n\n _textures.Add(info);\n\n return info;\n }\n\n /// \n /// 指定したテクスチャIDの画像を解放する\n /// \n /// 解放するテクスチャID\n public void ReleaseTexture(int textureId)\n {\n foreach ( var item in _textures )\n {\n if ( item.ID == textureId )\n {\n _textures.Remove(item);\n\n break;\n }\n }\n }\n\n /// \n /// テクスチャIDからテクスチャ情報を得る\n /// \n /// 取得したいテクスチャID\n /// テクスチャが存在していればTextureInfoが返る\n public TextureInfo? GetTextureInfoById(int textureId) { return _textures.FirstOrDefault(a => a.ID == textureId); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Token.cs", "using System.Runtime.CompilerServices;\nusing System.Text;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record Token\n{\n public string Text { get; set; } = string.Empty;\n\n public string Tag { get; set; } = string.Empty;\n\n public string Whitespace { get; set; } = string.Empty;\n\n public bool IsHead { get; set; } = true;\n\n public string? Alias { get; set; }\n\n public string? Phonemes { get; set; }\n\n public double? Stress { get; set; }\n\n public string? Currency { get; set; }\n\n public string NumFlags { get; set; } = string.Empty;\n\n public bool Prespace { get; set; }\n\n public int? Rating { get; set; }\n\n public double? StartTs { get; set; }\n\n public double? EndTs { get; set; }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static Token MergeTokens(List tokens, string? unk = null)\n {\n if ( tokens.Count == 0 )\n {\n throw new ArgumentException(\"Cannot merge empty token list\", nameof(tokens));\n }\n\n if ( tokens.Count == 1 )\n {\n return tokens[0];\n }\n\n var stressValues = new HashSet();\n var currencyValues = new HashSet();\n var ratingValues = new HashSet();\n string? phonemes;\n\n foreach ( var t in tokens )\n {\n if ( t.Stress.HasValue )\n {\n stressValues.Add(t.Stress);\n }\n\n if ( t.Currency != null )\n {\n currencyValues.Add(t.Currency);\n }\n\n ratingValues.Add(t.Rating);\n }\n\n if ( unk == null )\n {\n phonemes = null;\n }\n else\n {\n var sb = new StringBuilder();\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var t = tokens[i];\n if ( t.Prespace && sb.Length > 0 &&\n sb[sb.Length - 1] != ' ' &&\n !string.IsNullOrEmpty(t.Phonemes) )\n {\n sb.Append(' ');\n }\n\n sb.Append(t.Phonemes == null ? unk : t.Phonemes);\n }\n\n phonemes = sb.ToString();\n }\n\n // Get tag from token with highest \"weight\"\n var tag = tokens[0].Tag;\n var maxWeight = GetTagWeight(tokens[0]);\n\n for ( var i = 1; i < tokens.Count; i++ )\n {\n var weight = GetTagWeight(tokens[i]);\n if ( weight > maxWeight )\n {\n maxWeight = weight;\n tag = tokens[i].Tag;\n }\n }\n\n // Concatenate text and whitespace\n var textBuilder = new StringBuilder();\n for ( var i = 0; i < tokens.Count - 1; i++ )\n {\n textBuilder.Append(tokens[i].Text);\n textBuilder.Append(tokens[i].Whitespace);\n }\n\n textBuilder.Append(tokens[tokens.Count - 1].Text);\n\n // Build num flags\n var numFlagsBuilder = new StringBuilder();\n var flagsSet = new HashSet();\n\n foreach ( var t in tokens )\n {\n foreach ( var c in t.NumFlags )\n {\n flagsSet.Add(c);\n }\n }\n\n foreach ( var c in flagsSet.OrderBy(c => c) )\n {\n numFlagsBuilder.Append(c);\n }\n\n return new Token {\n Text = textBuilder.ToString(),\n Tag = tag,\n Whitespace = tokens[tokens.Count - 1].Whitespace,\n IsHead = tokens[0].IsHead,\n Alias = null,\n Phonemes = phonemes,\n Stress = stressValues.Count == 1 ? stressValues.First() : null,\n Currency = currencyValues.Any() ? currencyValues.OrderByDescending(c => c).First() : null,\n NumFlags = numFlagsBuilder.ToString(),\n Prespace = tokens[0].Prespace,\n Rating = ratingValues.Contains(null) ? null : ratingValues.Min(),\n StartTs = tokens[0].StartTs,\n EndTs = tokens[tokens.Count - 1].EndTs\n };\n }\n\n private static int GetTagWeight(Token token)\n {\n var weight = 0;\n foreach ( var c in token.Text )\n {\n weight += char.IsLower(c) ? 1 : 2;\n }\n\n return weight;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public bool IsTo()\n {\n return Text == \"to\" || Text == \"To\" ||\n (Text == \"TO\" && (Tag == \"TO\" || Tag == \"IN\"));\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public int StressWeight()\n {\n if ( string.IsNullOrEmpty(Phonemes) )\n {\n return 0;\n }\n\n var weight = 0;\n foreach ( var c in Phonemes )\n {\n if ( PhonemizerConstants.Diphthongs.Contains(c) )\n {\n weight += 2;\n }\n else\n {\n weight += 1;\n }\n }\n\n return weight;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanityDetector.cs", "using Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Profanity;\n\n/// \n/// A profanity detector that uses an ONNX model under the hood.\n/// It supports DI for logging, configurable filter threshold, and a benchmarking utility.\n/// \npublic class ProfanityDetector : IDisposable\n{\n private readonly ILogger _logger;\n\n private readonly ProfanityDetectorOnnx _onnxDetector;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logger injected via dependency injection.\n /// Optional path to the ONNX model file.\n /// Optional path to the vocabulary file for tokenization.\n public ProfanityDetector(ILogger logger)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _logger.LogInformation(\"Initializing ProfanityDetector\");\n _onnxDetector = new ProfanityDetectorOnnx();\n }\n\n /// \n /// Gets or sets the threshold for detecting any profanity.\n /// If the model's score is below this threshold, the sentence is considered clean.\n /// \n public float FilterThreshold { get; set; } = 0.5f;\n\n /// \n /// Gets or sets the threshold for moderate profanity.\n /// \n public float ModerateThreshold { get; set; } = 0.75f;\n\n /// \n /// Gets or sets the threshold for severe profanity.\n /// \n public float SevereThreshold { get; set; } = 0.9f;\n\n public void Dispose() { _onnxDetector.Dispose(); }\n\n /// \n /// Evaluates the given sentence and determines the severity of profanity.\n /// \n /// The sentence to evaluate.\n /// \n /// A enum value indicating the level of profanity:\n /// Clean, Mild, Moderate, or Severe.\n /// \n public ProfanitySeverity EvaluateProfanity(string sentence)\n {\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n _logger.LogWarning(\"Empty or whitespace sentence provided.\");\n\n return ProfanitySeverity.Clean;\n }\n\n var score = _onnxDetector.Run(sentence);\n _logger.LogDebug(\"Sentence: \\\"{sentence}\\\" scored {score}.\", sentence, score);\n\n if ( score < FilterThreshold )\n {\n return ProfanitySeverity.Clean;\n }\n\n if ( score < ModerateThreshold )\n {\n return ProfanitySeverity.Mild;\n }\n\n if ( score < SevereThreshold )\n {\n return ProfanitySeverity.Moderate;\n }\n\n return ProfanitySeverity.Severe;\n }\n\n /// \n /// Benchmarks the profanity filter using provided test data.\n /// Each test item consists of a sentence and the expected outcome (true if profane, false otherwise).\n /// For benchmarking purposes, any result other than is considered profane.\n /// Returns useful statistics to help calibrate the filter thresholds.\n /// \n /// A collection of test sentences with their expected results.\n /// A instance containing detailed metrics.\n public BenchmarkResult Benchmark(IEnumerable<(string Sentence, bool ExpectedIsProfane)> testData)\n {\n if ( testData == null )\n {\n throw new ArgumentNullException(nameof(testData));\n }\n\n int total = 0,\n truePositives = 0,\n falsePositives = 0,\n trueNegatives = 0,\n falseNegatives = 0;\n\n foreach ( var (sentence, expected) in testData )\n {\n total++;\n var severity = EvaluateProfanity(sentence);\n // For benchmarking, any severity other than Clean is considered profane.\n var actual = severity != ProfanitySeverity.Clean;\n\n if ( expected && actual )\n {\n truePositives++;\n }\n else if ( !expected && actual )\n {\n falsePositives++;\n }\n else if ( !expected && !actual )\n {\n trueNegatives++;\n }\n else if ( expected && !actual )\n {\n falseNegatives++;\n }\n\n _logger.LogDebug(\"Benchmarking sentence: \\\"{sentence}\\\" | Severity: {severity} | Expected: {expected} | Actual: {actual}\",\n sentence, severity, expected, actual);\n }\n\n var accuracy = total > 0 ? (double)(truePositives + trueNegatives) / total : 0;\n var precision = truePositives + falsePositives > 0 ? (double)truePositives / (truePositives + falsePositives) : 0;\n var recall = truePositives + falseNegatives > 0 ? (double)truePositives / (truePositives + falseNegatives) : 0;\n\n var result = new BenchmarkResult {\n Total = total,\n TruePositives = truePositives,\n FalsePositives = falsePositives,\n TrueNegatives = trueNegatives,\n FalseNegatives = falseNegatives,\n Accuracy = accuracy,\n Precision = precision,\n Recall = recall\n };\n\n _logger.LogInformation(\"Benchmark results: {result} [Thresholds: FilterThreshold={FilterThreshold}, ModerateThreshold={ModerateThreshold}, SevereThreshold={SevereThreshold}]\",\n result, FilterThreshold, ModerateThreshold, SevereThreshold);\n\n return result;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismOffscreenSurface_OpenGLES2.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\n/// \n/// オフスクリーン描画用構造体\n/// \npublic class CubismOffscreenSurface_OpenGLES2(OpenGLApi gl)\n{\n /// \n /// 引数によって設定されたカラーバッファか?\n /// \n private bool _isColorBufferInherited;\n\n /// \n /// 旧フレームバッファ\n /// \n private int _oldFBO;\n\n /// \n /// レンダリングターゲットとしてのアドレス\n /// \n public int RenderTexture { get; private set; }\n\n /// \n /// 描画の際使用するテクスチャとしてのアドレス\n /// \n public int ColorBuffer { get; private set; }\n\n /// \n /// Create時に指定された幅\n /// \n public int BufferWidth { get; private set; }\n\n /// \n /// Create時に指定された高さ\n /// \n public int BufferHeight { get; private set; }\n\n /// \n /// 指定の描画ターゲットに向けて描画開始\n /// \n /// 0以上の場合、EndDrawでこの値をglBindFramebufferする\n public void BeginDraw(int restoreFBO = -1)\n {\n if ( RenderTexture == 0 )\n {\n return;\n }\n\n // バックバッファのサーフェイスを記憶しておく\n if ( restoreFBO < 0 )\n {\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out _oldFBO);\n }\n else\n {\n _oldFBO = restoreFBO;\n }\n\n //マスク用RenderTextureをactiveにセット\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, RenderTexture);\n }\n\n /// \n /// 描画終了\n /// \n public void EndDraw()\n {\n if ( RenderTexture == 0 )\n {\n return;\n }\n\n // 描画対象を戻す\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, _oldFBO);\n }\n\n /// \n /// レンダリングターゲットのクリア\n /// 呼ぶ場合はBeginDrawの後で呼ぶこと\n /// \n /// 赤(0.0~1.0)\n /// 緑(0.0~1.0)\n /// 青(0.0~1.0)\n /// α(0.0~1.0)\n public void Clear(float r, float g, float b, float a)\n {\n // マスクをクリアする\n gl.ClearColor(r, g, b, a);\n gl.Clear(gl.GL_COLOR_BUFFER_BIT);\n }\n\n /// \n /// CubismOffscreenFrame作成\n /// \n /// 作成するバッファ幅\n /// 作成するバッファ高さ\n /// 0以外の場合、ピクセル格納領域としてcolorBufferを使用する\n public bool CreateOffscreenSurface(int displayBufferWidth, int displayBufferHeight, int colorBuffer = 0)\n {\n // 一旦削除\n DestroyOffscreenSurface();\n\n // 新しく生成する\n if ( colorBuffer == 0 )\n {\n ColorBuffer = gl.GenTexture();\n\n gl.BindTexture(gl.GL_TEXTURE_2D, ColorBuffer);\n gl.TexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, displayBufferWidth, displayBufferHeight, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, 0);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);\n gl.BindTexture(gl.GL_TEXTURE_2D, 0);\n\n _isColorBufferInherited = false;\n }\n else\n {\n // 指定されたものを使用\n ColorBuffer = colorBuffer;\n\n _isColorBufferInherited = true;\n }\n\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out var tmpFramebufferObject);\n\n var ret = gl.GenFramebuffer();\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, ret);\n gl.FramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, ColorBuffer, 0);\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, tmpFramebufferObject);\n\n RenderTexture = ret;\n\n BufferWidth = displayBufferWidth;\n BufferHeight = displayBufferHeight;\n\n // 成功\n return true;\n }\n\n /// \n /// CubismOffscreenFrameの削除\n /// \n public void DestroyOffscreenSurface()\n {\n if ( !_isColorBufferInherited && ColorBuffer != 0 )\n {\n gl.DeleteTexture(ColorBuffer);\n ColorBuffer = 0;\n }\n\n if ( RenderTexture != 0 )\n {\n gl.DeleteFramebuffer(RenderTexture);\n RenderTexture = 0;\n }\n }\n\n /// \n /// 現在有効かどうか\n /// \n public bool IsValid() { return RenderTexture != 0; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCUtils.cs", "using Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\ninternal static class RVCUtils\n{\n public static DenseTensor RepeatTensor(DenseTensor tensor, int times)\n {\n // Create output tensor with expanded dimensions\n var inputDims = tensor.Dimensions;\n var outputDims = inputDims.ToArray();\n outputDims[2] *= times;\n var result = new DenseTensor(outputDims);\n\n // Cache dimensions for faster access\n var dim0 = inputDims[0];\n var dim1 = inputDims[1];\n var dim2 = inputDims[2];\n var newDim2 = dim2 * times;\n\n // Compute strides for efficient indexing\n var inputStride1 = dim2;\n var inputStride0 = dim1 * inputStride1;\n\n var outputStride1 = newDim2;\n var outputStride0 = dim1 * outputStride1;\n\n // Use regular for-loop with thread partitioning instead of Parallel.For with lambda\n var totalBatches = dim0;\n var numThreads = Environment.ProcessorCount;\n var batchesPerThread = (totalBatches + numThreads - 1) / numThreads;\n\n Parallel.For(0, numThreads, threadIndex =>\n {\n // Calculate the range for this thread\n var startBatch = threadIndex * batchesPerThread;\n var endBatch = Math.Min(startBatch + batchesPerThread, totalBatches);\n\n // Process assigned batches without capturing Span\n for ( var i = startBatch; i < endBatch; i++ )\n {\n // Calculate base offsets for each dimension\n var inputBaseI = i * inputStride0;\n var outputBaseI = i * outputStride0;\n\n for ( var j = 0; j < dim1; j++ )\n {\n var inputBaseJ = inputBaseI + j * inputStride1;\n var outputBaseJ = outputBaseI + j * outputStride1;\n\n for ( var k = 0; k < dim2; k++ )\n {\n // Get input value using direct indexers\n var value = tensor.GetValue(inputBaseJ + k);\n var outputStartIdx = outputBaseJ + k * times;\n\n // Set output values in a loop\n for ( var t = 0; t < times; t++ )\n {\n result.SetValue(outputStartIdx + t, value);\n }\n }\n }\n }\n });\n\n return result;\n }\n\n public static DenseTensor Transpose(Tensor tensor, params int[] perm)\n {\n // Create output tensor with transposed dimensions\n var outputDims = new int[perm.Length];\n for ( var i = 0; i < perm.Length; i++ )\n {\n outputDims[i] = tensor.Dimensions[perm[i]];\n }\n\n var result = new DenseTensor(outputDims);\n\n // Optimize for the specific (0,2,1) permutation used in the codebase\n if ( tensor.Dimensions.Length == 3 && perm.Length == 3 &&\n perm[0] == 0 && perm[1] == 2 && perm[2] == 1 )\n {\n TransposeOptimized021(tensor, result);\n\n return result;\n }\n\n var rank = tensor.Dimensions.Length;\n\n // Precompute input strides for faster coordinate calculation\n var inputStrides = new int[rank];\n inputStrides[rank - 1] = 1;\n for ( var i = rank - 2; i >= 0; i-- )\n {\n inputStrides[i] = inputStrides[i + 1] * tensor.Dimensions[i + 1];\n }\n\n // Precompute output strides\n var outputStrides = new int[rank];\n outputStrides[rank - 1] = 1;\n for ( var i = rank - 2; i >= 0; i-- )\n {\n outputStrides[i] = outputStrides[i + 1] * outputDims[i + 1];\n }\n\n // Process in chunks for better parallelization\n const int chunkSize = 4096;\n var totalChunks = (tensor.Length + chunkSize - 1) / chunkSize;\n\n Parallel.For(0, totalChunks, chunkIdx =>\n {\n var startIdx = (int)chunkIdx * chunkSize;\n var endIdx = Math.Min(startIdx + chunkSize, tensor.Length);\n\n // Allocate coordinate array for this thread\n var coords = new int[rank];\n\n // Process this chunk\n for ( var flatIdx = startIdx; flatIdx < endIdx; flatIdx++ )\n {\n // Convert flat index to coordinates\n var remaining = flatIdx;\n for ( var dim = 0; dim < rank; dim++ )\n {\n coords[dim] = remaining / inputStrides[dim];\n remaining %= inputStrides[dim];\n }\n\n // Compute output index\n var outputIdx = 0;\n for ( var dim = 0; dim < rank; dim++ )\n {\n outputIdx += coords[perm[dim]] * outputStrides[dim];\n }\n\n // Transfer the value\n result.SetValue(outputIdx, tensor.GetValue(flatIdx));\n }\n });\n\n return result;\n }\n\n // Highly optimized method for the specific (0,2,1) permutation\n private static void TransposeOptimized021(Tensor input, DenseTensor output)\n {\n var dim0 = input.Dimensions[0];\n var dim1 = input.Dimensions[1];\n var dim2 = input.Dimensions[2];\n\n // Partitioning for parallel processing\n var numThreads = Environment.ProcessorCount;\n var batchesPerThread = (dim0 + numThreads - 1) / numThreads;\n\n Parallel.For(0, numThreads, threadIndex =>\n {\n var startBatch = threadIndex * batchesPerThread;\n var endBatch = Math.Min(startBatch + batchesPerThread, dim0);\n\n // Process batches assigned to this thread\n for ( var i = startBatch; i < endBatch; i++ )\n {\n // Compute base offsets for this batch\n var inputBatchOffset = i * dim1 * dim2;\n var outputBatchOffset = i * dim2 * dim1;\n\n // Cache-friendly block processing\n const int blockSize = 16; // Tuned for typical CPU cache line size\n\n // Process the 2D slice in blocks for better cache locality\n for ( var jBlock = 0; jBlock < dim1; jBlock += blockSize )\n {\n for ( var kBlock = 0; kBlock < dim2; kBlock += blockSize )\n {\n // Determine actual block boundaries\n var jEnd = Math.Min(jBlock + blockSize, dim1);\n var kEnd = Math.Min(kBlock + blockSize, dim2);\n\n // Process the block\n for ( var j = jBlock; j < jEnd; j++ )\n {\n var inputRowOffset = inputBatchOffset + j * dim2;\n\n for ( var k = kBlock; k < kEnd; k++ )\n {\n var inputIdx = inputRowOffset + k;\n var outputIdx = outputBatchOffset + k * dim1 + j;\n\n // Use element access methods instead of Span\n output.SetValue(outputIdx, input.GetValue(inputIdx));\n }\n }\n }\n }\n }\n });\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/WindowManager.cs", "using Silk.NET.Maths;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI;\n\n/// \n/// Wraps Silk.NET window creation, events, and OpenGL context initialization.\n/// \npublic class WindowManager\n{\n public WindowManager(Vector2D size, string title)\n {\n var options = WindowOptions.Default;\n options.Size = size;\n options.Title = title;\n options.UpdatesPerSecond = 60;\n options.FramesPerSecond = 30;\n options.WindowBorder = WindowBorder.Fixed;\n MainWindow = Window.Create(options);\n MainWindow.Load += OnLoad;\n MainWindow.Update += OnUpdate;\n MainWindow.Render += OnRender;\n MainWindow.Resize += OnResize;\n MainWindow.Closing += OnClose;\n }\n\n public IWindow MainWindow { get; }\n\n public GL GL { get; private set; }\n\n public event Action RenderFrame;\n\n public event Action Load;\n\n public event Action> Resize;\n\n public event Action Update;\n\n public event Action Close;\n\n private void OnLoad()\n {\n GL = GL.GetApi(MainWindow);\n Load?.Invoke();\n }\n\n private void OnUpdate(double delta) { Update?.Invoke(delta); }\n\n private void OnRender(double delta) { RenderFrame?.Invoke(delta); }\n\n private void OnResize(Vector2D size) { Resize?.Invoke(size); }\n\n private void OnClose() { Close?.Invoke(); }\n\n public void Run() { MainWindow.Run(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionObj.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\npublic record CubismMotionObj\n{\n public MetaObj Meta { get; set; }\n\n public List Curves { get; set; }\n\n public List UserData { get; set; }\n\n public record MetaObj\n {\n public float Duration { get; set; }\n\n public bool Loop { get; set; }\n\n public bool AreBeziersRestricted { get; set; }\n\n public int CurveCount { get; set; }\n\n public float Fps { get; set; }\n\n public int TotalSegmentCount { get; set; }\n\n public int TotalPointCount { get; set; }\n\n public float? FadeInTime { get; set; }\n\n public float? FadeOutTime { get; set; }\n\n public int UserDataCount { get; set; }\n\n public int TotalUserDataSize { get; set; }\n }\n\n public record Curve\n {\n public float? FadeInTime { get; set; }\n\n public float? FadeOutTime { get; set; }\n\n public List Segments { get; set; }\n\n public string Target { get; set; }\n\n public string Id { get; set; }\n }\n\n public record UserDataObj\n {\n public float Time { get; set; }\n\n public string Value { get; set; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/IConversationContext.cs", "using Microsoft.SemanticKernel.ChatCompletion;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic interface IConversationContext : IDisposable\n{\n IReadOnlyDictionary Participants { get; }\n\n IReadOnlyList History { get; }\n\n string? CurrentVisualContext { get; }\n\n InteractionTurn? PendingTurn { get; }\n\n bool TryAddParticipant(ParticipantInfo participant);\n\n bool TryRemoveParticipant(string participantId);\n\n void StartTurn(Guid turnId, IEnumerable participantIds);\n\n void AppendToTurn(string participantId, string chunk);\n\n string GetPendingMessageText(string participantId);\n\n void CompleteTurnPart(string participantId, bool interrupted = false);\n\n IReadOnlyList GetProjectedHistory();\n\n public void AbortTurn();\n\n ChatHistory GetSemanticKernelChatHistory(bool includePendingTurn = true);\n\n bool TryUpdateMessage(Guid turnId, Guid messageId, string newText);\n\n bool TryDeleteMessage(Guid turnId, Guid messageId);\n\n void ApplyCleanupStrategy();\n\n void ClearHistory();\n\n event EventHandler? ConversationUpdated;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.App/GuidToEmojiEnricher.cs", "using System.Collections.Concurrent;\n\nusing Serilog.Core;\nusing Serilog.Events;\n\nnamespace PersonaEngine.App;\n\npublic class GuidToEmojiEnricher : ILogEventEnricher\n{\n private readonly GuidEmojiMapper _mapper;\n\n public GuidToEmojiEnricher() { _mapper = new GuidEmojiMapper(); }\n\n public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)\n {\n var guidProperties = logEvent.Properties\n .Where(kvp => kvp.Value is ScalarValue { Value: Guid })\n .Select(kvp => new { kvp.Key, Value = (Guid)(((ScalarValue)kvp.Value).Value ?? Guid.Empty) })\n .ToList();\n\n foreach ( var propInfo in guidProperties )\n {\n var emoji = _mapper.GetEmojiForGuid(propInfo.Value);\n\n logEvent.RemovePropertyIfPresent(propInfo.Key);\n\n var emojiProperty = propertyFactory.CreateProperty(propInfo.Key, emoji);\n logEvent.AddOrUpdateProperty(emojiProperty);\n }\n }\n}\n\npublic class GuidEmojiMapper\n{\n private static readonly IReadOnlyList Emojis = new List {\n \"🚀\",\n \"🌟\",\n \"💡\",\n \"🔧\",\n \"🐞\",\n \"🔗\",\n \"💾\",\n \"🔑\",\n \"🎉\",\n \"🎯\",\n \"📁\",\n \"📄\",\n \"📦\",\n \"🧭\",\n \"📡\",\n \"🧪\",\n \"🧬\",\n \"⚙️\",\n \"💎\",\n \"🧩\",\n \"🐙\",\n \"🦄\",\n \"🐘\",\n \"🦋\",\n \"🐌\",\n \"🐬\",\n \"🐿️\",\n \"🍄\",\n \"🌵\",\n \"🍀\"\n }.AsReadOnly();\n\n private readonly ConcurrentDictionary _guidEmojiMap = new();\n\n private int _emojiIndex = -1;\n\n public string GetEmojiForGuid(Guid guid)\n {\n if ( guid == Guid.Empty )\n {\n return \"\\u2796\";\n }\n \n return _guidEmojiMap.GetOrAdd(guid, _ =>\n {\n var nextIndex = Interlocked.Increment(ref _emojiIndex);\n var emojiListIndex = (nextIndex & int.MaxValue) % Emojis.Count;\n\n return Emojis[emojiListIndex];\n });\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismRenderer.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// モデル描画を処理するレンダラ\n/// サブクラスに環境依存の描画命令を記述する\n/// \npublic abstract class CubismRenderer : IDisposable\n{\n /// \n /// Model-View-Projection 行列\n /// \n private readonly CubismMatrix44 _mvpMatrix4x4 = new();\n\n public CubismTextureColor ClearColor = new(0, 0, 0, 0);\n\n /// \n /// モデル自体のカラー(RGBA)\n /// \n public CubismTextureColor ModelColor = new();\n\n /// \n /// レンダラのインスタンスを生成して取得する\n /// \n public CubismRenderer(CubismModel model)\n {\n _mvpMatrix4x4.LoadIdentity();\n Model = model ?? throw new Exception(\"model is null\");\n }\n\n /// \n /// テクスチャの異方性フィルタリングのパラメータ\n /// \n public float Anisotropy { get; set; }\n\n /// \n /// レンダリング対象のモデル\n /// \n public CubismModel Model { get; private set; }\n\n /// \n /// 乗算済みαならtrue\n /// \n public bool IsPremultipliedAlpha { get; set; }\n\n /// \n /// カリングが有効ならtrue\n /// \n public bool IsCulling { get; set; }\n\n /// \n /// falseの場合、マスクを纏めて描画する trueの場合、マスクはパーツ描画ごとに書き直す\n /// \n public bool UseHighPrecisionMask { get; set; }\n\n /// \n /// レンダラのインスタンスを解放する\n /// \n public abstract void Dispose();\n\n /// \n /// モデルを描画する\n /// \n public void DrawModel()\n {\n /**\n * DoDrawModelの描画前と描画後に以下の関数を呼んでください。\n * ・SaveProfile();\n * ・RestoreProfile();\n * これはレンダラの描画設定を保存・復帰させることで、\n * モデル描画直前の状態に戻すための処理です。\n */\n\n SaveProfile();\n\n DoDrawModel();\n\n RestoreProfile();\n }\n\n /// \n /// Model-View-Projection 行列をセットする\n /// 配列は複製されるので元の配列は外で破棄して良い\n /// \n /// Model-View-Projection 行列\n public void SetMvpMatrix(CubismMatrix44 matrix4x4) { _mvpMatrix4x4.SetMatrix(matrix4x4.Tr); }\n\n /// \n /// Model-View-Projection 行列を取得する\n /// \n /// Model-View-Projection 行列\n public CubismMatrix44 GetMvpMatrix() { return _mvpMatrix4x4; }\n\n /// \n /// 透明度を考慮したモデルの色を計算する。\n /// \n /// 透明度\n /// RGBAのカラー情報\n public CubismTextureColor GetModelColorWithOpacity(float opacity)\n {\n CubismTextureColor modelColorRGBA = new(ModelColor);\n modelColorRGBA.A *= opacity;\n if ( IsPremultipliedAlpha )\n {\n modelColorRGBA.R *= modelColorRGBA.A;\n modelColorRGBA.G *= modelColorRGBA.A;\n modelColorRGBA.B *= modelColorRGBA.A;\n }\n\n return modelColorRGBA;\n }\n\n /// \n /// モデルの色をセットする。\n /// 各色0.0f~1.0fの間で指定する(1.0fが標準の状態)。\n /// \n /// 赤チャンネルの値\n /// 緑チャンネルの値\n /// 青チャンネルの値\n /// αチャンネルの値\n public void SetModelColor(float red, float green, float blue, float alpha)\n {\n if ( red < 0.0f )\n {\n red = 0.0f;\n }\n else if ( red > 1.0f )\n {\n red = 1.0f;\n }\n\n if ( green < 0.0f )\n {\n green = 0.0f;\n }\n else if ( green > 1.0f )\n {\n green = 1.0f;\n }\n\n if ( blue < 0.0f )\n {\n blue = 0.0f;\n }\n else if ( blue > 1.0f )\n {\n blue = 1.0f;\n }\n\n if ( alpha < 0.0f )\n {\n alpha = 0.0f;\n }\n else if ( alpha > 1.0f )\n {\n alpha = 1.0f;\n }\n\n ModelColor.R = red;\n ModelColor.G = green;\n ModelColor.B = blue;\n ModelColor.A = alpha;\n }\n\n /// \n /// モデル描画の実装\n /// \n protected abstract void DoDrawModel();\n\n /// \n /// 描画オブジェクト(アートメッシュ)を描画する。\n /// ポリゴンメッシュとテクスチャ番号をセットで渡す。\n /// \n /// 描画するテクスチャ番号\n /// 描画オブジェクトのインデックス値\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュ頂点のインデックス配列\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 不透明度\n /// カラーブレンディングのタイプ\n /// マスク使用時のマスクの反転使用\n internal abstract unsafe void DrawMesh(int textureNo, int indexCount, int vertexCount\n , ushort* indexArray, float* vertexArray, float* uvArray\n , float opacity, CubismBlendMode colorBlendMode, bool invertedMask);\n\n /// \n /// モデル描画直前のレンダラのステートを保持する\n /// \n protected abstract void SaveProfile();\n\n /// \n /// モデル描画直前のレンダラのステートを復帰させる\n /// \n protected abstract void RestoreProfile();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/FileModelProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// File-based model provider implementation\n/// \npublic class FileModelProvider : IModelProvider\n{\n private readonly string _baseDirectory;\n\n private readonly ILogger _logger;\n\n private readonly ConcurrentDictionary _modelCache = new();\n\n private bool _disposed;\n\n public FileModelProvider(string baseDirectory, ILogger logger)\n {\n _baseDirectory = baseDirectory ?? throw new ArgumentNullException(nameof(baseDirectory));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n if ( !Directory.Exists(_baseDirectory) )\n {\n throw new DirectoryNotFoundException($\"Model directory not found: {_baseDirectory}\");\n }\n }\n\n /// \n /// Gets a model by type\n /// \n public Task GetModelAsync(ModelType modelType, CancellationToken cancellationToken = default)\n {\n // Check if already cached\n if ( _modelCache.TryGetValue(modelType, out var cachedModel) )\n {\n return Task.FromResult(cachedModel);\n }\n\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Map model type to path\n var modelPath = GetModelPath(modelType);\n\n // Create new model resource\n var model = new ModelResource(modelPath);\n\n // Cache the model\n _modelCache[modelType] = model;\n\n _logger.LogInformation(\"Loaded model {ModelType} from {Path}\", modelType, modelPath);\n\n return Task.FromResult(model);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading model {ModelType}\", modelType);\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n // Dispose all cached models\n foreach ( var model in _modelCache.Values )\n {\n model.Dispose();\n }\n\n _modelCache.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Maps model type to file path\n /// \n private string GetModelPath(ModelType modelType)\n {\n var fullPath = Path.Combine(_baseDirectory, modelType.GetDescription());\n\n return fullPath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/IConversationSession.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic interface IConversationSession : IAsyncDisposable\n{\n IConversationContext Context { get; }\n\n Guid SessionId { get; }\n\n ValueTask RunAsync(CancellationToken cancellationToken);\n\n ValueTask StopAsync();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismMath.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 数値計算などに使用するユーティリティクラス\n/// \npublic static class CubismMath\n{\n public const float Pi = 3.1415926535897932384626433832795f;\n\n public const float Epsilon = 0.00001f;\n\n /// \n /// 第一引数の値を最小値と最大値の範囲に収めた値を返す\n /// \n /// 収められる値\n /// 範囲の最小値\n /// 範囲の最大値\n /// 最小値と最大値の範囲に収めた値\n public static float RangeF(float value, float min, float max)\n {\n if ( value < min )\n {\n value = min;\n }\n else if ( value > max )\n {\n value = max;\n }\n\n return value;\n }\n\n /// \n /// イージング処理されたサインを求める\n /// フェードイン・アウト時のイージングに利用できる\n /// \n /// イージングを行う値\n /// イージング処理されたサイン値\n public static float GetEasingSine(float value)\n {\n if ( value < 0.0f )\n {\n return 0.0f;\n }\n\n if ( value > 1.0f )\n {\n return 1.0f;\n }\n\n return 0.5f - 0.5f * MathF.Cos(value * Pi);\n }\n\n /// \n /// 大きい方の値を返す。\n /// \n /// 左辺の値\n /// 右辺の値\n /// 大きい方の値\n public static float Max(float l, float r) { return l > r ? l : r; }\n\n /// \n /// 小さい方の値を返す。\n /// \n /// 左辺の値\n /// 右辺の値\n /// 小さい方の値\n public static float Min(float l, float r) { return l > r ? r : l; }\n\n /// \n /// 角度値をラジアン値に変換します。\n /// \n /// 角度値\n /// 角度値から変換したラジアン値\n public static float DegreesToRadian(float degrees) { return degrees / 180.0f * Pi; }\n\n /// \n /// ラジアン値を角度値に変換します。\n /// \n /// ラジアン値\n /// ラジアン値から変換した角度値\n public static float RadianToDegrees(float radian) { return radian * 180.0f / Pi; }\n\n /// \n /// 2つのベクトルからラジアン値を求めます。\n /// \n /// 始点ベクトル\n /// 終点ベクトル\n /// ラジアン値から求めた方向ベクトル\n public static float DirectionToRadian(Vector2 from, Vector2 to)\n {\n float q1;\n float q2;\n float ret;\n\n q1 = MathF.Atan2(to.Y, to.X);\n q2 = MathF.Atan2(from.Y, from.X);\n\n ret = q1 - q2;\n\n while ( ret < -Pi )\n {\n ret += Pi * 2.0f;\n }\n\n while ( ret > Pi )\n {\n ret -= Pi * 2.0f;\n }\n\n return ret;\n }\n\n /// \n /// 2つのベクトルから角度値を求めます。\n /// \n /// 始点ベクトル\n /// 終点ベクトル\n /// 角度値から求めた方向ベクトル\n public static float DirectionToDegrees(Vector2 from, Vector2 to)\n {\n float radian;\n float degree;\n\n radian = DirectionToRadian(from, to);\n degree = RadianToDegrees(radian);\n\n if ( to.X - from.X > 0.0f )\n {\n degree = -degree;\n }\n\n return degree;\n }\n\n /// \n /// ラジアン値を方向ベクトルに変換します。\n /// \n /// ラジアン値\n /// ラジアン値から変換した方向ベクトル\n public static Vector2 RadianToDirection(float totalAngle) { return new Vector2(MathF.Sin(totalAngle), MathF.Cos(totalAngle)); }\n\n /// \n /// 三次方程式の三次項の係数が0になったときに補欠的に二次方程式の解をもとめる。\n /// a * x^2 + b * x + c = 0\n /// \n /// 二次項の係数値\n /// 一次項の係数値\n /// 定数項の値\n /// 二次方程式の解\n public static float QuadraticEquation(float a, float b, float c)\n {\n if ( MathF.Abs(a) < Epsilon )\n {\n if ( MathF.Abs(b) < Epsilon )\n {\n return -c;\n }\n\n return -c / b;\n }\n\n return -(b + MathF.Sqrt(b * b - 4.0f * a * c)) / (2.0f * a);\n }\n\n /// \n /// カルダノの公式によってベジェのt値に該当する3次方程式の解を求める。\n /// 重解になったときには0.0~1.0の値になる解を返す。\n /// a * x^3 + b * x^2 + c * x + d = 0\n /// \n /// 三次項の係数値\n /// 二次項の係数値\n /// 一次項の係数値\n /// 定数項の値\n /// 0.0~1.0の間にある解\n public static float CardanoAlgorithmForBezier(float a, float b, float c, float d)\n {\n if ( MathF.Abs(a) < Epsilon )\n {\n return RangeF(QuadraticEquation(b, c, d), 0.0f, 1.0f);\n }\n\n var ba = b / a;\n var ca = c / a;\n var da = d / a;\n\n var p = (3.0f * ca - ba * ba) / 3.0f;\n var p3 = p / 3.0f;\n var q = (2.0f * ba * ba * ba - 9.0f * ba * ca + 27.0f * da) / 27.0f;\n var q2 = q / 2.0f;\n var discriminant = q2 * q2 + p3 * p3 * p3;\n\n var center = 0.5f;\n var threshold = center + 0.01f;\n\n float root1;\n float u1;\n\n if ( discriminant < 0.0f )\n {\n var mp3 = -p / 3.0f;\n var mp33 = mp3 * mp3 * mp3;\n var r = MathF.Sqrt(mp33);\n var t = -q / (2.0f * r);\n var cosphi = RangeF(t, -1.0f, 1.0f);\n var phi = MathF.Acos(cosphi);\n var crtr = MathF.Cbrt(r);\n var t1 = 2.0f * crtr;\n\n root1 = t1 * MathF.Cos(phi / 3.0f) - ba / 3.0f;\n if ( MathF.Abs(root1 - center) < threshold )\n {\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n var root2 = t1 * MathF.Cos((phi + 2.0f * Pi) / 3.0f) - ba / 3.0f;\n if ( MathF.Abs(root2 - center) < threshold )\n {\n return RangeF(root2, 0.0f, 1.0f);\n }\n\n var root3 = t1 * MathF.Cos((phi + 4.0f * Pi) / 3.0f) - ba / 3.0f;\n\n return RangeF(root3, 0.0f, 1.0f);\n }\n\n if ( discriminant == 0.0f )\n {\n if ( q2 < 0.0f )\n {\n u1 = MathF.Cbrt(-q2);\n }\n else\n {\n u1 = -MathF.Cbrt(q2);\n }\n\n root1 = 2.0f * u1 - ba / 3.0f;\n if ( MathF.Abs(root1 - center) < threshold )\n {\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n var root2 = -u1 - ba / 3.0f;\n\n return RangeF(root2, 0.0f, 1.0f);\n }\n\n var sd = MathF.Sqrt(discriminant);\n u1 = MathF.Cbrt(sd - q2);\n var v1 = MathF.Cbrt(sd + q2);\n root1 = u1 - v1 - ba / 3.0f;\n\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n /// \n /// 値を範囲内に納めて返す\n /// \n /// 範囲内か確認する値\n /// 最小値\n /// 最大値\n /// 範囲内に収まった値\n public static int Clamp(int val, int min, int max)\n {\n if ( val < min )\n {\n return min;\n }\n\n if ( max < val )\n {\n return max;\n }\n\n return val;\n }\n\n /// \n /// 値を範囲内に納めて返す\n /// \n /// 範囲内か確認する値\n /// 最小値\n /// 最大値\n /// 範囲内に収まった値\n public static float ClampF(float val, float min, float max)\n {\n if ( val < min )\n {\n return min;\n }\n\n if ( max < val )\n {\n return max;\n }\n\n return val;\n }\n\n /// \n /// 浮動小数点の余りを求める。\n /// \n /// 被除数(割られる値)\n /// 除数(割る値)\n /// 余り\n public static float ModF(float dividend, float divisor)\n {\n if ( !float.IsFinite(dividend) || divisor == 0 || float.IsNaN(dividend) || float.IsNaN(divisor) )\n {\n CubismLog.Warning(\"dividend: %f, divisor: %f ModF() returns 'NaN'.\", dividend, divisor);\n\n return float.NaN;\n }\n\n // 絶対値に変換する。\n var absDividend = MathF.Abs(dividend);\n var absDivisor = MathF.Abs(divisor);\n\n // 絶対値で割り算する。\n var result = absDividend - MathF.Floor(absDividend / absDivisor) * absDivisor;\n\n // 符号を被除数のものに指定する。\n return MathF.CopySign(result, dividend);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/RealtimeSpeechTranscriptorOptions.cs", "using PersonaEngine.Lib.ASR.Transcriber;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic record RealtimeSpeechTranscriptorOptions : SpeechTranscriptorOptions\n{\n /// \n /// Gets or sets a value indicating whether to include speech recognizing events.\n /// \n /// \n /// This events are emitted before the segment is complete and are not final.\n /// \n public bool IncludeSpeechRecogizingEvents { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to autodetect the language only once at startup and use it for all the\n /// segments, instead of autodetecting it for each segment.\n /// \n public bool AutodetectLanguageOnce { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/LexiconEntry.cs", "using System.Text.Json.Serialization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Lexicon entry representing pronunciation for a word\n/// \npublic class LexiconEntry\n{\n /// \n /// Simple phoneme string (for entries with only one pronunciation)\n /// \n public string? Simple { get; set; }\n\n /// \n /// Phoneme strings by part-of-speech tag\n /// \n public Dictionary? ByTag { get; set; }\n\n /// \n /// Whether this is a simple entry\n /// \n [JsonIgnore]\n public bool IsSimple => ByTag == null;\n\n /// \n /// Gets phoneme string for a specific tag\n /// \n public string? GetForTag(string? tag)\n {\n if ( IsSimple )\n {\n return Simple;\n }\n\n if ( tag != null && ByTag != null && ByTag.TryGetValue(tag, out var value) )\n {\n return value;\n }\n\n if ( ByTag != null && ByTag.TryGetValue(\"DEFAULT\", out var def) )\n {\n return def;\n }\n\n return null;\n }\n\n /// \n /// Whether this entry has a specific tag\n /// \n public bool HasTag(string tag) { return ByTag != null && ByTag.ContainsKey(tag); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/NameTextFilter.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic class NameTextFilter : ITextFilter\n{\n public int Priority => 9999;\n\n public ValueTask ProcessAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text ?? string.Empty });\n }\n\n var span = text.AsSpan();\n\n if ( span.Length <= 2 || span[0] != '[' )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n var closingBracketIndex = span.IndexOf(']');\n\n if ( closingBracketIndex <= 1 )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n var remainingSpan = span[(closingBracketIndex + 1)..];\n\n remainingSpan = remainingSpan.TrimStart();\n\n var processedText = remainingSpan.ToString();\n\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = processedText });\n }\n\n public ValueTask PostProcessAsync(TextFilterResult textFilterResult, AudioSegment segment, CancellationToken cancellationToken = default) { return ValueTask.CompletedTask; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/ChannelAggregationStrategy.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// A strategy for aggregating multiple audio channels into a single channel.\n/// \npublic interface IChannelAggregationStrategy\n{\n /// \n /// Aggregates the specified frame of audio samples.\n /// \n void Aggregate(ReadOnlyMemory frame, Memory destination);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n}\n\n/// \n/// Provides predefined strategies for aggregating float audio channels.\n/// \npublic static class DefaultChannelAggregationStrategies\n{\n /// \n /// Gets the average aggregation strategy for float audio channels.\n /// \n public static IChannelAggregationStrategy Average { get; } = new AverageChannelAggregationStrategy();\n\n /// \n /// Gets the max aggregation strategy for float audio channels.\n /// \n public static IChannelAggregationStrategy Sum { get; } = new SumChannelAggregationStrategy();\n\n /// \n /// Gets the channel selection strategy for float audio channels.\n /// \n /// The index of the channel to use for aggregation.\n /// The channel selection strategy.\n public static IChannelAggregationStrategy SelectChannel(int channelIndex) { return new SelectChannelAggregationStrategy(channelIndex); }\n}\n\n/// \n/// Aggregates audio channels by computing the average of the samples.\n/// \ninternal class AverageChannelAggregationStrategy : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetAverageFloat(frame); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetAverageFloat(frame, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetAverageFloat(frame, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetAverageFloat(frame);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetAverageFloat(ReadOnlyMemory frame)\n {\n var span = frame.Span;\n var sum = 0.0f;\n for ( var i = 0; i < span.Length; i++ )\n {\n sum += span[i];\n }\n\n return sum / span.Length;\n }\n\n private static float GetAverageFloat(ReadOnlyMemory frame, ushort bitsPerSample)\n {\n var index = 0;\n var sum = 0f;\n var span = frame.Span;\n while ( index < frame.Length )\n {\n sum += SampleSerializer.ReadSample(span, ref index, bitsPerSample);\n }\n\n // We multiply by 8 first to avoid integer division\n return sum / (frame.Length * 8 / bitsPerSample);\n }\n}\n\n/// \n/// Aggregates float audio channels by selecting the maximum sample.\n/// \ninternal class SumChannelAggregationStrategy : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetSumFloat(frame); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetSumFloat(frame, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetSumFloat(frame, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetSumFloat(frame);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetSumFloat(ReadOnlyMemory frame)\n {\n var span = frame.Span;\n var sum = 0.0f;\n for ( var i = 0; i < span.Length; i++ )\n {\n sum += span[i];\n }\n\n // Ensure the float value is within the range (-1, 1)\n if ( sum > 1 )\n {\n sum = 1;\n }\n else if ( sum < -1 )\n {\n sum = -1;\n }\n\n return sum;\n }\n\n private static float GetSumFloat(ReadOnlyMemory frame, ushort bitsPerSample)\n {\n var index = 0;\n var sum = 0f;\n var span = frame.Span;\n while ( index < frame.Length )\n {\n sum += SampleSerializer.ReadSample(span, ref index, bitsPerSample);\n }\n\n // Ensure the float value is within the range (-1, 1)\n if ( sum > 1 )\n {\n sum = 1;\n }\n else if ( sum < -1 )\n {\n sum = -1;\n }\n\n return sum;\n }\n}\n\n/// \n/// Aggregates float audio channels by selecting a specific channel.\n/// \n/// The index of the channel to use for aggregation.\ninternal class SelectChannelAggregationStrategy(int channelIndex) : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetChannelFloat(frame, channelIndex); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetChannelFloat(frame, channelIndex, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetChannelFloat(frame, channelIndex, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetChannelFloat(frame, channelIndex);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetChannelFloat(ReadOnlyMemory frame, int channelIndex) { return frame.Span[channelIndex]; }\n\n private static float GetChannelFloat(ReadOnlyMemory frame, int channelIndex, ushort bitsPerSample)\n {\n var byteIndex = channelIndex * bitsPerSample / 8;\n\n return SampleSerializer.ReadSample(frame.Span, ref byteIndex, bitsPerSample);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/RealtimeOptions.cs", "namespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic class RealtimeOptions\n{\n /// \n /// Represents the length of the padding segmetents that will be appended to each sement detected by the VAD.\n /// \n /// \n /// If the VAD detects a segment of 1200ms starting at offset 200ms, and the is 125ms,\n /// 125ms of the original stream will be appended at the beginning and 125ms at the end of the segment.\n /// \n /// \n /// If the original stream is not long enough to append the padding segments, the padding won't be applied.\n /// \n public TimeSpan PaddingDuration { get; set; } = TimeSpan.FromMilliseconds(125);\n\n /// \n /// Represents the minimum length of a segment that will be processed by the transcriptor, if the segment is shorter\n /// than this value it will be ignored.\n /// \n public TimeSpan MinTranscriptDuration { get; set; } = TimeSpan.FromMilliseconds(200);\n\n /// \n /// Represents the minimum length of a segment and if it is shorter than this value it will be padded with silence.\n /// \n /// \n /// If the segment is 700ms, and the is 1100ms, the segment will be padded with\n /// 400ms of silence (200 ms at the beginning and 200ms at the end).\n /// \n public TimeSpan MinDurationWithPadding { get; set; } = TimeSpan.FromMilliseconds(1100);\n\n /// \n /// If set to true, the recognized segments will be concatenated to form the prompt for newer recognition.\n /// \n public bool ConcatenateSegmentsToPrompt { get; set; }\n\n /// \n /// Represents the interval at which the transcriptor will process the audio stream.\n /// \n public TimeSpan ProcessingInterval { get; set; } = TimeSpan.FromMilliseconds(100);\n\n /// \n /// Represents the interval at which the transcriptor will discard silence audio segments.\n /// \n public TimeSpan SilenceDiscardInterval { get; set; } = TimeSpan.FromSeconds(5);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroInferenceState.cs", "using Microsoft.ML.OnnxRuntime;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroInferenceState(OrtIoBinding binding)\n{\n /// Array for storing the context + input\n\n public float[] State { get; set; } = new float[SileroConstants.StateSize];\n\n // The state for the next inference\n public float[] PendingState { get; set; } = new float[SileroConstants.StateSize];\n\n public float[] Output { get; set; } = new float[SileroConstants.OutputSize];\n\n public OrtIoBinding Binding { get; } = binding;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Configuration/ConversationContextOptions.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\npublic record ConversationContextOptions\n{\n public string? SystemPromptFile { get; set; }\n\n public string? SystemPrompt { get; set; }\n\n public string? CurrentContext { get; set; }\n\n public List Topics { get; set; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/LexiconUtils.cs", "using System.Collections.Concurrent;\nusing System.Runtime.CompilerServices;\nusing System.Text;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class LexiconUtils\n{\n private static readonly ConcurrentDictionary _parentTagCache = new(StringComparer.Ordinal);\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static string? GetParentTag(string? tag)\n {\n if ( tag == null )\n {\n return null;\n }\n\n if ( _parentTagCache.TryGetValue(tag, out var cachedParent) )\n {\n return cachedParent;\n }\n\n string parent;\n if ( tag.StartsWith(\"VB\") )\n {\n parent = \"VERB\";\n }\n else if ( tag.StartsWith(\"NN\") )\n {\n parent = \"NOUN\";\n }\n else if ( tag.StartsWith(\"ADV\") || tag.StartsWith(\"RB\") )\n {\n parent = \"ADV\";\n }\n else if ( tag.StartsWith(\"ADJ\") || tag.StartsWith(\"JJ\") )\n {\n parent = \"ADJ\";\n }\n else\n {\n parent = tag;\n }\n\n _parentTagCache[tag] = parent;\n\n return parent;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static string Capitalize(ReadOnlySpan str)\n {\n if ( str.IsEmpty )\n {\n return string.Empty;\n }\n\n // Fast path for single-character strings\n if ( str.Length == 1 )\n {\n return char.ToUpper(str[0]).ToString();\n }\n\n // Avoid allocation if already capitalized\n if ( char.IsUpper(str[0]) )\n {\n return str.ToString();\n }\n\n var result = new StringBuilder(str.Length);\n result.Append(char.ToUpper(str[0]));\n result.Append(str.Slice(1));\n\n return result.ToString();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsObj.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\npublic record CubismPhysicsObj\n{\n public MetaObj Meta { get; set; }\n\n public List PhysicsSettings { get; set; }\n\n public record MetaObj\n {\n public EffectiveForce EffectiveForces { get; set; }\n\n public float Fps { get; set; }\n\n public int PhysicsSettingCount { get; set; }\n\n public int TotalInputCount { get; set; }\n\n public int TotalOutputCount { get; set; }\n\n public int VertexCount { get; set; }\n\n public record EffectiveForce\n {\n public Vector2 Gravity { get; set; }\n\n public Vector2 Wind { get; set; }\n }\n }\n\n public record PhysicsSetting\n {\n public NormalizationObj Normalization { get; set; }\n\n public List Input { get; set; }\n\n public List Output { get; set; }\n\n public List Vertices { get; set; }\n\n public record NormalizationObj\n {\n public PositionObj Position { get; set; }\n\n public PositionObj Angle { get; set; }\n\n public record PositionObj\n {\n public float Minimum { get; set; }\n\n public float Maximum { get; set; }\n\n public float Default { get; set; }\n }\n }\n\n public record InputObj\n {\n public float Weight { get; set; }\n\n public bool Reflect { get; set; }\n\n public string Type { get; set; }\n\n public SourceObj Source { get; set; }\n\n public record SourceObj\n {\n public string Id { get; set; }\n }\n }\n\n public record OutputObj\n {\n public int VertexIndex { get; set; }\n\n public float Scale { get; set; }\n\n public float Weight { get; set; }\n\n public DestinationObj Destination { get; set; }\n\n public string Type { get; set; }\n\n public bool Reflect { get; set; }\n\n public record DestinationObj\n {\n public string Id { get; set; }\n }\n }\n\n public record Vertice\n {\n public float Mobility { get; set; }\n\n public float Delay { get; set; }\n\n public float Acceleration { get; set; }\n\n public float Radius { get; set; }\n\n public Vector2 Position { get; set; }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/AvatarAppConfig.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\nnamespace PersonaEngine.Lib.Configuration;\n\npublic record AvatarAppConfig\n{\n public WindowConfiguration Window { get; set; } = new();\n\n public LlmOptions Llm { get; set; } = new();\n\n public TtsConfiguration Tts { get; set; } = new();\n\n public AsrConfiguration Asr { get; set; } = new();\n\n public MicrophoneConfiguration Microphone { get; set; } = new();\n\n public SubtitleOptions Subtitle { get; set; } = new();\n\n public Live2DOptions Live2D { get; set; } = new();\n\n public SpoutConfiguration[] SpoutConfigs { get; set; } = [];\n\n public VisionConfig Vision { get; set; } = new();\n\n public RouletteWheelOptions RouletteWheel { get; set; } = new();\n\n public ConversationOptions Conversation { get; set; } = new();\n \n // This would need to be seperate per configured conversation session\n public ConversationContextOptions ConversationContext { get; set; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Events/IInputEvent.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\npublic interface IInputEvent : IConversationEvent\n{\n string ParticipantId { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismViewMatrix.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// カメラの位置変更に使うと便利な4x4行列のクラス。\n/// \npublic record CubismViewMatrix : CubismMatrix44\n{\n /// \n /// デバイスに対応する論理座標上の範囲(左辺X軸位置)\n /// \n public float ScreenLeft { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(右辺X軸位置)\n /// \n public float ScreenRight { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(下辺Y軸位置)\n /// \n public float ScreenTop { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(上辺Y軸位置)\n /// \n public float ScreenBottom { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(左辺X軸位置)\n /// \n public float MaxLeft { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(右辺X軸位置)\n /// \n public float MaxRight { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(下辺Y軸位置)\n /// \n public float MaxTop { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(上辺Y軸位置)\n /// \n public float MaxBottom { get; private set; }\n\n /// \n /// 拡大率の最大値\n /// \n public float MaxScale { get; set; }\n\n /// \n /// 拡大率の最小値\n /// \n public float MinScale { get; set; }\n\n /// \n /// 移動を調整する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void AdjustTranslate(float x, float y)\n {\n if ( _tr[0] * MaxLeft + (_tr[12] + x) > ScreenLeft )\n {\n x = ScreenLeft - _tr[0] * MaxLeft - _tr[12];\n }\n\n if ( _tr[0] * MaxRight + (_tr[12] + x) < ScreenRight )\n {\n x = ScreenRight - _tr[0] * MaxRight - _tr[12];\n }\n\n if ( _tr[5] * MaxTop + (_tr[13] + y) < ScreenTop )\n {\n y = ScreenTop - _tr[5] * MaxTop - _tr[13];\n }\n\n if ( _tr[5] * MaxBottom + (_tr[13] + y) > ScreenBottom )\n {\n y = ScreenBottom - _tr[5] * MaxBottom - _tr[13];\n }\n\n float[] tr1 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n x, y, 0.0f, 1.0f\n ];\n\n MultiplyByMatrix(tr1);\n }\n\n /// \n /// 拡大率を調整する。\n /// \n /// 拡大を行うX軸の中心位置\n /// 拡大を行うY軸の中心位置\n /// 拡大率\n public void AdjustScale(float cx, float cy, float scale)\n {\n var maxScale = MaxScale;\n var minScale = MinScale;\n\n var targetScale = scale * _tr[0]; //\n\n if ( targetScale < minScale )\n {\n if ( _tr[0] > 0.0f )\n {\n scale = minScale / _tr[0];\n }\n }\n else if ( targetScale > maxScale )\n {\n if ( _tr[0] > 0.0f )\n {\n scale = maxScale / _tr[0];\n }\n }\n\n MultiplyByMatrix([\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n -cx, -cy, 0.0f, 1.0f\n ]);\n\n MultiplyByMatrix([\n scale, 0.0f, 0.0f, 0.0f,\n 0.0f, scale, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ]);\n\n MultiplyByMatrix([\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n cx, cy, 0.0f, 1.0f\n ]);\n }\n\n /// \n /// デバイスに対応する論理座標上の範囲の設定を行う。\n /// \n /// 左辺のX軸の位置\n /// 右辺のX軸の位置\n /// 下辺のY軸の位置\n /// 上辺のY軸の位置\n public void SetScreenRect(float left, float right, float bottom, float top)\n {\n ScreenLeft = left;\n ScreenRight = right;\n ScreenTop = top;\n ScreenBottom = bottom;\n }\n\n /// \n /// デバイスに対応する論理座標上の移動可能範囲の設定を行う。\n /// \n /// 左辺のX軸の位置\n /// 右辺のX軸の位置\n /// 下辺のY軸の位置\n /// 上辺のY軸の位置\n public void SetMaxScreenRect(float left, float right, float bottom, float top)\n {\n MaxLeft = left;\n MaxRight = right;\n MaxTop = top;\n MaxBottom = bottom;\n }\n\n /// \n /// 拡大率が最大になっているかどうかを確認する。\n /// \n /// \n /// true 拡大率は最大になっている\n /// false 拡大率は最大になっていない\n /// \n public bool IsMaxScale() { return GetScaleX() >= MaxScale; }\n\n /// \n /// 拡大率が最小になっているかどうかを確認する。\n /// \n /// \n /// true 拡大率は最小になっている\n /// false 拡大率は最小になっていない\n /// \n public bool IsMinScale() { return GetScaleX() <= MinScale; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/EnumExtensions.cs", "using System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Reflection;\n\nnamespace PersonaEngine.Lib.Utils;\n\npublic static class EnumExtensions\n{\n // Thread-safe cache for storing descriptions\n private static readonly ConcurrentDictionary<(Type Type, string Name), string> DescriptionCache = new();\n\n /// \n /// Gets the description of an enum value.\n /// If the enum value has a , returns its value.\n /// Otherwise, returns the string representation of the enum value.\n /// \n /// The enum value.\n /// The description or the string representation if no description is found.\n public static string GetDescription(this Enum value)\n {\n var type = value.GetType();\n var name = Enum.GetName(type, value);\n\n if ( name == null )\n {\n return value.ToString();\n }\n\n var cacheKey = (type, name);\n\n return DescriptionCache.GetOrAdd(cacheKey, key =>\n {\n var field = key.Type.GetField(key.Name);\n\n if ( field == null )\n {\n return key.Name;\n }\n\n var attribute = field.GetCustomAttribute(false);\n\n return attribute?.Description ?? key.Name;\n });\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/ConversationTrigger.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic enum ConversationTrigger\n{\n InitializeRequested,\n \n InitializeComplete,\n \n StopRequested,\n \n PauseRequested,\n \n ResumeRequested,\n \n InputDetected,\n \n InputFinalized,\n \n LlmRequestSent,\n \n LlmStreamStarted,\n \n LlmStreamChunkReceived,\n \n LlmStreamEnded,\n \n TtsRequestSent,\n \n TtsStreamStarted,\n \n TtsStreamChunkReceived,\n\n TtsStreamEnded,\n \n AudioStreamStarted,\n \n AudioStreamEnded,\n \n ErrorOccurred,\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemizerConstants.cs", "using System.Collections.Frozen;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class PhonemizerConstants\n{\n public static readonly HashSet Diphthongs = new(\"AIOQWYʤʧ\");\n\n public static readonly HashSet Vowels = new(\"AIOQWYaiuæɑɒɔəɛɜɪʊʌᵻ\");\n\n public static readonly HashSet Consonants = new(\"bdfhjklmnpstvwzðŋɡɹɾʃʒʤʧθ\");\n\n public static readonly char PrimaryStress = 'ˈ';\n\n public static readonly char SecondaryStress = 'ˌ';\n\n public static readonly char[] Stresses = ['ˌ', 'ˈ'];\n\n public static readonly HashSet UsTaus = new(\"AIOWYiuæɑəɛɪɹʊʌ\");\n\n public static readonly HashSet UsVocab = new(\"AIOWYbdfhijklmnpstuvwzæðŋɑɔəɛɜɡɪɹɾʃʊʌʒʤʧˈˌθᵊᵻ\");\n\n public static readonly HashSet GbVocab = new(\"AIQWYabdfhijklmnpstuvwzðŋɑɒɔəɛɜɡɪɹʃʊʌʒʤʧˈˌːθᵊ\");\n\n public static readonly IReadOnlyDictionary Currencies = new Dictionary { [\"$\"] = (\"dollar\", \"cent\"), [\"£\"] = (\"pound\", \"pence\"), [\"€\"] = (\"euro\", \"cent\") }.ToFrozenDictionary();\n\n public static readonly Dictionary AddSymbols = new() { [\".\"] = \"dot\", [\"/\"] = \"slash\" };\n\n public static readonly Dictionary Symbols = new() { [\"%\"] = \"percent\", [\"&\"] = \"and\", [\"+\"] = \"plus\", [\"@\"] = \"at\" };\n\n public static readonly HashSet Ordinals = [\"st\", \"nd\", \"rd\", \"th\"];\n\n public static readonly HashSet PunctTags = [\n \".\",\n \",\",\n \"-LRB-\",\n \"-RRB-\",\n \"``\",\n \"\\\"\\\"\",\n \"''\",\n \":\",\n \"$\",\n \"#\",\n \"NFP\"\n ];\n\n public static readonly Dictionary PunctTagPhonemes = new() {\n [\"-LRB-\"] = \"(\",\n [\"-RRB-\"] = \")\",\n [\"``\"] = \"\\u2014\", // em dash\n [\"\\\"\\\"\"] = \"\\u201D\", // right double quote\n [\"''\"] = \"\\u201D\" // right double quote\n };\n\n public static readonly HashSet SubtokenJunks = new(\"',-._''/\");\n\n public static readonly HashSet Puncts = new(\";:,.!?—…\\\"\\\"\\\"\");\n\n public static readonly HashSet NonQuotePuncts = [];\n\n static PhonemizerConstants()\n {\n // Initialize NonQuotePuncts\n foreach ( var c in Puncts )\n {\n if ( c != '\"' && c != '\"' && c != '\"' )\n {\n NonQuotePuncts.Add(c);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Events/IConversationEvent.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\npublic interface IConversationEvent\n{\n Guid SessionId { get; }\n\n Guid? TurnId { get; }\n\n DateTimeOffset Timestamp { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/IConversationOrchestrator.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic interface IConversationOrchestrator : IAsyncDisposable\n{\n IConversationSession GetSession(Guid sessionId);\n \n Task StartNewSessionAsync(CancellationToken cancellationToken = default);\n\n ValueTask StopSessionAsync(Guid sessionId);\n\n IEnumerable GetActiveSessionIds();\n\n ValueTask StopAllSessionsAsync();\n \n event EventHandler? SessionsUpdated;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Events/IOutputEvent.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\npublic interface IOutputEvent : IConversationEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismTargetPoint.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 顔の向きの制御機能を提供するクラス。\n/// \npublic class CubismTargetPoint\n{\n public const int FrameRate = 30;\n\n public const float Epsilon = 0.01f;\n\n /// \n /// 顔の向きのX目標値(この値に近づいていく)\n /// \n private float _faceTargetX;\n\n /// \n /// 顔の向きのY目標値(この値に近づいていく)\n /// \n private float _faceTargetY;\n\n /// \n /// 顔の向きの変化速度X\n /// \n private float _faceVX;\n\n /// \n /// 顔の向きの変化速度Y\n /// \n private float _faceVY;\n\n /// \n /// 最後の実行時間[秒]\n /// \n private float _lastTimeSeconds;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n private float _userTimeSeconds;\n\n /// \n /// 顔の向きX(-1.0 - 1.0)\n /// \n public float FaceX { get; private set; }\n\n /// \n /// 顔の向きY(-1.0 - 1.0)\n /// \n public float FaceY { get; private set; }\n\n /// \n /// 更新処理を行う。\n /// \n /// デルタ時間[秒]\n public void Update(float deltaTimeSeconds)\n {\n // デルタ時間を加算する\n _userTimeSeconds += deltaTimeSeconds;\n\n // 首を中央から左右に振るときの平均的な早さは 秒程度。加速・減速を考慮して、その2倍を最高速度とする\n // 顔のふり具合を、中央(0.0)から、左右は(+-1.0)とする\n var FaceParamMaxV = 40.0f / 10.0f; // 7.5秒間に40分移動(5.3/sc)\n var MaxV = FaceParamMaxV * 1.0f / FrameRate; // 1frameあたりに変化できる速度の上限\n\n if ( _lastTimeSeconds == 0.0f )\n {\n _lastTimeSeconds = _userTimeSeconds;\n\n return;\n }\n\n var deltaTimeWeight = (_userTimeSeconds - _lastTimeSeconds) * FrameRate;\n _lastTimeSeconds = _userTimeSeconds;\n\n // 最高速度になるまでの時間を\n var TimeToMaxSpeed = 0.15f;\n var FrameToMaxSpeed = TimeToMaxSpeed * FrameRate; // sec * frame/sec\n var MaxA = deltaTimeWeight * MaxV / FrameToMaxSpeed; // 1frameあたりの加速度\n\n // 目指す向きは、(dx, dy)方向のベクトルとなる\n var dx = _faceTargetX - FaceX;\n var dy = _faceTargetY - FaceY;\n\n if ( MathF.Abs(dx) <= Epsilon && MathF.Abs(dy) <= Epsilon )\n {\n return; // 変化なし\n }\n\n // 速度の最大よりも大きい場合は、速度を落とす\n var d = MathF.Sqrt(dx * dx + dy * dy);\n\n // 進行方向の最大速度ベクトル\n var vx = MaxV * dx / d;\n var vy = MaxV * dy / d;\n\n // 現在の速度から、新規速度への変化(加速度)を求める\n var ax = vx - _faceVX;\n var ay = vy - _faceVY;\n\n var a = MathF.Sqrt(ax * ax + ay * ay);\n\n // 加速のとき\n if ( a < -MaxA || a > MaxA )\n {\n ax *= MaxA / a;\n ay *= MaxA / a;\n }\n\n // 加速度を元の速度に足して、新速度とする\n _faceVX += ax;\n _faceVY += ay;\n\n // 目的の方向に近づいたとき、滑らかに減速するための処理\n // 設定された加速度で止まることのできる距離と速度の関係から\n // 現在とりうる最高速度を計算し、それ以上のときは速度を落とす\n // ※本来、人間は筋力で力(加速度)を調整できるため、より自由度が高いが、簡単な処理ですませている\n {\n // 加速度、速度、距離の関係式。\n // 2 6 2 3\n // sqrt(a t + 16 a h t - 8 a h) - a t\n // v = --------------------------------------\n // 2\n // 4 t - 2\n // (t=1)\n // 時刻tは、あらかじめ加速度、速度を1/60(フレームレート、単位なし)で\n // 考えているので、t=1として消してよい(※未検証)\n\n var maxV = 0.5f * (MathF.Sqrt(MaxA * MaxA + 16.0f * MaxA * d - 8.0f * MaxA * d) - MaxA);\n var curV = MathF.Sqrt(_faceVX * _faceVX + _faceVY * _faceVY);\n\n if ( curV > maxV )\n {\n // 現在の速度 > 最高速度のとき、最高速度まで減速\n _faceVX *= maxV / curV;\n _faceVY *= maxV / curV;\n }\n }\n\n FaceX += _faceVX;\n FaceY += _faceVY;\n }\n\n /// \n /// 顔の向きの目標値を設定する。\n /// \n /// X軸の顔の向きの値(-1.0 - 1.0)\n /// Y軸の顔の向きの値(-1.0 - 1.0)\n public void Set(float x, float y)\n {\n _faceTargetX = x;\n _faceTargetY = y;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismFramework.cs", "using PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Id;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// Live2D Cubism Original Workflow SDKのエントリポイント\n/// 利用開始時はCubismFramework.Initialize()を呼び、CubismFramework.Dispose()で終了する。\n/// \npublic static class CubismFramework\n{\n /// \n /// メッシュ頂点のオフセット値\n /// \n public const int VertexOffset = 0;\n\n /// \n /// メッシュ頂点のステップ値\n /// \n public const int VertexStep = 2;\n\n private static ICubismAllocator? s_allocator;\n\n private static Option? s_option;\n\n /// \n /// IDマネージャのインスタンスを取得する。\n /// \n public static CubismIdManager CubismIdManager { get; private set; } = new();\n\n public static bool IsInitialized { get; private set; }\n\n public static bool IsStarted { get; private set; }\n\n /// \n /// Cubism FrameworkのAPIを使用可能にする。\n /// APIを実行する前に必ずこの関数を実行すること。\n /// 引数に必ずメモリアロケータを渡してください。\n /// 一度準備が完了して以降は、再び実行しても内部処理がスキップされます。\n /// \n /// ICubismAllocatorクラスのインスタンス\n /// Optionクラスのインスタンス\n /// 準備処理が完了したらtrueが返ります。\n public static bool StartUp(ICubismAllocator allocator, Option option)\n {\n if ( IsStarted )\n {\n CubismLog.Info(\"[Live2D SDK]CubismFramework.StartUp() is already done.\");\n\n return IsStarted;\n }\n\n s_option = option;\n if ( s_option != null )\n {\n CubismCore.SetLogFunction(s_option.LogFunction);\n }\n\n if ( allocator == null )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.StartUp() failed, need allocator instance.\");\n IsStarted = false;\n }\n else\n {\n s_allocator = allocator;\n IsStarted = true;\n }\n\n //Live2D Cubism Coreバージョン情報を表示\n if ( IsStarted )\n {\n var version = CubismCore.GetVersion();\n\n var major = (version & 0xFF000000) >> 24;\n var minor = (version & 0x00FF0000) >> 16;\n var patch = version & 0x0000FFFF;\n var versionNumber = version;\n\n CubismLog.Info($\"[Live2D SDK]Cubism Core version: {major:#0}.{minor:0}.{patch:0000} ({versionNumber})\");\n }\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.StartUp() is complete.\");\n\n return IsStarted;\n }\n\n /// \n /// StartUp()で初期化したCubismFrameworkの各パラメータをクリアします。\n /// Dispose()したCubismFrameworkを再利用する際に利用してください。\n /// \n public static void CleanUp()\n {\n IsStarted = false;\n IsInitialized = false;\n }\n\n /// \n /// Cubism Framework内のリソースを初期化してモデルを表示可能な状態にします。\n /// 再度Initialize()するには先にDispose()を実行する必要があります。\n /// \n public static void Initialize()\n {\n if ( !IsStarted )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework is not started.\");\n\n return;\n }\n\n // --- s_isInitializedによる連続初期化ガード ---\n // 連続してリソース確保が行われないようにする。\n // 再度Initialize()するには先にDispose()を実行する必要がある。\n if ( IsInitialized )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.Initialize() skipped, already initialized.\");\n\n return;\n }\n\n IsInitialized = true;\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.Initialize() is complete.\");\n }\n\n /// \n /// Cubism Framework内の全てのリソースを解放します。\n /// ただし、外部で確保されたリソースについては解放しません。\n /// 外部で適切に破棄する必要があります。\n /// \n public static void Dispose()\n {\n if ( !IsStarted )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework is not started.\");\n\n return;\n }\n\n // --- s_isInitializedによる未初期化解放ガード ---\n // Dispose()するには先にInitialize()を実行する必要がある。\n if ( !IsInitialized ) // false...リソース未確保の場合\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.Dispose() skipped, not initialized.\");\n\n return;\n }\n\n IsInitialized = false;\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.Dispose() is complete.\");\n }\n\n /// \n /// Core APIにバインドしたログ関数を実行する\n /// \n /// ログメッセージ\n public static void CoreLogFunction(string data) { CubismCore.GetLogFunction()?.Invoke(data); }\n\n /// \n /// 現在のログ出力レベル設定の値を返す。\n /// \n /// 現在のログ出力レベル設定の値\n public static LogLevel GetLoggingLevel()\n {\n if ( s_option != null )\n {\n return s_option.LoggingLevel;\n }\n\n return LogLevel.Off;\n }\n\n public static IntPtr Allocate(int size) { return s_allocator!.Allocate(size); }\n\n public static IntPtr AllocateAligned(int size, int alignment) { return s_allocator!.AllocateAligned(size, alignment); }\n\n public static void Deallocate(IntPtr address) { s_allocator!.Deallocate(address); }\n\n public static void DeallocateAligned(IntPtr address) { s_allocator!.DeallocateAligned(address); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/TranscriptSegment.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic class TranscriptSegment\n{\n public IReadOnlyDictionary Metadata { get; init; }\n\n /// \n /// Gets or sets the text of the segment.\n /// \n public string Text { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the start time of the segment.\n /// \n public TimeSpan StartTime { get; set; }\n\n /// \n /// Gets or sets the duration of the segment\n /// \n public TimeSpan Duration { get; set; }\n\n /// \n /// Gets or sets the confidence of the segment\n /// \n public float? ConfidenceLevel { get; set; }\n\n /// \n /// Gets or sets the language of the segment.\n /// \n public CultureInfo? Language { get; set; }\n\n /// \n /// Gets or sets the tokens of the segment.\n /// \n /// \n /// Not all the transcriptors will provide tokens.\n /// \n public IList? Tokens { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/ACFMethod.cs", "namespace PersonaEngine.Lib.TTS.RVC;\n\npublic class ACFMethod : IF0Predictor\n{\n private readonly int SampleRate;\n\n private int HopLength;\n\n public ACFMethod(int hopLength, int samplingRate)\n {\n HopLength = hopLength;\n SampleRate = samplingRate;\n }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n HopLength = (int)Math.Floor(wav.Length / (double)length);\n\n var wavSpan = wav.Span;\n var f0Span = f0Output.Span;\n var frameLength = HopLength;\n\n for ( var i = 0; i < length; i++ )\n {\n // Create a window for this frame without allocations\n var startIdx = i * frameLength;\n var endIdx = Math.Min(startIdx + (int)(frameLength * 1.5), wav.Length);\n var frameSize = endIdx - startIdx;\n\n f0Span[i] = ComputeF0ForFrame(wavSpan.Slice(startIdx, frameSize));\n }\n }\n\n public void Dispose() { }\n\n private float ComputeF0ForFrame(ReadOnlySpan frame)\n {\n var n = frame.Length;\n Span autocorrelation = stackalloc float[n]; // Use stack allocation to avoid heap allocations\n\n // Calculate autocorrelation function\n for ( var lag = 0; lag < n; lag++ )\n {\n float sum = 0;\n for ( var i = 0; i < n - lag; i++ )\n {\n sum += frame[i] * frame[i + lag];\n }\n\n autocorrelation[lag] = sum;\n }\n\n // Ignore zero-delay peak, find first non-zero delay peak\n var peakIndex = 1;\n var maxVal = autocorrelation[1];\n for ( ; peakIndex < autocorrelation.Length && (maxVal = autocorrelation[peakIndex]) > 0; peakIndex++ )\n {\n ;\n }\n\n for ( var lag = peakIndex; lag < n; lag++ )\n {\n if ( autocorrelation[lag] > maxVal )\n {\n maxVal = autocorrelation[lag];\n peakIndex = lag;\n }\n }\n\n // Calculate fundamental frequency\n var f0 = SampleRate / (float)peakIndex;\n\n return f0;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismModelMatrix.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// モデル座標設定用の4x4行列クラス。\n/// \npublic record CubismModelMatrix : CubismMatrix44\n{\n public const string KeyWidth = \"width\";\n\n public const string KeyHeight = \"height\";\n\n public const string KeyX = \"x\";\n\n public const string KeyY = \"y\";\n\n public const string KeyCenterX = \"center_x\";\n\n public const string KeyCenterY = \"center_y\";\n\n public const string KeyTop = \"top\";\n\n public const string KeyBottom = \"bottom\";\n\n public const string KeyLeft = \"left\";\n\n public const string KeyRight = \"right\";\n\n /// \n /// 縦幅\n /// \n private readonly float _height;\n\n /// \n /// 横幅\n /// \n private readonly float _width;\n\n public CubismModelMatrix(float w, float h)\n {\n _width = w;\n _height = h;\n\n SetHeight(2.0f);\n }\n\n /// \n /// 横幅を設定する。\n /// \n /// 横幅\n public void SetWidth(float w)\n {\n var scaleX = w / _width;\n var scaleY = scaleX;\n Scale(scaleX, scaleY);\n }\n\n /// \n /// 縦幅を設定する。\n /// \n /// 縦幅\n public void SetHeight(float h)\n {\n var scaleX = h / _height;\n var scaleY = scaleX;\n Scale(scaleX, scaleY);\n }\n\n /// \n /// 位置を設定する。\n /// \n /// X軸の位置\n /// Y軸の位置\n public void SetPosition(float x, float y) { Translate(x, y); }\n\n /// \n /// 中心位置を設定する。\n /// \n /// X軸の中心位置\n /// Y軸の中心位置\n public void SetCenterPosition(float x, float y)\n {\n CenterX(x);\n CenterY(y);\n }\n\n /// \n /// 上辺の位置を設定する。\n /// \n /// 上辺のY軸位置\n public void Top(float y) { SetY(y); }\n\n /// \n /// 下辺の位置を設定する。\n /// \n /// 下辺のY軸位置\n public void Bottom(float y)\n {\n var h = _height * GetScaleY();\n TranslateY(y - h);\n }\n\n /// \n /// 左辺の位置を設定する。\n /// \n /// 左辺のX軸位置\n public void Left(float x) { SetX(x); }\n\n /// \n /// 右辺の位置を設定する。\n /// \n /// 右辺のX軸位置\n public void Right(float x)\n {\n var w = _width * GetScaleX();\n TranslateX(x - w);\n }\n\n /// \n /// X軸の中心位置を設定する。\n /// \n /// X軸の中心位置\n public void CenterX(float x)\n {\n var w = _width * GetScaleX();\n TranslateX(x - w / 2.0f);\n }\n\n /// \n /// X軸の位置を設定する。\n /// \n /// X軸の位置\n public void SetX(float x) { TranslateX(x); }\n\n /// \n /// Y軸の中心位置を設定する。\n /// \n /// Y軸の中心位置\n public void CenterY(float y)\n {\n var h = _height * GetScaleY();\n TranslateY(y - h / 2.0f);\n }\n\n /// \n /// Y軸の位置を設定する。\n /// \n /// Y軸の位置\n public void SetY(float y) { TranslateY(y); }\n\n /// \n /// レイアウト情報から位置を設定する。\n /// \n /// レイアウト情報\n public void SetupFromLayout(Dictionary layout)\n {\n foreach ( var item in layout )\n {\n if ( item.Key == KeyWidth )\n {\n SetWidth(item.Value);\n }\n else if ( item.Key == KeyHeight )\n {\n SetHeight(item.Value);\n }\n }\n\n foreach ( var item in layout )\n {\n if ( item.Key == KeyX )\n {\n SetX(item.Value);\n }\n else if ( item.Key == KeyY )\n {\n SetY(item.Value);\n }\n else if ( item.Key == KeyCenterX )\n {\n CenterX(item.Value);\n }\n else if ( item.Key == KeyCenterY )\n {\n CenterY(item.Value);\n }\n else if ( item.Key == KeyTop )\n {\n Top(item.Value);\n }\n else if ( item.Key == KeyBottom )\n {\n Bottom(item.Value);\n }\n else if ( item.Key == KeyLeft )\n {\n Left(item.Value);\n }\n else if ( item.Key == KeyRight )\n {\n Right(item.Value);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/GLUtility.cs", "using System.Diagnostics.Contracts;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\ninternal static class GlUtility\n{\n [Pure]\n public static float Clamp(float value, float min, float max)\n {\n return value < min\n ? min\n : value > max\n ? max\n : value;\n }\n\n public static void CheckError(this GL gl, string? title = null)\n {\n var error = gl.GetError();\n if ( error == GLEnum.NoError )\n {\n return;\n }\n\n if ( title != null )\n {\n throw new Exception($\"{title}: {error}\");\n }\n\n throw new Exception($\"GL.GetError(): {error}\");\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/ChatMessage.cs", "using OpenAI.Chat;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic class ChatMessage(Guid messageId, string participantId, string participantName, string text, DateTimeOffset timestamp, bool isPartial, ChatMessageRole role)\n{\n public Guid MessageId { get; } = messageId;\n\n public string ParticipantId { get; } = participantId;\n\n public string ParticipantName { get; } = participantName;\n\n public string Text { get; internal set; } = text;\n\n public DateTimeOffset Timestamp { get; } = timestamp;\n\n public bool IsPartial { get; internal set; } = isPartial;\n\n public ChatMessageRole Role { get; } = role;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/AsyncQueue.cs", "namespace PersonaEngine.Lib.Utils;\n\npublic sealed class AsyncQueue : IDisposable\n{\n private readonly Queue _queue = new();\n\n private readonly SemaphoreSlim _semaphore = new(0);\n\n private bool _isDisposed;\n\n public void Dispose()\n {\n if ( _isDisposed )\n {\n return;\n }\n\n _semaphore.Dispose();\n _isDisposed = true;\n }\n\n public void Enqueue(T item)\n {\n lock (_queue)\n {\n _queue.Enqueue(item);\n _semaphore.Release();\n }\n }\n\n public async Task DequeueAsync(CancellationToken ct = default)\n {\n await _semaphore.WaitAsync(ct);\n\n lock (_queue)\n {\n return _queue.Dequeue();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleWordInfo.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Holds the intrinsic properties and calculated state of a single word for rendering.\n/// Designed as a struct to potentially reduce GC pressure when dealing with many words,\n/// but be mindful of copying costs if passed around extensively by value.\n/// \npublic struct SubtitleWordInfo\n{\n public string Text;\n\n public Vector2 Size;\n\n public float AbsoluteStartTime;\n\n public float Duration;\n\n public Vector2 Position;\n\n public float AnimationProgress;\n\n public FSColor CurrentColor;\n\n public Vector2 CurrentScale;\n\n public bool IsActive(float currentTime) { return currentTime >= AbsoluteStartTime && currentTime < AbsoluteStartTime + Duration; }\n\n public bool IsComplete(float currentTime) { return currentTime >= AbsoluteStartTime + Duration; }\n\n public bool HasStarted(float currentTime) { return currentTime >= AbsoluteStartTime; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Spout/SpoutRegistry.cs", "using PersonaEngine.Lib.Configuration;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Spout;\n\npublic class SpoutRegistry : IDisposable\n{\n private readonly SpoutConfiguration[] _configs;\n\n private readonly GL _gl;\n\n private readonly Dictionary _spoutManagers = new();\n\n public SpoutRegistry(GL gl, SpoutConfiguration[] configs)\n {\n _gl = gl;\n _configs = configs;\n\n foreach ( var config in _configs )\n {\n GetOrCreateManager(config);\n }\n }\n\n public void Dispose()\n {\n foreach ( var manager in _spoutManagers.Values )\n {\n manager.Dispose();\n }\n\n _spoutManagers.Clear();\n }\n\n public SpoutManager GetOrCreateManager(SpoutConfiguration config)\n {\n if ( !_spoutManagers.TryGetValue(config.OutputName, out var manager) )\n {\n manager = new SpoutManager(_gl, config);\n _spoutManagers.Add(config.OutputName, manager);\n }\n\n return manager;\n }\n\n public void BeginFrame(string spoutName)\n {\n if ( string.IsNullOrEmpty(spoutName) || !_spoutManagers.TryGetValue(spoutName, out var manager) )\n {\n return;\n }\n\n manager.BeginFrame();\n }\n\n public void SendFrame(string spoutName)\n {\n if ( string.IsNullOrEmpty(spoutName) || !_spoutManagers.TryGetValue(spoutName, out var manager) )\n {\n return;\n }\n\n manager.SendFrame();\n }\n\n public void ResizeAll(int width, int height)\n {\n foreach ( var manager in _spoutManagers.Values )\n {\n manager.ResizeFramebuffer(width, height);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/NotificationService.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements notification service\n/// \npublic class NotificationService : INotificationService\n{\n private readonly List _activeNotifications = new();\n\n public void ShowInfo(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Info, message, 5f, action, actionLabel)); }\n\n public void ShowSuccess(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Success, message, 5f, action, actionLabel)); }\n\n public void ShowWarning(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Warning, message, 8f, action, actionLabel)); }\n\n public void ShowError(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Error, message, 10f, action, actionLabel)); }\n\n public IReadOnlyList GetActiveNotifications() { return _activeNotifications.AsReadOnly(); }\n\n public void Update(float deltaTime)\n {\n // Update remaining time for each notification\n for ( var i = _activeNotifications.Count - 1; i >= 0; i-- )\n {\n var notification = _activeNotifications[i];\n notification.RemainingTime -= deltaTime;\n\n // Remove expired notifications\n if ( notification.RemainingTime <= 0 )\n {\n _activeNotifications.RemoveAt(i);\n }\n }\n }\n\n private void AddNotification(Notification notification)\n {\n // Limit the number of active notifications\n if ( _activeNotifications.Count >= 5 )\n {\n _activeNotifications.RemoveAt(0);\n }\n\n _activeNotifications.Add(notification);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppView.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 描画クラス\n/// \n/// \n/// コンストラクタ\n/// \npublic class LAppView(LAppDelegate lapp)\n{\n /// \n /// デバイスからスクリーンへの行列\n /// \n private readonly CubismMatrix44 _deviceToScreen = new();\n\n /// \n /// タッチマネージャー\n /// \n private readonly TouchManager _touchManager = new();\n\n /// \n /// viewMatrix\n /// \n private readonly CubismViewMatrix _viewMatrix = new();\n\n /// \n /// 初期化する。\n /// \n public void Initialize()\n {\n lapp.GL.GetWindowSize(out var width, out var height);\n\n if ( width == 0 || height == 0 )\n {\n return;\n }\n\n // 縦サイズを基準とする\n var ratio = (float)width / height;\n var left = -ratio;\n var right = ratio;\n var bottom = LAppDefine.ViewLogicalLeft;\n var top = LAppDefine.ViewLogicalRight;\n\n _viewMatrix.SetScreenRect(left, right, bottom, top); // デバイスに対応する画面の範囲。 Xの左端, Xの右端, Yの下端, Yの上端\n _viewMatrix.Scale(LAppDefine.ViewScale, LAppDefine.ViewScale);\n\n _deviceToScreen.LoadIdentity(); // サイズが変わった際などリセット必須\n if ( width > height )\n {\n var screenW = MathF.Abs(right - left);\n _deviceToScreen.ScaleRelative(screenW / width, -screenW / width);\n }\n else\n {\n var screenH = MathF.Abs(top - bottom);\n _deviceToScreen.ScaleRelative(screenH / height, -screenH / height);\n }\n\n _deviceToScreen.TranslateRelative(-width * 0.5f, -height * 0.5f);\n\n // 表示範囲の設定\n _viewMatrix.MaxScale = LAppDefine.ViewMaxScale; // 限界拡大率\n _viewMatrix.MinScale = LAppDefine.ViewMinScale; // 限界縮小率\n\n // 表示できる最大範囲\n _viewMatrix.SetMaxScreenRect(\n LAppDefine.ViewLogicalMaxLeft,\n LAppDefine.ViewLogicalMaxRight,\n LAppDefine.ViewLogicalMaxBottom,\n LAppDefine.ViewLogicalMaxTop\n );\n }\n\n /// \n /// 描画する。\n /// \n public void Render()\n {\n var Live2DManager = lapp.Live2dManager;\n Live2DManager.ViewMatrix.SetMatrix(_viewMatrix);\n\n // Cubism更新・描画\n Live2DManager.OnUpdate();\n }\n\n /// \n /// タッチされたときに呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesBegan(float pointX, float pointY)\n {\n _touchManager.TouchesBegan(pointX, pointY);\n CubismLog.Debug($\"[Live2D]touchesBegan x:{pointX:#.##} y:{pointY:#.##}\");\n }\n\n /// \n /// タッチしているときにポインタが動いたら呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesMoved(float pointX, float pointY)\n {\n var viewX = TransformViewX(_touchManager.GetX());\n var viewY = TransformViewY(_touchManager.GetY());\n\n _touchManager.TouchesMoved(pointX, pointY);\n\n lapp.Live2dManager.OnDrag(viewX, viewY);\n }\n\n /// \n /// タッチが終了したら呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesEnded(float _, float __)\n {\n // タッチ終了\n var live2DManager = lapp.Live2dManager;\n live2DManager.OnDrag(0.0f, 0.0f);\n // シングルタップ\n var x = _deviceToScreen.TransformX(_touchManager.GetX()); // 論理座標変換した座標を取得。\n var y = _deviceToScreen.TransformY(_touchManager.GetY()); // 論理座標変換した座標を取得。\n CubismLog.Debug($\"[Live2D]touchesEnded x:{x:#.##} y:{y:#.##}\");\n live2DManager.OnTap(x, y);\n }\n\n /// \n /// X座標をView座標に変換する。\n /// \n /// デバイスX座標\n public float TransformViewX(float deviceX)\n {\n var screenX = _deviceToScreen.TransformX(deviceX); // 論理座標変換した座標を取得。\n\n return _viewMatrix.InvertTransformX(screenX); // 拡大、縮小、移動後の値。\n }\n\n /// \n /// Y座標をView座標に変換する。\n /// \n /// デバイスY座標\n public float TransformViewY(float deviceY)\n {\n var screenY = _deviceToScreen.TransformY(deviceY); // 論理座標変換した座標を取得。\n\n return _viewMatrix.InvertTransformY(screenY); // 拡大、縮小、移動後の値。\n }\n\n /// \n /// X座標をScreen座標に変換する。\n /// \n /// デバイスX座標\n public float TransformScreenX(float deviceX) { return _deviceToScreen.TransformX(deviceX); }\n\n /// \n /// Y座標をScreen座標に変換する。\n /// \n /// デバイスY座標\n public float TransformScreenY(float deviceY) { return _deviceToScreen.TransformY(deviceY); }\n\n /// \n /// 別レンダリングターゲットにモデルを描画するサンプルで\n /// 描画時のαを決定する\n /// \n public static float GetSpriteAlpha(int assign)\n {\n // assignの数値に応じて適当に決定\n var alpha = 0.25f + assign * 0.5f; // サンプルとしてαに適当な差をつける\n if ( alpha > 1.0f )\n {\n alpha = 1.0f;\n }\n\n if ( alpha < 0.1f )\n {\n alpha = 0.1f;\n }\n\n return alpha;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/ISpeechTranscriptor.cs", "using PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\n/// \n/// Represents a segment of transcribed text.\n/// \npublic interface ISpeechTranscriptor : IAsyncDisposable\n{\n /// \n /// Transcribes the given audio stream to segments of text.\n /// \n /// The audio source to transcribe.\n /// The cancellation token to observe.\n /// \n IAsyncEnumerable TranscribeAsync(IAudioSource source, CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeEntry.cs", "using System.Text.Json;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic abstract record PhonemeEntry\n{\n // Factory method to create the appropriate entry type from JSON\n public static PhonemeEntry FromJsonElement(JsonElement element)\n {\n if ( element.ValueKind == JsonValueKind.String )\n {\n return new SimplePhonemeEntry(element.GetString()!);\n }\n\n if ( element.ValueKind == JsonValueKind.Object )\n {\n var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);\n foreach ( var property in element.EnumerateObject() )\n {\n if ( property.Value.ValueKind == JsonValueKind.String )\n {\n dict[property.Name] = property.Value.GetString()!;\n }\n }\n\n return new ContextualPhonemeEntry(dict);\n }\n\n throw new JsonException($\"Unexpected JSON element type: {element.ValueKind}\");\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionQueueEntry.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\npublic class CubismMotionQueueEntry\n{\n public CubismMotionQueueEntry()\n {\n Available = true;\n StartTime = -1.0f;\n EndTime = -1.0f;\n }\n\n /// \n /// Motion\n /// \n public required ACubismMotion Motion { get; set; }\n\n /// \n /// Activation flag\n /// \n public bool Available { get; set; }\n\n /// \n /// Completion flag\n /// \n public bool Finished { get; set; }\n\n /// \n /// Start flag (since 0.9.00)\n /// \n public bool Started { get; set; }\n\n /// \n /// Motion playback start time [seconds]\n /// \n public float StartTime { get; set; }\n\n /// \n /// Fade-in start time (only the first time for loops) [seconds]\n /// \n public float FadeInStartTime { get; set; }\n\n /// \n /// Scheduled end time [seconds]\n /// \n public float EndTime { get; set; }\n\n /// \n /// Time state [seconds]\n /// \n public float StateTime { get; private set; }\n\n /// \n /// Weight state\n /// \n public float StateWeight { get; private set; }\n\n /// \n /// Last time checked by the Motion side\n /// \n public float LastEventCheckSeconds { get; set; }\n\n public float FadeOutSeconds { get; private set; }\n\n public bool IsTriggeredFadeOut { get; private set; }\n\n /// \n /// Set the start of fade-out.\n /// \n /// Time required for fade-out [seconds]\n public void SetFadeout(float fadeOutSeconds)\n {\n FadeOutSeconds = fadeOutSeconds;\n IsTriggeredFadeOut = true;\n }\n\n /// \n /// Start fade-out.\n /// \n /// Time required for fade-out [seconds]\n /// Accumulated delta time [seconds]\n public void StartFadeout(float fadeOutSeconds, float userTimeSeconds)\n {\n var newEndTimeSeconds = userTimeSeconds + fadeOutSeconds;\n IsTriggeredFadeOut = true;\n\n if ( EndTime < 0.0f || newEndTimeSeconds < EndTime )\n {\n EndTime = newEndTimeSeconds;\n }\n }\n\n /// \n /// Set the motion state.\n /// \n /// Current time [seconds]\n /// Motion weight\n public void SetState(float timeSeconds, float weight)\n {\n StateTime = timeSeconds;\n StateWeight = weight;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OpenNlpSentenceDetector.cs", "using Microsoft.Extensions.Logging;\n\nusing OpenNLP.Tools.SentenceDetect;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of OpenNLP-based sentence detection\n/// \npublic class OpenNlpSentenceDetector : IMlSentenceDetector\n{\n private readonly EnglishMaximumEntropySentenceDetector _detector;\n\n private readonly ILogger _logger;\n\n private bool _disposed;\n\n public OpenNlpSentenceDetector(string modelPath, ILogger logger)\n {\n if ( string.IsNullOrEmpty(modelPath) )\n {\n throw new ArgumentException(\"Model path cannot be null or empty\", nameof(modelPath));\n }\n\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n try\n {\n _detector = new EnglishMaximumEntropySentenceDetector(modelPath);\n _logger.LogInformation(\"Initialized OpenNLP sentence detector from {ModelPath}\", modelPath);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to initialize OpenNLP sentence detector\");\n\n throw;\n }\n }\n\n /// \n /// Detects sentences in text using OpenNLP\n /// \n public IReadOnlyList Detect(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Array.Empty();\n }\n\n try\n {\n var sentences = _detector.SentenceDetect(text);\n\n return sentences;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error detecting sentences\");\n\n throw;\n }\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/SilkNetApi.cs", "using PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D;\n\npublic class SilkNetApi : OpenGLApi\n{\n private readonly GL Gl;\n\n private readonly int Height;\n\n private readonly int Width;\n\n public SilkNetApi(GL gl, int width, int height)\n {\n Width = width;\n Height = height;\n Gl = gl;\n }\n\n public override bool IsES2 => false;\n\n public override bool IsPhoneES2 => false;\n\n public override bool AlwaysClear => false;\n\n public override void GetWindowSize(out int w, out int h)\n {\n w = Width;\n h = Height;\n }\n\n public override void ActiveTexture(int bit) { Gl.ActiveTexture((TextureUnit)bit); }\n\n public override void AttachShader(int program, int shader) { Gl.AttachShader((uint)program, (uint)shader); }\n\n public override void BindBuffer(int target, int buffer) { Gl.BindBuffer((BufferTargetARB)target, (uint)buffer); }\n\n public override void BindFramebuffer(int target, int framebuffer) { Gl.BindFramebuffer((FramebufferTarget)target, (uint)framebuffer); }\n\n public override void BindTexture(int target, int texture) { Gl.BindTexture((TextureTarget)target, (uint)texture); }\n\n public override void BindVertexArrayOES(int array) { Gl.BindVertexArray((uint)array); }\n\n public override void BlendFunc(int sfactor, int dfactor) { Gl.BlendFunc((BlendingFactor)sfactor, (BlendingFactor)dfactor); }\n\n public override void BlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { Gl.BlendFuncSeparate((BlendingFactor)srcRGB, (BlendingFactor)dstRGB, (BlendingFactor)srcAlpha, (BlendingFactor)dstAlpha); }\n\n public override void Clear(int mask) { Gl.Clear((ClearBufferMask)mask); }\n\n public override void ClearColor(float r, float g, float b, float a) { Gl.ClearColor(r, g, b, a); }\n\n public override void ClearDepthf(float depth) { Gl.ClearDepth(depth); }\n\n public override void ColorMask(bool r, bool g, bool b, bool a) { Gl.ColorMask(r, g, b, a); }\n\n public override void CompileShader(int shader) { Gl.CompileShader((uint)shader); }\n\n public override int CreateProgram() { return (int)Gl.CreateProgram(); }\n\n public override int CreateShader(int type) { return (int)Gl.CreateShader((ShaderType)type); }\n\n public override void DeleteFramebuffer(int framebuffer) { Gl.DeleteFramebuffer((uint)framebuffer); }\n\n public override void DeleteProgram(int program) { Gl.DeleteProgram((uint)program); }\n\n public override void DeleteShader(int shader) { Gl.DeleteShader((uint)shader); }\n\n public override void DeleteTexture(int texture) { Gl.DeleteTexture((uint)texture); }\n\n public override void DetachShader(int program, int shader) { Gl.DetachShader((uint)program, (uint)shader); }\n\n public override void Disable(int cap) { Gl.Disable((EnableCap)cap); }\n\n public override void DisableVertexAttribArray(int index) { Gl.DisableVertexAttribArray((uint)index); }\n\n public override void DrawElements(int mode, int count, int type, nint indices)\n {\n unsafe\n {\n Gl.DrawElements((PrimitiveType)mode, (uint)count, (DrawElementsType)type, (void*)indices);\n }\n }\n\n public override void Enable(int cap) { Gl.Enable((EnableCap)cap); }\n\n public override void EnableVertexAttribArray(int index) { Gl.EnableVertexAttribArray((uint)index); }\n\n public override void FramebufferTexture2D(int target, int attachment, int textarget, int texture, int level)\n {\n Gl.FramebufferTexture2D((FramebufferTarget)target, (FramebufferAttachment)attachment,\n (TextureTarget)textarget, (uint)texture, level);\n }\n\n public override void FrontFace(int mode) { Gl.FrontFace((FrontFaceDirection)mode); }\n\n public override void GenerateMipmap(int target) { Gl.GenerateMipmap((TextureTarget)target); }\n\n public override int GenFramebuffer() { return (int)Gl.GenFramebuffer(); }\n\n public override int GenTexture() { return (int)Gl.GenTexture(); }\n\n public override int GetAttribLocation(int program, string name) { return Gl.GetAttribLocation((uint)program, name); }\n\n public override void GetBooleanv(int pname, bool[] data) { Gl.GetBoolean((GetPName)pname, out data[0]); }\n\n public override void GetIntegerv(int pname, out int data) { Gl.GetInteger((GetPName)pname, out data); }\n\n public override void GetIntegerv(int pname, int[] data) { Gl.GetInteger((GetPName)pname, out data[0]); }\n\n public override void GetProgramInfoLog(int program, out string infoLog)\n {\n var length = Gl.GetProgram((uint)program, GLEnum.InfoLogLength);\n infoLog = Gl.GetProgramInfoLog((uint)program);\n }\n\n public override unsafe void GetProgramiv(int program, int pname, int* length) { Gl.GetProgram((uint)program, (GLEnum)pname, length); }\n\n public override void GetShaderInfoLog(int shader, out string infoLog)\n {\n var length = Gl.GetShader((uint)shader, GLEnum.InfoLogLength);\n infoLog = Gl.GetShaderInfoLog((uint)shader);\n }\n\n public override unsafe void GetShaderiv(int shader, int pname, int* length) { Gl.GetShader((uint)shader, (GLEnum)pname, length); }\n\n public override int GetUniformLocation(int program, string name) { return Gl.GetUniformLocation((uint)program, name); }\n\n public override void GetVertexAttribiv(int index, int pname, out int @params) { Gl.GetVertexAttrib((uint)index, (VertexAttribPropertyARB)pname, out @params); }\n\n public override bool IsEnabled(int cap) { return Gl.IsEnabled((EnableCap)cap); }\n\n public override void LinkProgram(int program) { Gl.LinkProgram((uint)program); }\n\n public override void ShaderSource(int shader, string source) { Gl.ShaderSource((uint)shader, source); }\n\n public override void TexImage2D(int target, int level, int internalformat, int width, int height, int border,\n int format, int type, nint pixels)\n {\n unsafe\n {\n Gl.TexImage2D((TextureTarget)target, level, (InternalFormat)internalformat,\n (uint)width, (uint)height, border, (PixelFormat)format,\n (PixelType)type, pixels == 0 ? null : (void*)pixels);\n }\n }\n\n public override void TexParameterf(int target, int pname, float param) { Gl.TexParameter((TextureTarget)target, (TextureParameterName)pname, param); }\n\n public override void TexParameteri(int target, int pname, int param) { Gl.TexParameter((TextureTarget)target, (TextureParameterName)pname, param); }\n\n public override void Uniform1i(int location, int v0) { Gl.Uniform1(location, v0); }\n\n public override void Uniform4f(int location, float v0, float v1, float v2, float v3) { Gl.Uniform4(location, v0, v1, v2, v3); }\n\n public override void UniformMatrix4fv(int location, int count, bool transpose, float[] value) { Gl.UniformMatrix4(location, (uint)count, transpose, value); }\n\n public override void UseProgram(int program) { Gl.UseProgram((uint)program); }\n\n public override void ValidateProgram(int program) { Gl.ValidateProgram((uint)program); }\n\n public override void VertexAttribPointer(int index, int size, int type, bool normalized,\n int stride, nint pointer)\n {\n unsafe\n {\n Gl.VertexAttribPointer((uint)index, size, (VertexAttribPointerType)type,\n normalized, (uint)stride, (void*)pointer);\n }\n }\n\n public override void Viewport(int x, int y, int width, int height) { Gl.Viewport(x, y, (uint)width, (uint)height); }\n\n public override int GetError() { return (int)Gl.GetError(); }\n\n public override int GenBuffer() { return (int)Gl.GenBuffer(); }\n\n public override void BufferData(int target, int size, nint data, int usage)\n {\n unsafe\n {\n Gl.BufferData((BufferTargetARB)target, (nuint)size, (void*)data, (BufferUsageARB)usage);\n }\n }\n\n public override int GenVertexArray() { return (int)Gl.GenVertexArray(); }\n\n public override void BindVertexArray(int array) { Gl.BindVertexArray((uint)array); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/TextMeasurer.cs", "using System.Collections.Concurrent;\nusing System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Measures text dimensions using a specific font and caches the results.\n/// Provides information about available rendering width and line height.\n/// Thread-safe for use in concurrent processing.\n/// \npublic class TextMeasurer\n{\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly float _sideMargin;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n public TextMeasurer(DynamicSpriteFont font, float sideMargin, int initialWidth, int initialHeight)\n {\n Font = font;\n _sideMargin = sideMargin;\n UpdateViewport(initialWidth, initialHeight);\n LineHeight = Font.MeasureString(\"Ay\").Y;\n if ( LineHeight <= 0 )\n {\n LineHeight = Font.FontSize;\n }\n }\n\n public float AvailableWidth { get; private set; }\n\n public float LineHeight { get; private set; }\n\n public DynamicSpriteFont Font { get; }\n\n public void UpdateViewport(int width, int height)\n {\n _viewportWidth = width;\n _viewportHeight = height;\n AvailableWidth = Math.Max(1, _viewportWidth - 2 * _sideMargin);\n _cache.Clear();\n }\n\n public Vector2 MeasureText(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Vector2.Zero;\n }\n\n return _cache.GetOrAdd(text, t => Font.MeasureString(t));\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/ParticipantInfo.cs", "using OpenAI.Chat;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic record ParticipantInfo(\n string Id,\n string Name,\n ChatMessageRole Role\n);"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/EditorStateManager.cs", "using System.Collections.Immutable;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements editor state management\n/// \npublic class EditorStateManager : IEditorStateManager\n{\n private readonly Dictionary _activeOperations = new();\n\n private readonly Dictionary _stateValues = new();\n\n public event EventHandler StateChanged;\n\n public bool HasUnsavedChanges { get; private set; } = false;\n\n public void MarkAsChanged(string? sectionKey = null)\n {\n SetStateValue(\"HasUnsavedChanges\", false, true);\n HasUnsavedChanges = true;\n }\n\n public void MarkAsSaved()\n {\n SetStateValue(\"HasUnsavedChanges\", true, false);\n HasUnsavedChanges = false;\n }\n\n public ActiveOperation? GetActiveOperation() { return _activeOperations.Values.FirstOrDefault(); }\n\n public void RegisterActiveOperation(ActiveOperation operation)\n {\n _activeOperations[operation.Id] = operation;\n FireStateChanged(\"ActiveOperations\", null, _activeOperations.Values.ToImmutableList());\n }\n\n public void ClearActiveOperation(string operationId)\n {\n if ( _activeOperations.TryGetValue(operationId, out var operation) )\n {\n _activeOperations.Remove(operationId);\n operation.CancellationSource.Dispose();\n FireStateChanged(\"ActiveOperations\", null, _activeOperations.Values.ToImmutableList());\n }\n }\n\n private void SetStateValue(string key, T? oldValue, T newValue) where T : struct\n {\n _stateValues[key] = newValue;\n FireStateChanged(key, oldValue, newValue);\n }\n\n private void FireStateChanged(string key, T? oldValue, T newValue) where T : struct { StateChanged?.Invoke(this, new EditorStateChangedEventArgs(key, oldValue, newValue)); }\n\n private void FireStateChanged(string key, T? oldValue, T newValue) { StateChanged?.Invoke(this, new EditorStateChangedEventArgs(key, oldValue, newValue)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsInternal.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// 物理演算の適用先の種類。\n/// \npublic enum CubismPhysicsTargetType\n{\n /// \n /// パラメータに対して適用\n /// \n CubismPhysicsTargetType_Parameter\n}\n\n/// \n/// 物理演算の入力の種類。\n/// \npublic enum CubismPhysicsSource\n{\n /// \n /// X軸の位置から\n /// \n CubismPhysicsSource_X,\n\n /// \n /// Y軸の位置から\n /// \n CubismPhysicsSource_Y,\n\n /// \n /// 角度から\n /// \n CubismPhysicsSource_Angle\n}\n\n/// \n/// 物理演算で使用する外部の力。\n/// \npublic record PhysicsJsonEffectiveForces\n{\n /// \n /// 重力\n /// \n public Vector2 Gravity;\n\n /// \n /// 風\n /// \n public Vector2 Wind;\n}\n\n/// \n/// 物理演算のパラメータ情報。\n/// \npublic record CubismPhysicsParameter\n{\n /// \n /// パラメータID\n /// \n public required string Id;\n\n /// \n /// 適用先の種類\n /// \n public CubismPhysicsTargetType TargetType;\n}\n\n/// \n/// 物理演算の正規化情報。\n/// \npublic record CubismPhysicsNormalization\n{\n /// \n /// デフォルト値\n /// \n public float Default;\n\n /// \n /// 最小値\n /// \n public float Maximum;\n\n /// \n /// 最大値\n /// \n public float Minimum;\n}\n\n/// \n/// 物理演算の演算に使用する物理点の情報。\n/// \npublic record CubismPhysicsParticle\n{\n /// \n /// 加速度\n /// \n public float Acceleration;\n\n /// \n /// 遅れ\n /// \n public float Delay;\n\n /// \n /// 現在かかっている力\n /// \n public Vector2 Force;\n\n /// \n /// 初期位置\n /// \n public Vector2 InitialPosition;\n\n /// \n /// 最後の重力\n /// \n public Vector2 LastGravity;\n\n /// \n /// 最後の位置\n /// \n public Vector2 LastPosition;\n\n /// \n /// 動きやすさ\n /// \n public float Mobility;\n\n /// \n /// 現在の位置\n /// \n public Vector2 Position;\n\n /// \n /// 距離\n /// \n public float Radius;\n\n /// \n /// 現在の速度\n /// \n public Vector2 Velocity;\n}\n\n/// \n/// 物理演算の物理点の管理。\n/// \npublic record CubismPhysicsSubRig\n{\n /// \n /// 入力の最初のインデックス\n /// \n public int BaseInputIndex;\n\n /// \n /// 出力の最初のインデックス\n /// \n public int BaseOutputIndex;\n\n /// \n /// /物理点の最初のインデックス\n /// \n public int BaseParticleIndex;\n\n /// \n /// 入力の個数\n /// \n public int InputCount;\n\n /// \n /// 正規化された角度\n /// \n public required CubismPhysicsNormalization NormalizationAngle;\n\n /// \n /// 正規化された位置\n /// \n public required CubismPhysicsNormalization NormalizationPosition;\n\n /// \n /// 出力の個数\n /// \n public int OutputCount;\n\n /// \n /// 物理点の個数\n /// \n public int ParticleCount;\n}\n\n/// \n/// 正規化されたパラメータの取得関数の宣言。\n/// \n/// 演算結果の移動値\n/// 演算結果の角度\n/// パラメータの値\n/// パラメータの最小値\n/// パラメータの最大値\n/// パラメータのデフォルト値\n/// 正規化された位置\n/// 正規化された角度\n/// 値が反転されているか?\n/// 重み\npublic delegate void NormalizedPhysicsParameterValueGetter(\n ref Vector2 targetTranslation,\n ref float targetAngle,\n float value,\n float parameterMinimumValue,\n float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted,\n float weight\n);\n\n/// \n/// 物理演算の値の取得関数の宣言。\n/// \n/// 移動値\n/// 物理点のリスト\n/// \n/// 値が反転されているか?\n/// 重力\n/// \npublic delegate float PhysicsValueGetter(\n Vector2 translation,\n CubismPhysicsParticle[] particles,\n int currentParticleIndex,\n int particleIndex,\n bool isInverted,\n Vector2 parentGravity\n);\n\n/// \n/// 物理演算のスケールの取得関数の宣言。\n/// \n/// 移動値のスケール\n/// 角度のスケール\n/// スケール値\npublic delegate float PhysicsScaleGetter(Vector2 translationScale, float angleScale);\n\n/// \n/// 物理演算の入力情報。\n/// \npublic record CubismPhysicsInput\n{\n /// \n /// 正規化されたパラメータ値の取得関数\n /// \n public NormalizedPhysicsParameterValueGetter GetNormalizedParameterValue;\n\n /// \n /// 値が反転されているかどうか\n /// \n public bool Reflect;\n\n /// \n /// 入力元のパラメータ\n /// \n public required CubismPhysicsParameter Source;\n\n /// \n /// 入力元のパラメータのインデックス\n /// \n public int SourceParameterIndex;\n\n /// \n /// 入力の種類\n /// \n public CubismPhysicsSource Type;\n\n /// \n /// 重み\n /// \n public float Weight;\n}\n\n/// \n/// 物理演算の出力情報。\n/// \npublic record CubismPhysicsOutput\n{\n /// \n /// 角度のスケール\n /// \n public float AngleScale;\n\n /// \n /// 出力先のパラメータ\n /// \n public required CubismPhysicsParameter Destination;\n\n /// \n /// 出力先のパラメータのインデックス\n /// \n public int DestinationParameterIndex;\n\n /// \n /// 物理演算のスケール値の取得関数\n /// \n public PhysicsScaleGetter GetScale;\n\n /// \n /// 物理演算の値の取得関数\n /// \n public PhysicsValueGetter GetValue;\n\n /// \n /// 値が反転されているかどうか\n /// \n public bool Reflect;\n\n /// \n /// 移動値のスケール\n /// \n public Vector2 TranslationScale;\n\n /// \n /// 出力の種類\n /// \n public CubismPhysicsSource Type;\n\n /// \n /// 最小値を下回った時の値\n /// \n public float ValueBelowMinimum;\n\n /// \n /// 最大値をこえた時の値\n /// \n public float ValueExceededMaximum;\n\n /// \n /// 振り子のインデックス\n /// \n public int VertexIndex;\n\n /// \n /// 重み\n /// \n public float Weight;\n}\n\n/// \n/// 物理演算のデータ。\n/// \npublic record CubismPhysicsRig\n{\n /// \n /// 物理演算動作FPS\n /// \n public float Fps;\n\n /// \n /// 重力\n /// \n public Vector2 Gravity;\n\n /// \n /// 物理演算の入力のリスト\n /// \n public required CubismPhysicsInput[] Inputs;\n\n /// \n /// 物理演算の出力のリスト\n /// \n public required CubismPhysicsOutput[] Outputs;\n\n /// \n /// 物理演算の物理点のリスト\n /// \n public required CubismPhysicsParticle[] Particles;\n\n /// \n /// 物理演算の物理点の管理のリスト\n /// \n public required CubismPhysicsSubRig[] Settings;\n\n /// \n /// 物理演算の物理点の個数\n /// \n public int SubRigCount;\n\n /// \n /// 風\n /// \n public Vector2 Wind;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionInternal.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーション再生終了コールバック関数定義\n/// \npublic delegate void FinishedMotionCallback(CubismModel model, ACubismMotion self);\n\n/// \n/// イベントのコールバックに登録できる関数の型情報\n/// \n/// 発火したイベントの文字列データ\n/// コールバックに返される登録時に指定されたデータ\npublic delegate void CubismMotionEventFunction(CubismUserModel? customData, string eventValue);\n\n/// \n/// モーションカーブのセグメントの評価関数。\n/// \n/// モーションカーブの制御点リスト\n/// 評価する時間[秒]\npublic delegate float csmMotionSegmentEvaluationFunction(CubismMotionPoint[] points, int start, float time);\n\n/// \n/// モーションの優先度定数\n/// \npublic enum MotionPriority\n{\n PriorityNone = 0,\n\n PriorityIdle = 1,\n\n PriorityLow = 2,\n \n PriorityNormal = 3,\n\n PriorityForce = 4\n}\n\n/// \n/// 表情パラメータ値の計算方式\n/// \npublic enum ExpressionBlendType\n{\n /// \n /// 加算\n /// \n Add = 0,\n\n /// \n /// 乗算\n /// \n Multiply = 1,\n\n /// \n /// 上書き\n /// \n Overwrite = 2\n}\n\n/// \n/// 表情のパラメータ情報の構造体。\n/// \npublic record ExpressionParameter\n{\n /// \n /// パラメータID\n /// \n public required string ParameterId { get; set; }\n\n /// \n /// パラメータの演算種類\n /// \n public ExpressionBlendType BlendType { get; set; }\n\n /// \n /// 値\n /// \n public float Value { get; set; }\n}\n\n/// \n/// モーションカーブの種類。\n/// \npublic enum CubismMotionCurveTarget\n{\n /// \n /// モデルに対して\n /// \n Model,\n\n /// \n /// パラメータに対して\n /// \n Parameter,\n\n /// \n /// パーツの不透明度に対して\n /// \n PartOpacity\n}\n\n/// \n/// モーションカーブのセグメントの種類。\n/// \npublic enum CubismMotionSegmentType\n{\n /// \n /// リニア\n /// \n Linear = 0,\n\n /// \n /// ベジェ曲線\n /// \n Bezier = 1,\n\n /// \n /// ステップ\n /// \n Stepped = 2,\n\n /// \n /// インバースステップ\n /// \n InverseStepped = 3\n}\n\n/// \n/// モーションカーブの制御点。\n/// \npublic struct CubismMotionPoint\n{\n /// \n /// 時間[秒]\n /// \n public float Time;\n\n /// \n /// 値\n /// \n public float Value;\n}\n\n/// \n/// モーションカーブのセグメント。\n/// \npublic record CubismMotionSegment\n{\n /// \n /// 最初のセグメントへのインデックス\n /// \n public int BasePointIndex;\n\n /// \n /// 使用する評価関数\n /// \n public csmMotionSegmentEvaluationFunction Evaluate;\n\n /// \n /// セグメントの種類\n /// \n public CubismMotionSegmentType SegmentType;\n}\n\n/// \n/// モーションカーブ。\n/// \npublic record CubismMotionCurve\n{\n /// \n /// 最初のセグメントのインデックス\n /// \n public int BaseSegmentIndex;\n\n /// \n /// フェードインにかかる時間[秒]\n /// \n public float FadeInTime;\n\n /// \n /// フェードアウトにかかる時間[秒]\n /// \n public float FadeOutTime;\n\n /// \n /// カーブのID\n /// \n public string Id;\n\n /// \n /// セグメントの個数\n /// \n public int SegmentCount;\n\n /// \n /// カーブの種類\n /// \n public CubismMotionCurveTarget Type;\n}\n\n/// \n/// イベント。\n/// \npublic record CubismMotionEvent\n{\n public float FireTime;\n\n public string Value;\n}\n\n/// \n/// モーションデータ。\n/// \npublic record CubismMotionData\n{\n /// \n /// カーブの個数\n /// \n public int CurveCount;\n\n /// \n /// カーブのリスト\n /// \n public CubismMotionCurve[] Curves;\n\n /// \n /// モーションの長さ[秒]\n /// \n public float Duration;\n\n /// \n /// UserDataの個数\n /// \n public int EventCount;\n\n /// \n /// イベントのリスト\n /// \n public CubismMotionEvent[] Events;\n\n /// \n /// フレームレート\n /// \n public float Fps;\n\n /// \n /// ループするかどうか\n /// \n public bool Loop;\n\n /// \n /// ポイントのリスト\n /// \n public CubismMotionPoint[] Points;\n\n /// \n /// セグメントのリスト\n /// \n public CubismMotionSegment[] Segments;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AsyncAutoResetEvent.cs", "namespace PersonaEngine.Lib.Audio;\n\ninternal class AsyncAutoResetEvent\n{\n private static readonly Task Completed = Task.CompletedTask;\n\n private int isSignaled; // 0 for false, 1 for true\n\n private TaskCompletionSource? waitTcs;\n\n public Task WaitAsync()\n {\n if ( Interlocked.CompareExchange(ref isSignaled, 0, 1) == 1 )\n {\n return Completed;\n }\n\n var tcs = new TaskCompletionSource();\n var oldTcs = Interlocked.Exchange(ref waitTcs, tcs);\n oldTcs?.TrySetCanceled();\n\n return tcs.Task;\n }\n\n public void Set()\n {\n var toRelease = Interlocked.Exchange(ref waitTcs, null);\n if ( toRelease != null )\n {\n toRelease.SetResult(true);\n }\n else\n {\n Interlocked.Exchange(ref isSignaled, 1);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionExtensions.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Extension methods for accessing emotion data in audio segments\n/// \npublic static class EmotionExtensions\n{\n /// \n /// Gets the emotions associated with an audio segment\n /// \n public static IReadOnlyList GetEmotions(this AudioSegment segment, IEmotionService emotionService) { return emotionService.GetEmotions(segment.Id); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/PopAnimator.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Implements a \"pop\" animation effect using an overshoot easing function.\n/// \npublic class PopAnimator : IWordAnimator\n{\n private readonly float _overshoot;\n\n public PopAnimator(float overshoot = 1.70158f) { _overshoot = overshoot; }\n\n public Vector2 CalculateScale(float progress)\n {\n progress = Math.Clamp(progress, 0.0f, 1.0f);\n\n var scale = 1.0f + (_overshoot + 1.0f) * MathF.Pow(progress - 1.0f, 3) + _overshoot * MathF.Pow(progress - 1.0f, 2);\n\n scale = Math.Max(0.0f, scale);\n\n return new Vector2(scale, scale);\n }\n\n public FSColor CalculateColor(FSColor startColor, FSColor endColor, float progress)\n {\n progress = Math.Clamp(progress, 0.0f, 1.0f);\n\n var r = (byte)(startColor.R + (endColor.R - startColor.R) * progress);\n var g = (byte)(startColor.G + (endColor.G - startColor.G) * progress);\n var b = (byte)(startColor.B + (endColor.B - startColor.B) * progress);\n var a = (byte)(startColor.A + (endColor.A - startColor.A) * progress);\n\n return new FSColor(r, g, b, a);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/ConversationState.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic enum ConversationState\n{\n Initial,\n \n Initializing,\n\n Idle,\n\n Listening,\n\n ActiveTurn,\n \n ProcessingInput,\n\n WaitingForLlm,\n\n StreamingResponse,\n \n Speaking,\n\n Paused,\n\n Interrupted,\n\n Error,\n\n Ended\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismLog.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class CubismLog\n{\n public static void CubismLogPrintln(LogLevel level, string head, string fmt, params object?[] args)\n {\n var data = $\"[CSM] {head} {string.Format(fmt, args)}\";\n if ( level < CubismFramework.GetLoggingLevel() )\n {\n return;\n }\n\n CubismFramework.CoreLogFunction(data);\n }\n\n public static void Verbose(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Verbose, \"[V]\", fmt, args); }\n\n public static void Debug(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Debug, \"[D]\", fmt, args); }\n\n public static void Info(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Info, \"[I]\", fmt, args); }\n\n public static void Warning(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Warning, \"[W]\", fmt, args); }\n\n public static void Error(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Error, \"[E]\", fmt, args); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/ModelSettingObj.cs", "using System.ComponentModel;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\npublic record ModelSettingObj\n{\n public FileReference FileReferences { get; set; }\n\n public List HitAreas { get; set; }\n\n public Dictionary Layout { get; set; }\n\n public List Groups { get; set; }\n\n public record FileReference\n {\n public string Moc { get; set; }\n\n public List Textures { get; set; }\n\n public string Physics { get; set; }\n\n public string Pose { get; set; }\n\n public string DisplayInfo { get; set; }\n\n public List Expressions { get; set; }\n\n public Dictionary> Motions { get; set; }\n\n public string UserData { get; set; }\n\n public record Expression\n {\n public string Name { get; set; }\n\n public string File { get; set; }\n }\n\n public record Motion\n {\n public string File { get; set; }\n\n public string Sound { get; set; }\n\n [DefaultValue(-1f)] public float FadeInTime { get; set; }\n\n [DefaultValue(-1f)] public float FadeOutTime { get; set; }\n }\n }\n\n public record HitArea\n {\n public string Id { get; set; }\n\n public string Name { get; set; }\n }\n\n public record Parameter\n {\n public string Name { get; set; }\n\n public List Ids { get; set; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションの管理を行うクラス。\n/// \npublic class CubismMotionManager : CubismMotionQueueManager\n{\n /// \n /// 現在再生中のモーションの優先度\n /// \n public MotionPriority CurrentPriority { get; private set; }\n\n /// \n /// 再生予定のモーションの優先度。再生中は0になる。モーションファイルを別スレッドで読み込むときの機能。\n /// \n public MotionPriority ReservePriority { get; set; }\n\n /// \n /// 優先度を設定してモーションを開始する。\n /// \n /// モーション\n /// 再生が終了したモーションのインスタンスを削除するならtrue\n /// 優先度\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotionPriority(ACubismMotion motion, MotionPriority priority)\n {\n if ( priority == ReservePriority )\n {\n ReservePriority = 0; // 予約を解除\n }\n\n CurrentPriority = priority; // 再生中モーションの優先度を設定\n\n return StartMotion(motion);\n }\n\n /// \n /// モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// \n /// true 更新されている\n /// false 更新されていない\n /// \n public bool UpdateMotion(CubismModel model, float deltaTimeSeconds)\n {\n UserTimeSeconds += deltaTimeSeconds;\n\n var updated = DoUpdateMotion(model, UserTimeSeconds);\n\n if ( IsFinished() )\n {\n CurrentPriority = 0; // 再生中モーションの優先度を解除\n }\n\n return updated;\n }\n\n /// \n /// モーションを予約する。\n /// \n /// 優先度\n /// \n /// true 予約できた\n /// false 予約できなかった\n /// \n public bool ReserveMotion(MotionPriority priority)\n {\n if ( priority <= ReservePriority || priority <= CurrentPriority )\n {\n return false;\n }\n\n ReservePriority = priority;\n\n return true;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Core/CubismCore.cs", "using System.Numerics;\nusing System.Runtime.InteropServices;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Core;\n\npublic static class CsmEnum\n{\n //Alignment constraints.\n\n /// \n /// Necessary alignment for mocs (in bytes).\n /// \n public const int csmAlignofMoc = 64;\n\n /// \n /// Necessary alignment for models (in bytes).\n /// \n public const int CsmAlignofModel = 16;\n\n //Bit masks for non-dynamic drawable flags.\n\n /// \n /// Additive blend mode mask.\n /// \n public const byte CsmBlendAdditive = 1 << 0;\n\n /// \n /// Multiplicative blend mode mask.\n /// \n public const byte CsmBlendMultiplicative = 1 << 1;\n\n /// \n /// Double-sidedness mask.\n /// \n public const byte CsmIsDoubleSided = 1 << 2;\n\n /// \n /// Clipping mask inversion mode mask.\n /// \n public const byte CsmIsInvertedMask = 1 << 3;\n\n //Bit masks for dynamic drawable flags.\n\n /// \n /// Flag set when visible.\n /// \n public const byte CsmIsVisible = 1 << 0;\n\n /// \n /// Flag set when visibility did change.\n /// \n public const byte CsmVisibilityDidChange = 1 << 1;\n\n /// \n /// Flag set when opacity did change.\n /// \n public const byte CsmOpacityDidChange = 1 << 2;\n\n /// \n /// Flag set when draw order did change.\n /// \n public const byte CsmDrawOrderDidChange = 1 << 3;\n\n /// \n /// Flag set when render order did change.\n /// \n public const byte CsmRenderOrderDidChange = 1 << 4;\n\n /// \n /// Flag set when vertex positions did change.\n /// \n public const byte CsmVertexPositionsDidChange = 1 << 5;\n\n /// \n /// Flag set when blend color did change.\n /// \n public const byte CsmBlendColorDidChange = 1 << 6;\n\n //moc3 file format version.\n\n /// \n /// unknown\n /// \n public const int CsmMocVersion_Unknown = 0;\n\n /// \n /// moc3 file version 3.0.00 - 3.2.07\n /// \n public const int CsmMocVersion_30 = 1;\n\n /// \n /// moc3 file version 3.3.00 - 3.3.03\n /// \n public const int CsmMocVersion_33 = 2;\n\n /// \n /// moc3 file version 4.0.00 - 4.1.05\n /// \n public const int CsmMocVersion_40 = 3;\n\n /// \n /// moc3 file version 4.2.00 -\n /// \n public const int CsmMocVersion_42 = 4;\n\n //Parameter types.\n\n /// \n /// Normal parameter.\n /// \n public const int CsmParameterType_Normal = 0;\n\n /// \n /// Parameter for blend shape.\n /// \n public const int CsmParameterType_BlendShape = 1;\n}\n\n/// \n/// Log handler.\n/// \n/// Null-terminated string message to log.\npublic delegate void LogFunction(string message);\n\npublic static partial class CubismCore\n{\n //VERSION\n\n public static uint Version() { return GetVersion(); }\n\n /// \n /// Queries Core version.\n /// \n /// Core version.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetVersion\")]\n internal static partial uint GetVersion();\n\n /// \n /// Gets Moc file supported latest version.\n /// \n /// csmMocVersion (Moc file latest format version).\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetLatestMocVersion\")]\n internal static partial uint GetLatestMocVersion();\n\n /// \n /// Gets Moc file format version.\n /// \n /// Address of moc.\n /// Size of moc (in bytes).\n /// csmMocVersion\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetMocVersion\")]\n internal static partial uint GetMocVersion(IntPtr address, int size);\n\n //CONSISTENCY\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// '1' if Moc is valid; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmHasMocConsistency\")]\n [return: MarshalAs(UnmanagedType.I4)]\n internal static partial bool HasMocConsistency(IntPtr address, int size);\n\n //LOGGING\n\n /// \n /// Queries log handler.\n /// \n /// Log handler.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetLogFunction\")]\n internal static partial LogFunction GetLogFunction();\n\n /// \n /// Sets log handler.\n /// \n /// Handler to use.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmSetLogFunction\")]\n internal static partial void SetLogFunction(LogFunction handler);\n\n //MOC\n\n /// \n /// Tries to revive a moc from bytes in place.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmReviveMocInPlace\")]\n internal static partial IntPtr ReviveMocInPlace(IntPtr address, int size);\n\n //MODEL\n\n /// \n /// Queries size of a model in bytes.\n /// \n /// Moc to query.\n /// Valid size on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetSizeofModel\")]\n internal static partial int GetSizeofModel(IntPtr moc);\n\n /// \n /// Tries to instantiate a model in place.\n /// \n /// Source moc.\n /// Address to place instance at. Address must be aligned to 'csmAlignofModel'.\n /// Size of memory block for instance (in bytes).\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmInitializeModelInPlace\")]\n internal static partial IntPtr InitializeModelInPlace(IntPtr moc, IntPtr address, int size);\n\n /// \n /// Updates a model.\n /// \n /// Model to update.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmUpdateModel\")]\n internal static partial void UpdateModel(IntPtr model);\n\n //CANVAS\n\n /// \n /// Reads info on a model canvas.\n /// \n /// Model query.\n /// Canvas dimensions.\n /// Origin of model on canvas.\n /// Aspect used for scaling pixels to units.\n [DllImport(\"Live2DCubismCore\", EntryPoint = \"csmReadCanvasInfo\")]\n#pragma warning disable SYSLIB1054 // 使用 “LibraryImportAttribute” 而不是 “DllImportAttribute” 在编译时生成 P/Invoke 封送代码\n internal static extern void ReadCanvasInfo(IntPtr model, out Vector2 outSizeInPixels,\n#pragma warning restore SYSLIB1054 // 使用 “LibraryImportAttribute” 而不是 “DllImportAttribute” 在编译时生成 P/Invoke 封送代码\n out Vector2 outOriginInPixels, out float outPixelsPerUnit);\n\n //PARAMETERS\n\n /// \n /// Gets number of parameters.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterCount\")]\n internal static partial int GetParameterCount(IntPtr model);\n\n /// \n /// Gets parameter IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterIds\")]\n internal static unsafe partial sbyte** GetParameterIds(IntPtr model);\n\n /// \n /// Gets parameter types.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterTypes\")]\n internal static unsafe partial int* GetParameterTypes(IntPtr model);\n\n /// \n /// Gets minimum parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterMinimumValues\")]\n internal static unsafe partial float* GetParameterMinimumValues(IntPtr model);\n\n /// \n /// Gets maximum parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterMaximumValues\")]\n internal static unsafe partial float* GetParameterMaximumValues(IntPtr model);\n\n /// \n /// Gets default parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterDefaultValues\")]\n internal static unsafe partial float* GetParameterDefaultValues(IntPtr model);\n\n /// \n /// Gets read/write parameter values buffer.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterValues\")]\n internal static unsafe partial float* GetParameterValues(IntPtr model);\n\n /// \n /// Gets number of key values of each parameter.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterKeyCounts\")]\n internal static unsafe partial int* GetParameterKeyCounts(IntPtr model);\n\n /// \n /// Gets key values of each parameter.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterKeyValues\")]\n internal static unsafe partial float** GetParameterKeyValues(IntPtr model);\n\n //PARTS\n\n /// \n /// Gets number of parts.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartCount\")]\n internal static partial int GetPartCount(IntPtr model);\n\n /// \n /// Gets parts IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartIds\")]\n internal static unsafe partial sbyte** GetPartIds(IntPtr model);\n\n /// \n /// Gets read/write part opacities buffer.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartOpacities\")]\n internal static unsafe partial float* GetPartOpacities(IntPtr model);\n\n /// \n /// Gets part's parent part indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartParentPartIndices\")]\n internal static unsafe partial int* GetPartParentPartIndices(IntPtr model);\n\n //DRAWABLES\n\n /// \n /// Gets number of drawables.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableCount\")]\n internal static partial int GetDrawableCount(IntPtr model);\n\n /// \n /// Gets drawable IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIds\")]\n internal static unsafe partial sbyte** GetDrawableIds(IntPtr model);\n\n /// \n /// Gets constant drawable flags.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableConstantFlags\")]\n internal static unsafe partial byte* GetDrawableConstantFlags(IntPtr model);\n\n /// \n /// Gets dynamic drawable flags.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableDynamicFlags\")]\n internal static unsafe partial byte* GetDrawableDynamicFlags(IntPtr model);\n\n /// \n /// Gets drawable texture indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableTextureIndices\")]\n internal static unsafe partial int* GetDrawableTextureIndices(IntPtr model);\n\n /// \n /// Gets drawable draw orders.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableDrawOrders\")]\n internal static unsafe partial int* GetDrawableDrawOrders(IntPtr model);\n\n /// \n /// Gets drawable render orders.\n /// The higher the order, the more up front a drawable is.\n /// \n /// Model to query.\n /// Valid pointer on success; '0'otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableRenderOrders\")]\n internal static unsafe partial int* GetDrawableRenderOrders(IntPtr model);\n\n /// \n /// Gets drawable opacities.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableOpacities\")]\n internal static unsafe partial float* GetDrawableOpacities(IntPtr model);\n\n /// \n /// Gets numbers of masks of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMaskCounts\")]\n internal static unsafe partial int* GetDrawableMaskCounts(IntPtr model);\n\n /// \n /// Gets number of vertices of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMasks\")]\n internal static unsafe partial int** GetDrawableMasks(IntPtr model);\n\n /// \n /// Gets number of vertices of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexCounts\")]\n internal static unsafe partial int* GetDrawableVertexCounts(IntPtr model);\n\n /// \n /// Gets vertex position data of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; a null pointer otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexPositions\")]\n internal static unsafe partial Vector2** GetDrawableVertexPositions(IntPtr model);\n\n /// \n /// Gets texture coordinate data of each drawables.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexUvs\")]\n internal static unsafe partial Vector2** GetDrawableVertexUvs(IntPtr model);\n\n /// \n /// Gets number of triangle indices for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIndexCounts\")]\n internal static unsafe partial int* GetDrawableIndexCounts(IntPtr model);\n\n /// \n /// Gets triangle index data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIndices\")]\n internal static unsafe partial ushort** GetDrawableIndices(IntPtr model);\n\n /// \n /// Gets multiply color data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMultiplyColors\")]\n internal static unsafe partial Vector4* GetDrawableMultiplyColors(IntPtr model);\n\n /// \n /// Gets screen color data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableScreenColors\")]\n internal static unsafe partial Vector4* GetDrawableScreenColors(IntPtr model);\n\n /// \n /// Gets drawable's parent part indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableParentPartIndices\")]\n internal static unsafe partial int* GetDrawableParentPartIndices(IntPtr model);\n\n /// \n /// Resets all dynamic drawable flags.\n /// \n /// Model containing flags.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmResetDrawableDynamicFlags\")]\n internal static unsafe partial void ResetDrawableDynamicFlags(IntPtr model);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/TouchManager.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\npublic class TouchManager\n{\n /// \n /// 前回の値から今回の値へのxの移動距離。\n /// \n private float _deltaX;\n\n /// \n /// 前回の値から今回の値へのyの移動距離。\n /// \n private float _deltaY;\n\n /// \n /// フリップが有効かどうか\n /// \n private bool _flipAvailable;\n\n /// \n /// 2本以上でタッチしたときの指の距離\n /// \n private float _lastTouchDistance;\n\n /// \n /// シングルタッチ時のxの値\n /// \n private float _lastX;\n\n /// \n /// ダブルタッチ時の一つ目のxの値\n /// \n private float _lastX1;\n\n /// \n /// ダブルタッチ時の二つ目のxの値\n /// \n private float _lastX2;\n\n /// \n /// シングルタッチ時のyの値\n /// \n private float _lastY;\n\n /// \n /// ダブルタッチ時の一つ目のyの値\n /// \n private float _lastY1;\n\n /// \n /// ダブルタッチ時の二つ目のyの値\n /// \n private float _lastY2;\n\n /// \n /// このフレームで掛け合わせる拡大率。拡大操作中以外は1。\n /// \n private float _scale;\n\n /// \n /// タッチを開始した時のyの値\n /// \n private float _startX;\n\n /// \n /// タッチを開始した時のxの値\n /// \n private float _startY;\n\n /// \n /// シングルタッチ時はtrue\n /// \n private bool _touchSingle;\n\n public TouchManager() { _scale = 1.0f; }\n\n public float GetCenterX() { return _lastX; }\n\n public float GetCenterY() { return _lastY; }\n\n public float GetDeltaX() { return _deltaX; }\n\n public float GetDeltaY() { return _deltaY; }\n\n public float GetStartX() { return _startX; }\n\n public float GetStartY() { return _startY; }\n\n public float GetScale() { return _scale; }\n\n public float GetX() { return _lastX; }\n\n public float GetY() { return _lastY; }\n\n public float GetX1() { return _lastX1; }\n\n public float GetY1() { return _lastY1; }\n\n public float GetX2() { return _lastX2; }\n\n public float GetY2() { return _lastY2; }\n\n public bool IsSingleTouch() { return _touchSingle; }\n\n public bool IsFlickAvailable() { return _flipAvailable; }\n\n public void DisableFlick() { _flipAvailable = false; }\n\n /// \n /// タッチ開始時イベント\n /// \n /// タッチした画面のyの値\n /// タッチした画面のxの値\n public void TouchesBegan(float deviceX, float deviceY)\n {\n _lastX = deviceX;\n _lastY = deviceY;\n _startX = deviceX;\n _startY = deviceY;\n _lastTouchDistance = -1.0f;\n _flipAvailable = true;\n _touchSingle = true;\n }\n\n /// \n /// ドラッグ時のイベント\n /// \n /// タッチした画面のxの値\n /// タッチした画面のyの値\n public void TouchesMoved(float deviceX, float deviceY)\n {\n _lastX = deviceX;\n _lastY = deviceY;\n _lastTouchDistance = -1.0f;\n _touchSingle = true;\n }\n\n /// \n /// ドラッグ時のイベント\n /// \n /// 1つめのタッチした画面のxの値\n /// 1つめのタッチした画面のyの値\n /// 2つめのタッチした画面のxの値\n /// 2つめのタッチした画面のyの値\n public void TouchesMoved(float deviceX1, float deviceY1, float deviceX2, float deviceY2)\n {\n var distance = CalculateDistance(deviceX1, deviceY1, deviceX2, deviceY2);\n var centerX = (deviceX1 + deviceX2) * 0.5f;\n var centerY = (deviceY1 + deviceY2) * 0.5f;\n\n if ( _lastTouchDistance > 0.0f )\n {\n _scale = MathF.Pow(distance / _lastTouchDistance, 0.75f);\n _deltaX = CalculateMovingAmount(deviceX1 - _lastX1, deviceX2 - _lastX2);\n _deltaY = CalculateMovingAmount(deviceY1 - _lastY1, deviceY2 - _lastY2);\n }\n else\n {\n _scale = 1.0f;\n _deltaX = 0.0f;\n _deltaY = 0.0f;\n }\n\n _lastX = centerX;\n _lastY = centerY;\n _lastX1 = deviceX1;\n _lastY1 = deviceY1;\n _lastX2 = deviceX2;\n _lastY2 = deviceY2;\n _lastTouchDistance = distance;\n _touchSingle = false;\n }\n\n /// \n /// フリックの距離測定\n /// \n /// フリック距離\n public float GetFlickDistance() { return CalculateDistance(_startX, _startY, _lastX, _lastY); }\n\n /// \n /// 点1から点2への距離を求める\n /// \n /// 1つめのタッチした画面のxの値\n /// 1つめのタッチした画面のyの値\n /// 2つめのタッチした画面のxの値\n /// 2つめのタッチした画面のyの値\n /// 2点の距離\n public static float CalculateDistance(float x1, float y1, float x2, float y2) { return MathF.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); }\n\n /// \n /// 二つの値から、移動量を求める。\n /// 違う方向の場合は移動量0。同じ方向の場合は、絶対値が小さい方の値を参照する\n /// \n /// 1つめの移動量\n /// 2つめの移動量\n /// 小さい方の移動量\n public static float CalculateMovingAmount(float v1, float v2)\n {\n if ( v1 > 0.0f != v2 > 0.0f )\n {\n return 0.0f;\n }\n\n var sign = v1 > 0.0f ? 1.0f : -1.0f;\n var absoluteValue1 = MathF.Abs(v1);\n var absoluteValue2 = MathF.Abs(v2);\n\n return sign * (absoluteValue1 < absoluteValue2 ? absoluteValue1 : absoluteValue2);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigSectionEditorBase.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Base implementation for configuration section editors\n/// \npublic abstract class ConfigSectionEditorBase : IConfigSectionEditor, IDisposable\n{\n protected readonly IUiConfigurationManager ConfigManager;\n\n protected readonly IEditorStateManager StateManager;\n\n protected internal bool _hasUnsavedChanges = false;\n\n protected ConfigSectionEditorBase(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager)\n {\n ConfigManager = configManager ?? throw new ArgumentNullException(nameof(configManager));\n StateManager = stateManager ?? throw new ArgumentNullException(nameof(stateManager));\n }\n\n public abstract string SectionKey { get; }\n\n public abstract string DisplayName { get; }\n\n public bool HasUnsavedChanges => _hasUnsavedChanges;\n\n public virtual void Initialize() { }\n\n public abstract void Render();\n\n public virtual void RenderMenuItems() { }\n\n public virtual void Update(float deltaTime) { }\n\n public virtual void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n if ( args.Type is ConfigurationChangedEventArgs.ChangeType.Saved or ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n _hasUnsavedChanges = false;\n }\n }\n\n public virtual void Dispose()\n {\n // Base implementation does nothing\n GC.SuppressFinalize(this);\n }\n\n protected void MarkAsChanged()\n {\n if ( !_hasUnsavedChanges )\n {\n _hasUnsavedChanges = true;\n StateManager.MarkAsChanged(SectionKey);\n }\n }\n\n protected void MarkAsSaved()\n {\n _hasUnsavedChanges = false;\n StateManager.MarkAsSaved();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismMatrix44.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 4x4行列の便利クラス。\n/// \npublic record CubismMatrix44\n{\n private readonly float[] _mpt1 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n private readonly float[] _mpt2 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n private readonly float[] Ident = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n public float[] _mpt = new float[16];\n\n /// \n /// 4x4行列データ\n /// \n protected float[] _tr = new float[16];\n\n /// \n /// コンストラクタ。\n /// \n public CubismMatrix44() { LoadIdentity(); }\n\n public float[] Tr => _tr;\n\n /// \n /// 単位行列に初期化する。\n /// \n public void LoadIdentity() { SetMatrix(Ident); }\n\n /// \n /// 行列を設定する。\n /// \n /// 16個の浮動小数点数で表される4x4の行列\n public void SetMatrix(float[] tr) { Array.Copy(tr, _tr, 16); }\n\n public void SetMatrix(CubismMatrix44 tr) { SetMatrix(tr.Tr); }\n\n /// \n /// X軸の拡大率を取得する。\n /// \n /// X軸の拡大率\n public float GetScaleX() { return _tr[0]; }\n\n /// \n /// Y軸の拡大率を取得する。\n /// \n /// Y軸の拡大率\n public float GetScaleY() { return _tr[5]; }\n\n /// \n /// X軸の移動量を取得する。\n /// \n /// X軸の移動量\n public float GetTranslateX() { return _tr[12]; }\n\n /// \n /// Y軸の移動量を取得する。\n /// \n /// Y軸の移動量\n public float GetTranslateY() { return _tr[13]; }\n\n /// \n /// X軸の値を現在の行列で計算する。\n /// \n /// X軸の値\n /// 現在の行列で計算されたX軸の値\n public float TransformX(float src) { return _tr[0] * src + _tr[12]; }\n\n /// \n /// Y軸の値を現在の行列で計算する。\n /// \n /// Y軸の値\n /// 現在の行列で計算されたY軸の値\n public float TransformY(float src) { return _tr[5] * src + _tr[13]; }\n\n /// \n /// X軸の値を現在の行列で逆計算する。\n /// \n /// X軸の値\n /// 現在の行列で逆計算されたX軸の値\n public float InvertTransformX(float src) { return (src - _tr[12]) / _tr[0]; }\n\n /// \n /// Y軸の値を現在の行列で逆計算する。\n /// \n /// Y軸の値\n /// 現在の行列で逆計算されたY軸の値\n public float InvertTransformY(float src) { return (src - _tr[13]) / _tr[5]; }\n\n /// \n /// 現在の行列の位置を起点にして相対的に移動する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void TranslateRelative(float x, float y)\n {\n _mpt1[12] = x;\n _mpt1[13] = y;\n MultiplyByMatrix(_mpt1);\n }\n\n /// \n /// 現在の行列の位置を指定した位置へ移動する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void Translate(float x, float y)\n {\n _tr[12] = x;\n _tr[13] = y;\n }\n\n /// \n /// 現在の行列のX軸の位置を指定した位置へ移動する。\n /// \n /// X軸の移動量\n public void TranslateX(float x) { _tr[12] = x; }\n\n /// \n /// 現在の行列のY軸の位置を指定した位置へ移動する。\n /// \n /// Y軸の移動量\n public void TranslateY(float y) { _tr[13] = y; }\n\n /// \n /// 現在の行列の拡大率を相対的に設定する。\n /// \n /// X軸の拡大率\n /// Y軸の拡大率\n public void ScaleRelative(float x, float y)\n {\n _mpt2[0] = x;\n _mpt2[5] = y;\n MultiplyByMatrix(_mpt2);\n }\n\n /// \n /// 現在の行列の拡大率を指定した倍率に設定する。\n /// \n /// X軸の拡大率\n /// Y軸の拡大率\n public void Scale(float x, float y)\n {\n _tr[0] = x;\n _tr[5] = y;\n }\n\n public void MultiplyByMatrix(float[] a)\n {\n Array.Fill(_mpt, 0);\n\n var n = 4;\n\n for ( var i = 0; i < n; ++i )\n {\n for ( var j = 0; j < n; ++j )\n {\n for ( var k = 0; k < n; ++k )\n {\n _mpt[j + i * 4] += a[k + i * 4] * _tr[j + k * 4];\n }\n }\n }\n\n Array.Copy(_mpt, _tr, 16);\n }\n\n /// \n /// 現在の行列に行列を乗算する。\n /// \n /// 行列\n public void MultiplyByMatrix(CubismMatrix44 m) { MultiplyByMatrix(m.Tr); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/Notification.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Notification data structure\n/// \npublic class Notification\n{\n public enum NotificationType\n {\n Info,\n\n Success,\n\n Warning,\n\n Error\n }\n\n public Notification(NotificationType type, string message, float duration = 5f, Action? action = null, string actionLabel = \"OK\")\n {\n Type = type;\n Message = message;\n RemainingTime = duration;\n Action = action;\n ActionLabel = actionLabel;\n }\n\n public string Id { get; } = Guid.NewGuid().ToString();\n\n public NotificationType Type { get; }\n\n public string Message { get; }\n\n public float RemainingTime { get; set; }\n\n public Action? Action { get; }\n\n public string ActionLabel { get; }\n\n public bool HasAction => Action != null;\n\n public void InvokeAction() { Action?.Invoke(); }\n\n public Vector4 GetBackgroundColor()\n {\n return Type switch {\n NotificationType.Info => new Vector4(0.2f, 0.4f, 0.8f, 0.2f),\n NotificationType.Success => new Vector4(0.2f, 0.8f, 0.2f, 0.2f),\n NotificationType.Warning => new Vector4(0.9f, 0.7f, 0.0f, 0.2f),\n NotificationType.Error => new Vector4(0.8f, 0.2f, 0.2f, 0.25f),\n _ => new Vector4(0.3f, 0.3f, 0.3f, 0.2f)\n };\n }\n\n public Vector4 GetTextColor()\n {\n return Type switch {\n NotificationType.Info => new Vector4(0.3f, 0.6f, 1.0f, 1.0f),\n NotificationType.Success => new Vector4(0.0f, 0.8f, 0.0f, 1.0f),\n NotificationType.Warning => new Vector4(1.0f, 0.7f, 0.0f, 1.0f),\n NotificationType.Error => new Vector4(1.0f, 0.3f, 0.3f, 1.0f),\n _ => new Vector4(0.9f, 0.9f, 0.9f, 1.0f)\n };\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppAllocator.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// メモリ確保・解放処理のインターフェースの実装。\n/// フレームワークから呼び出される。\n/// \npublic class LAppAllocator : ICubismAllocator\n{\n /// \n /// メモリ領域を割り当てる。\n /// \n /// 割り当てたいサイズ。\n /// 指定したメモリ領域\n public IntPtr Allocate(int size) { return Marshal.AllocHGlobal(size); }\n\n /// \n /// メモリ領域を解放する\n /// \n /// 解放するメモリ。\n public void Deallocate(IntPtr memory) { Marshal.FreeHGlobal(memory); }\n\n /// \n /// \n /// 割り当てたいサイズ。\n /// 割り当てたいサイズ。\n /// alignedAddress\n public unsafe IntPtr AllocateAligned(int size, int alignment)\n {\n IntPtr offset,\n shift,\n alignedAddress;\n\n IntPtr allocation;\n void** preamble;\n\n offset = alignment - 1 + sizeof(void*);\n\n allocation = Allocate((int)(size + offset));\n\n alignedAddress = allocation + sizeof(void*);\n\n shift = alignedAddress % alignment;\n\n if ( shift != 0 )\n {\n alignedAddress += alignment - shift;\n }\n\n preamble = (void**)alignedAddress;\n preamble[-1] = (void*)allocation;\n\n return alignedAddress;\n }\n\n /// \n /// \n /// 解放するメモリ。\n public unsafe void DeallocateAligned(IntPtr alignedMemory)\n {\n var preamble = (void**)alignedMemory;\n\n Deallocate(new IntPtr(preamble[-1]));\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/IWordAnimator.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Interface for defining word animation strategies (scale, color).\n/// \npublic interface IWordAnimator\n{\n Vector2 CalculateScale(float progress);\n\n FSColor CalculateColor(FSColor startColor, FSColor endColor, float progress);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigSectionRegistrationTask.cs", "using PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class ConfigSectionRegistrationTask : IStartupTask\n{\n private readonly ChatEditor _chatEditor;\n\n private readonly IConfigSectionRegistry _registry;\n\n private readonly RouletteWheelEditor _rouletteWheelEditor;\n\n private readonly TtsConfigEditor _ttsEditor;\n\n private readonly MicrophoneConfigEditor _microphoneConfigEditor;\n\n public ConfigSectionRegistrationTask(IConfigSectionRegistry registry, TtsConfigEditor ttsEditor, RouletteWheelEditor rouletteWheelEditor, ChatEditor chatEditor, MicrophoneConfigEditor microphoneConfigEditor)\n {\n _registry = registry;\n _ttsEditor = ttsEditor;\n _rouletteWheelEditor = rouletteWheelEditor;\n _chatEditor = chatEditor;\n _microphoneConfigEditor = microphoneConfigEditor;\n }\n\n public void Execute(GL _)\n {\n _registry.RegisterSection(_ttsEditor);\n _registry.RegisterSection(_rouletteWheelEditor);\n _registry.RegisterSection(_chatEditor);\n _registry.RegisterSection(_microphoneConfigEditor);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ProcessedText.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Result of text preprocessing\n/// \npublic class ProcessedText\n{\n public ProcessedText(string normalizedText, IReadOnlyList sentences)\n {\n NormalizedText = normalizedText;\n Sentences = sentences;\n }\n\n /// \n /// Normalized text\n /// \n public string NormalizedText { get; }\n\n /// \n /// Segmented sentences\n /// \n public IReadOnlyList Sentences { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigSectionRegistry.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements configuration section registry\n/// \npublic class ConfigSectionRegistry : IConfigSectionRegistry\n{\n private readonly Dictionary _sections = new();\n\n public void RegisterSection(IConfigSectionEditor section)\n {\n if ( section == null )\n {\n throw new ArgumentNullException(nameof(section));\n }\n\n _sections[section.SectionKey] = section;\n }\n\n public void UnregisterSection(string sectionKey) { _sections.Remove(sectionKey); }\n\n public IConfigSectionEditor GetSection(string sectionKey) { return _sections.TryGetValue(sectionKey, out var section) ? section : null; }\n\n public IReadOnlyList GetSections() { return _sections.Values.ToList().AsReadOnly(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/VertexArrayObject.cs", "using PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\npublic class VertexArrayObject : IDisposable\n{\n private readonly GL _gl;\n\n private readonly uint _handle;\n\n private readonly int _stride;\n\n public VertexArrayObject(GL glApi, int stride)\n {\n _gl = glApi;\n\n if ( stride <= 0 )\n {\n throw new ArgumentOutOfRangeException(nameof(stride));\n }\n\n _stride = stride;\n\n _gl.GenVertexArrays(1, out _handle);\n _gl.CheckError();\n }\n\n public void Dispose()\n {\n _gl.DeleteVertexArray(_handle);\n _gl.CheckError();\n }\n\n public void Bind()\n {\n _gl.BindVertexArray(_handle);\n _gl.CheckError();\n }\n\n public unsafe void VertexAttribPointer(int location, int size, VertexAttribPointerType type, bool normalized, int offset)\n {\n _gl.EnableVertexAttribArray((uint)location);\n _gl.VertexAttribPointer((uint)location, size, type, normalized, (uint)_stride, (void*)offset);\n _gl.CheckError();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeConstants.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Phonetic constants used in pronunciation\n/// \npublic class PhonemeConstants\n{\n public PhonemeConstants(bool useBritishEnglish) { UseBritishEnglish = useBritishEnglish; }\n\n /// \n /// Whether to use British English pronunciation\n /// \n public bool UseBritishEnglish { get; init; }\n\n /// \n /// US-specific tau sounds for flapping rules\n /// \n public HashSet UsTauSounds { get; } = new(\"aeiouAEIOUæɑɒɔəɛɪʊʌᵻ\");\n\n /// \n /// Currency symbols with their word representations\n /// \n public Dictionary CurrencyRepresentations { get; } = new() { { '$', (\"dollar\", \"cent\") }, { '£', (\"pound\", \"pence\") }, { '€', (\"euro\", \"cent\") } };\n\n public Dictionary Symbols { get; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismClippingContext.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Type;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic unsafe class CubismClippingContext(CubismClippingManager manager, int* clippingDrawableIndices, int clipCount)\n{\n /// \n /// このクリッピングで、クリッピングされる全ての描画オブジェクトの囲み矩形(毎回更新)\n /// \n public RectF AllClippedDrawRect = new();\n\n /// \n /// このマスクが割り当てられるレンダーテクスチャ(フレームバッファ)やカラーバッファのインデックス\n /// \n public int BufferIndex;\n\n /// \n /// このマスクにクリップされる描画オブジェクトのリスト\n /// \n public List ClippedDrawableIndexList = [];\n\n /// \n /// クリッピングマスクの数\n /// \n public int ClippingIdCount = clipCount;\n\n /// \n /// クリッピングマスクのIDリスト\n /// \n public int* ClippingIdList = clippingDrawableIndices;\n\n /// \n /// 現在の描画状態でマスクの準備が必要ならtrue\n /// \n public bool IsUsing;\n\n /// \n /// マスク用チャンネルのどの領域にマスクを入れるか(View座標-1..1, UVは0..1に直す)\n /// \n public RectF LayoutBounds = new();\n\n /// \n /// RGBAのいずれのチャンネルにこのクリップを配置するか(0:R , 1:G , 2:B , 3:A)\n /// \n public int LayoutChannelIndex = 0;\n\n /// \n /// 描画オブジェクトの位置計算結果を保持する行列\n /// \n public CubismMatrix44 MatrixForDraw = new();\n\n /// \n /// マスクの位置計算結果を保持する行列\n /// \n public CubismMatrix44 MatrixForMask = new();\n\n public CubismClippingManager Manager { get; } = manager;\n\n /// \n /// このマスクにクリップされる描画オブジェクトを追加する\n /// \n /// クリッピング対象に追加する描画オブジェクトのインデックス\n public void AddClippedDrawable(int drawableIndex) { ClippedDrawableIndexList.Add(drawableIndex); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/VoiceData.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Voice data for synthesis\n/// \npublic class VoiceData\n{\n private const int StyleDim = 256;\n\n private readonly ReadOnlyMemory _rawEmbedding;\n\n public VoiceData(string id, ReadOnlyMemory rawEmbedding)\n {\n Id = id;\n _rawEmbedding = rawEmbedding;\n }\n\n /// \n /// Voice ID\n /// \n public string Id { get; }\n\n public ReadOnlyMemory GetEmbedding(ReadOnlySpan inputDimensions)\n {\n var numTokens = GetNumTokens(inputDimensions);\n var offset = numTokens * StyleDim;\n\n // Check bounds to prevent access violations\n return offset + StyleDim > _rawEmbedding.Length\n ?\n // Return empty vector if out of bounds\n new float[StyleDim]\n :\n // Return the slice of memory at the specified offset\n _rawEmbedding.Slice(offset, StyleDim);\n }\n\n private int GetNumTokens(ReadOnlySpan inputDimensions)\n {\n var lastDim = inputDimensions[^1];\n\n return Math.Min(Math.Max(lastDim - 2, 0), 509);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/VadSegment.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\n/// \n/// Represents a voice activity detection segment.\n/// \npublic class VadSegment\n{\n /// \n /// Gets or sets the start time of the segment.\n /// \n public TimeSpan StartTime { get; set; }\n\n /// \n /// Gets or sets the duration of the segment.\n /// \n public TimeSpan Duration { get; set; }\n\n /// \n /// Gets or sets a value indicating whether this segment is the last one in the audio stream and can be incomplete.\n /// \n public bool IsIncomplete { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/SpeechTranscriptorOptions.cs", "using System.Globalization;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic record SpeechTranscriptorOptions\n{\n public bool LanguageAutoDetect { get; set; } = true;\n\n public bool RetrieveTokenDetails { get; set; }\n\n public CultureInfo Language { get; set; } = CultureInfo.GetCultureInfo(\"en-us\");\n\n public string? Prompt { get; set; }\n \n public WhisperConfigTemplate? Template { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ModelResource.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Model resource wrapper\n/// \npublic class ModelResource : IDisposable\n{\n private byte[]? _modelData;\n\n public ModelResource(string path) { Path = path; }\n\n /// \n /// Path to the model\n /// \n public string Path { get; }\n\n /// \n /// Whether the model is loaded\n /// \n public bool IsLoaded => _modelData != null;\n\n public void Dispose() { _modelData = null; }\n\n /// \n /// Gets the model data, loading it if necessary\n /// \n public async Task GetDataAsync()\n {\n if ( _modelData == null )\n {\n _modelData = await File.ReadAllBytesAsync(Path);\n }\n\n return _modelData;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IAudioBufferManager.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Manages audio buffers for playback.\n/// \npublic interface IAudioBufferManager : IAsyncDisposable\n{\n /// \n /// Gets the number of audio buffers in the queue.\n /// \n int BufferCount { get; }\n\n bool ProducerCompleted { get; }\n\n /// \n /// Enqueues audio segments for playback.\n /// \n /// Audio segments to enqueue.\n /// Cancellation token.\n Task EnqueueSegmentsAsync(IAsyncEnumerable audioSegments, CancellationToken cancellationToken);\n\n /// \n /// Tries to get the next audio buffer from the queue.\n /// \n /// The audio buffer if available.\n /// Timeout in milliseconds.\n /// Cancellation token.\n /// True if a buffer was retrieved, false otherwise.\n bool TryGetNextBuffer(out (Memory Data, AudioSegment Segment) buffer, int timeoutMs, CancellationToken cancellationToken);\n\n /// \n /// Clears all buffers from the queue.\n /// \n void Clear();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Id/CubismIdManager.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Id;\n\n/// \n/// ID名を管理する。\n/// \npublic class CubismIdManager\n{\n /// \n /// 登録されているIDのリスト\n /// \n private readonly List _ids = [];\n\n /// \n /// ID名をリストから登録する。\n /// \n /// ID名リスト\n public void RegisterIds(List list) { list.ForEach(item => { GetId(item); }); }\n\n /// \n /// ID名からIDを取得する。\n /// 未登録のID名の場合、登録も行う。\n /// \n /// ID名\n public string GetId(string item)\n {\n if ( _ids.Contains(item) )\n {\n return item;\n }\n\n _ids.Add(item);\n\n return item;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/ITextFilter.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic interface ITextFilter\n{\n int Priority { get; }\n\n ValueTask ProcessAsync(string text, CancellationToken cancellationToken = default);\n\n ValueTask PostProcessAsync(TextFilterResult textFilterResult, AudioSegment segment, CancellationToken cancellationToken = default);\n}\n\npublic record TextFilterResult\n{\n public string ProcessedText { get; set; } = string.Empty;\n\n public Dictionary Metadata { get; set; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismRendererProfile_OpenGLES2.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal class CubismRendererProfile_OpenGLES2(OpenGLApi gl)\n{\n /// \n /// モデル描画直前のアクティブなテクスチャ\n /// \n internal int LastActiveTexture;\n\n /// \n /// モデル描画直前の頂点バッファ\n /// \n internal int LastArrayBufferBinding;\n\n /// \n /// モデル描画直前のGL_SCISSOR_TESTパラメータ\n /// \n internal bool LastBlend;\n\n /// \n /// モデル描画直前のカラーブレンディングパラメータ\n /// \n internal int[] LastBlending = new int[4];\n\n /// \n /// モデル描画直前のGL_COLOR_WRITEMASKパラメータ\n /// \n internal bool[] LastColorMask = new bool[4];\n\n /// \n /// モデル描画直前のGL_CULL_FACEパラメータ\n /// \n internal bool LastCullFace;\n\n /// \n /// モデル描画直前のGL_DEPTH_TESTパラメータ\n /// \n internal bool LastDepthTest;\n\n /// \n /// モデル描画直前のElementバッファ\n /// \n internal int LastElementArrayBufferBinding;\n\n /// \n /// モデル描画直前のフレームバッファ\n /// \n internal int LastFBO;\n\n /// \n /// モデル描画直前のGL_CULL_FACEパラメータ\n /// \n internal int LastFrontFace;\n\n /// \n /// モデル描画直前のシェーダプログラムバッファ\n /// \n internal int LastProgram;\n\n /// \n /// モデル描画直前のGL_VERTEX_ATTRIB_ARRAY_ENABLEDパラメータ\n /// \n internal bool LastScissorTest;\n\n /// \n /// モデル描画直前のGL_STENCIL_TESTパラメータ\n /// \n internal bool LastStencilTest;\n\n /// \n /// モデル描画直前のテクスチャユニット0\n /// \n internal int LastTexture0Binding2D;\n\n /// \n /// モデル描画直前のテクスチャユニット1\n /// \n internal int LastTexture1Binding2D;\n\n /// \n /// モデル描画直前のテクスチャユニット1\n /// \n internal int[] LastVertexAttribArrayEnabled = new int[4];\n\n /// \n /// モデル描画直前のビューポート\n /// \n internal int[] LastViewport = new int[4];\n\n /// \n /// OpenGLES2のステートを保持する\n /// \n internal void Save()\n {\n //-- push state --\n gl.GetIntegerv(gl.GL_ARRAY_BUFFER_BINDING, out LastArrayBufferBinding);\n gl.GetIntegerv(gl.GL_ELEMENT_ARRAY_BUFFER_BINDING, out LastElementArrayBufferBinding);\n gl.GetIntegerv(gl.GL_CURRENT_PROGRAM, out LastProgram);\n\n gl.GetIntegerv(gl.GL_ACTIVE_TEXTURE, out LastActiveTexture);\n gl.ActiveTexture(gl.GL_TEXTURE1); //テクスチャユニット1をアクティブに(以後の設定対象とする)\n gl.GetIntegerv(gl.GL_TEXTURE_BINDING_2D, out LastTexture1Binding2D);\n\n gl.ActiveTexture(gl.GL_TEXTURE0); //テクスチャユニット0をアクティブに(以後の設定対象とする)\n gl.GetIntegerv(gl.GL_TEXTURE_BINDING_2D, out LastTexture0Binding2D);\n\n gl.GetVertexAttribiv(0, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[0]);\n gl.GetVertexAttribiv(1, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[1]);\n gl.GetVertexAttribiv(2, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[2]);\n gl.GetVertexAttribiv(3, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[3]);\n\n LastScissorTest = gl.IsEnabled(gl.GL_SCISSOR_TEST);\n LastStencilTest = gl.IsEnabled(gl.GL_STENCIL_TEST);\n LastDepthTest = gl.IsEnabled(gl.GL_DEPTH_TEST);\n LastCullFace = gl.IsEnabled(gl.GL_CULL_FACE);\n LastBlend = gl.IsEnabled(gl.GL_BLEND);\n\n gl.GetIntegerv(gl.GL_FRONT_FACE, out LastFrontFace);\n\n gl.GetBooleanv(gl.GL_COLOR_WRITEMASK, LastColorMask);\n\n // backup blending\n gl.GetIntegerv(gl.GL_BLEND_SRC_RGB, out LastBlending[0]);\n gl.GetIntegerv(gl.GL_BLEND_DST_RGB, out LastBlending[1]);\n gl.GetIntegerv(gl.GL_BLEND_SRC_ALPHA, out LastBlending[2]);\n gl.GetIntegerv(gl.GL_BLEND_DST_ALPHA, out LastBlending[3]);\n\n // モデル描画直前のFBOとビューポートを保存\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out LastFBO);\n gl.GetIntegerv(gl.GL_VIEWPORT, LastViewport);\n }\n\n /// \n /// 保持したOpenGLES2のステートを復帰させる\n /// \n internal void Restore()\n {\n gl.UseProgram(LastProgram);\n\n SetGlEnableVertexAttribArray(0, LastVertexAttribArrayEnabled[0] > 0);\n SetGlEnableVertexAttribArray(1, LastVertexAttribArrayEnabled[1] > 0);\n SetGlEnableVertexAttribArray(2, LastVertexAttribArrayEnabled[2] > 0);\n SetGlEnableVertexAttribArray(3, LastVertexAttribArrayEnabled[3] > 0);\n\n SetGlEnable(gl.GL_SCISSOR_TEST, LastScissorTest);\n SetGlEnable(gl.GL_STENCIL_TEST, LastStencilTest);\n SetGlEnable(gl.GL_DEPTH_TEST, LastDepthTest);\n SetGlEnable(gl.GL_CULL_FACE, LastCullFace);\n SetGlEnable(gl.GL_BLEND, LastBlend);\n\n gl.FrontFace(LastFrontFace);\n\n gl.ColorMask(LastColorMask[0], LastColorMask[1], LastColorMask[2], LastColorMask[3]);\n\n gl.BindBuffer(gl.GL_ARRAY_BUFFER, LastArrayBufferBinding); //前にバッファがバインドされていたら破棄する必要がある\n gl.BindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, LastElementArrayBufferBinding);\n\n gl.ActiveTexture(gl.GL_TEXTURE1); //テクスチャユニット1を復元\n gl.BindTexture(gl.GL_TEXTURE_2D, LastTexture1Binding2D);\n\n gl.ActiveTexture(gl.GL_TEXTURE0); //テクスチャユニット0を復元\n gl.BindTexture(gl.GL_TEXTURE_2D, LastTexture0Binding2D);\n\n gl.ActiveTexture(LastActiveTexture);\n\n // restore blending\n gl.BlendFuncSeparate(LastBlending[0], LastBlending[1], LastBlending[2], LastBlending[3]);\n }\n\n /// \n /// OpenGLES2の機能の有効・無効をセットする\n /// \n /// 有効・無効にする機能\n /// trueなら有効にする\n internal void SetGlEnable(int index, bool enabled)\n {\n if ( enabled )\n {\n gl.Enable(index);\n }\n else\n {\n gl.Disable(index);\n }\n }\n\n /// \n /// OpenGLES2のVertex Attribute Array機能の有効・無効をセットする\n /// \n /// 有効・無効にする機能\n /// trueなら有効にする\n internal void SetGlEnableVertexAttribArray(int index, bool enabled)\n {\n if ( enabled )\n {\n gl.EnableVertexAttribArray(index);\n }\n else\n {\n gl.DisableVertexAttribArray(index);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/IRenderComponent.cs", "using Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI;\n\npublic interface IRenderComponent : IDisposable\n{\n bool UseSpout { get; }\n\n string SpoutTarget { get; }\n \n /// \n /// Priority of the filter (higher values run first)\n /// \n int Priority { get; }\n\n void Update(float deltaTime);\n\n void Render(float deltaTime);\n\n void Resize();\n\n void Initialize(GL gl, IView view, IInputContext input);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismTextureColor.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// テクスチャの色をRGBAで扱うための構造体\n/// \npublic struct CubismTextureColor\n{\n /// \n /// 赤チャンネル\n /// \n public float R;\n\n /// \n /// 緑チャンネル\n /// \n public float G;\n\n /// \n /// 青チャンネル\n /// \n public float B;\n\n /// \n /// αチャンネル\n /// \n public float A;\n\n public CubismTextureColor()\n {\n R = 1.0f;\n G = 1.0f;\n B = 1.0f;\n A = 1.0f;\n }\n\n public CubismTextureColor(CubismTextureColor old)\n {\n R = old.R;\n G = old.G;\n B = old.B;\n A = old.A;\n Check();\n }\n\n public CubismTextureColor(float r, float g, float b, float a)\n {\n R = r;\n G = g;\n B = b;\n A = a;\n Check();\n }\n\n private void Check()\n {\n R = R > 1.0f ? 1f : R;\n G = G > 1.0f ? 1f : G;\n B = B > 1.0f ? 1f : B;\n A = A > 1.0f ? 1f : A;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IFallbackPhonemizer.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for fallback phoneme generation\n/// \npublic interface IFallbackPhonemizer : IAsyncDisposable\n{\n /// \n /// Gets phonemes for a word when the lexicon fails\n /// \n Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(string word, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/ShaderNames.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic enum ShaderNames\n{\n // SetupMask\n SetupMask,\n\n //Normal\n Normal,\n\n NormalMasked,\n\n NormalMaskedInverted,\n\n NormalPremultipliedAlpha,\n\n NormalMaskedPremultipliedAlpha,\n\n NormalMaskedInvertedPremultipliedAlpha,\n\n //Add\n Add,\n\n AddMasked,\n\n AddMaskedInverted,\n\n AddPremultipliedAlpha,\n\n AddMaskedPremultipliedAlpha,\n\n AddMaskedPremultipliedAlphaInverted,\n\n //Mult\n Mult,\n\n MultMasked,\n\n MultMaskedInverted,\n\n MultPremultipliedAlpha,\n\n MultMaskedPremultipliedAlpha,\n\n MultMaskedPremultipliedAlphaInverted\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserDataObj.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Model;\n\npublic record CubismModelUserDataObj\n{\n public MetaObj Meta { get; set; }\n\n public List UserData { get; set; }\n\n public record MetaObj\n {\n public int UserDataCount { get; set; }\n\n public int TotalUserDataSize { get; set; }\n }\n\n public record UserDataObj\n {\n public string Target { get; set; }\n\n public string Id { get; set; }\n\n public string Value { get; set; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanityTestData.cs", "namespace PersonaEngine.Lib.TTS.Profanity;\n\npublic class ProfanityTestData\n{\n public static IEnumerable<(string Sentence, bool ExpectedIsProfane)> TestCases => new List<(string, bool)> {\n // Explicit Profanity (Expanded)\n (\"You're a cunt and everyone knows it.\", true),\n (\"Holy shit, that's one massive cock!\", true),\n (\"Bullshit detector going off the charts.\", true),\n (\"Eat a bag of dicks, you worthless twat.\", true),\n (\"This nazi propaganda makes me sick.\", true),\n\n // Innocent Phrases (Expanded)\n (\"Mansfield's historical documents\", false),\n (\"Cockburn Harbour shipping schedule\", false),\n (\"Shitake mushroom risotto recipe\", false),\n (\"Cummins engine specifications\", false),\n (\"Titmouse spotted in woodland area\", false),\n\n // Foreign Words (Expanded)\n (\"Fart means 'speed' in Norwegian\", false),\n (\"Kuk (Polish for 'rooster') symbolism\", false),\n (\"Concha (Spanish seashell) collection\", false),\n (\"Puta madre (Spanish idiom) explanation\", false),\n (\"Fica (Italian fig fruit) exports\", false),\n\n // Contextual Slurs (Expanded)\n (\"Digital rectal examination needed\", false),\n (\"Spasticity in cerebral palsy\", false),\n (\"Midget submarine technology\", true),\n (\"Gyp payment systems\", true),\n (\"Retardant chemical formula\", false),\n\n // Split Evasion (Expanded)\n (\"F.u.c.k.e.r.y in progress\", true),\n (\"B-i-t-c-h please!\", true),\n (\"S H I T B R I C K S\", true),\n\n // Homophones/Near-Misses (Expanded)\n (\"Pass the Bass ale\", false),\n (\"Duck dynasty documentary\", false),\n (\"Master debater competition\", false),\n (\"Cockpit voice recorder data\", false),\n (\"Therapist ass.ociation meeting\", false),\n\n // Implicit Offense (Expanded)\n (\"That's so jewish of you\", true),\n (\"Gypsy lifestyle portrayal\", true),\n (\"Wheelchair-bound vocabulary\", true),\n (\"Tranny fluid replacement\", true), // Mechanical context but problematic\n (\"Pikey market traders\", true),\n\n // Technical Terms (New Category)\n (\"Cumulus cloud formation\", false),\n (\"Scunthorpe town council\", false),\n (\"Cumbustion engine manual\", false), // Typo but should pass\n (\"Clbuttic encoding error\", false),\n (\"Rectum measurement device\", false),\n\n // Cultural References (Expanded)\n (\"Kick the bucket list\", false),\n (\"Donkey's years since\", false),\n (\"The bee's knees cocktail\", false),\n (\"Cat got your tongue?\", false),\n (\"Bob's your uncle\", false),\n\n // Digital Contexts (New Category)\n (\"http://cunt.ly/shortener\", true),\n (\"User@analytics.com\", false),\n (\"WTF_Championship results\", true),\n (\"dickbutt.png filename\", true),\n (\"NSFW_Content_Warning\", true),\n\n // Word Boundaries (New Category)\n (\"Assassin's creed gameplay\", false),\n (\"Classicass movie review\", true), // \"classic ass\"\n (\"Butternut squash soup\", false),\n (\"Masshole driver behavior\", true), // MA + asshole\n (\"Grasshopper infestation\", false),\n\n // Multi-Language Mix (New Category)\n (\"Foda-se (Portuguese) phrasebook\", true),\n (\"Merde alors! (French)\", true),\n (\"Chingado (Spanish) cultural study\", true),\n (\"Kurwa (Polish) linguistics\", true),\n (\"Scheiße (German) dictionary\", true),\n\n // Historical Terms (New Category)\n (\"Niggardly medieval records\", false),\n (\"Spastic colony archives\", true),\n (\"Retardation in horology\", false),\n (\"Gay 90s fashion exhibit\", false),\n (\"Oriental rug cleaning\", false),\n\n // Corporate/Product Names\n (\"Buttplug.io developer tools\", true),\n (\"CumEx Financial scandal\", true),\n (\"Hitler's Poodle pub\", true),\n (\"DikFm radio station\", true),\n (\"FckngKlm apparel brand\", true),\n\n // Poetic/Literary\n (\"Wherefore art thou, Romeo?\", false),\n (\"Shakespeare's sonnet 69\", false),\n (\"Byron's dark fuckëdness\", true),\n (\"Whitman's body electric\", false),\n (\"Plath's bell jar metaphor\", false),\n\n // Youth Vernacular\n (\"That's sus cap no bussin\", false),\n (\"Lit af fam no kizzy\", false),\n (\"She's being extra salty\", false),\n (\"Ghosted his toxic ass\", true),\n (\"Daddy chill vibes only\", true)\n };\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismBreath.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 呼吸機能を提供する。\n/// \npublic class CubismBreath\n{\n /// \n /// 積算時間[秒]\n /// \n private float _currentTime;\n\n /// \n /// 呼吸にひもづいているパラメータのリスト\n /// \n public required List Parameters { get; init; }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n _currentTime += deltaTimeSeconds;\n\n var t = _currentTime * 2.0f * 3.14159f;\n\n foreach ( var item in Parameters )\n {\n model.AddParameterValue(item.ParameterId, item.Offset +\n item.Peak * MathF.Sin(t / item.Cycle), item.Weight);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismClippingContext_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic unsafe class CubismClippingContext_OpenGLES2(\n CubismClippingManager manager,\n CubismModel model,\n int* clippingDrawableIndices,\n int clipCount) : CubismClippingContext(manager, clippingDrawableIndices, clipCount) { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/AudioSegment.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record AudioSegment\n{\n public AudioSegment(Memory audioData, int sampleRate, IReadOnlyList tokens)\n {\n AudioData = audioData;\n SampleRate = sampleRate;\n Channels = 1;\n Tokens = tokens ?? Array.Empty();\n }\n\n public Guid Id { get; init; } = Guid.NewGuid();\n\n public Memory AudioData { get; set; }\n\n public int SampleRate { get; set; }\n\n public float DurationInSeconds => AudioData.Length / (float)SampleRate;\n\n public IReadOnlyList Tokens { get; }\n\n public int Channels { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/IEmotionService.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Service that tracks emotion timings for audio segments\n/// \npublic interface IEmotionService\n{\n /// \n /// Associates emotion timings with an audio segment\n /// \n void RegisterEmotions(Guid segmentId, IReadOnlyList emotions);\n\n /// \n /// Retrieves emotion timings for an audio segment\n /// \n IReadOnlyList GetEmotions(Guid segmentId);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/AudioData.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Result of audio synthesis\n/// \npublic class AudioData\n{\n public AudioData(Memory samples, ReadOnlyMemory phonemeTimings)\n {\n Samples = samples;\n PhonemeTimings = phonemeTimings;\n }\n\n /// \n /// Audio samples\n /// \n public Memory Samples { get; }\n\n /// \n /// Durations for phoneme timing\n /// \n public ReadOnlyMemory PhonemeTimings { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\npublic interface IAudioSource : IDisposable\n{\n IReadOnlyDictionary Metadata { get; }\n\n /// \n /// Gets the duration of the audio stream.\n /// \n TimeSpan Duration { get; }\n\n /// \n /// Gets the total duration of the audio stream.\n /// \n /// \n /// TotalDuration can include virtual frames that are not available in the source.\n /// \n TimeSpan TotalDuration { get; }\n\n /// \n /// Gets or sets the sample rate of the audio stream.\n /// \n uint SampleRate { get; }\n\n /// \n /// Gets the number of frames available in the stream\n /// \n /// \n /// The total number of samples in the stream is equal to the number of frames multiplied by the number of channels.\n /// \n long FramesCount { get; }\n\n /// \n /// Gets the actual number of channels in the source.\n /// \n /// \n /// Note, that the actual number of channels may be different from the number of channels in the header if the source\n /// uses an aggregation strategy.\n /// \n ushort ChannelCount { get; }\n\n /// \n /// Gets a value indicating whether the stream is initialized.\n /// \n bool IsInitialized { get; }\n\n ushort BitsPerSample { get; }\n\n /// \n /// Gets the memory slices for all the samples interleaved by channel.\n /// \n /// The frame index of the samples to get.\n /// Optional. The maximum length of the frames to get.\n /// The cancellation token to observe.\n /// \n /// \n /// The maximum length of the returned memory is * .\n /// \n Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default);\n\n /// \n /// Gets the memory slices for all the frames interleaved by channel.\n /// \n /// The frame index of the samples to get.\n /// Optional. The maximum length of the frames to get.\n /// The cancellation token to observe.\n /// \n /// \n /// The maximum length of the returned memory is * *\n /// / 8.\n /// \n Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default);\n\n Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/RouletteWheelOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record RouletteWheelOptions\n{\n // Font and Text Settings\n public string Font { get; set; } = \"DynaPuff_Condensed-Bold.ttf\";\n\n public int FontSize { get; set; } = 24;\n\n public string TextColor { get; set; } = \"#FFFFFF\";\n\n public float TextScale { get; set; } = 1f;\n\n public int TextStroke { get; set; } = 2;\n\n public bool AdaptiveText { get; set; } = true;\n\n public bool RadialTextOrientation { get; set; } = true;\n\n // Wheel Configuration\n public string[] SectionLabels { get; set; } = [];\n\n public float SpinDuration { get; set; } = 8f;\n\n public float MinRotations { get; set; } = 5f;\n\n public float WheelSizePercentage { get; set; } = 1.0f;\n\n // Viewport and Position\n public int Width { get; set; } = 1080;\n\n public int Height { get; set; } = 1080;\n\n public string PositionMode { get; set; } = \"Anchored\"; // \"Absolute\", \"Percentage\", or \"Anchored\"\n\n public string ViewportAnchor { get; set; } = \"Center\"; // One of the ViewportAnchor enum values\n\n public float PositionXPercentage { get; set; } = 0.5f;\n\n public float PositionYPercentage { get; set; } = 0.5f;\n\n public float AnchorOffsetX { get; set; } = 0f;\n\n public float AnchorOffsetY { get; set; } = 0f;\n\n public float AbsolutePositionX { get; set; } = 0f;\n\n public float AbsolutePositionY { get; set; } = 0f;\n\n // State and Animation\n public bool Enabled { get; set; } = false;\n\n public float RotationDegrees { get; set; } = 0;\n\n public bool AnimateToggle { get; set; } = true;\n\n public float AnimationDuration { get; set; } = 0.5f;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsJson.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// physics3.jsonのコンテナ。\n/// \npublic record CubismPhysicsJson\n{\n public const string Position = \"Position\";\n\n public const string X = \"X\";\n\n public const string Y = \"Y\";\n\n public const string Angle = \"Angle\";\n\n public const string Type = \"Type\";\n\n public const string Id = \"Id\";\n\n // Meta\n public const string Meta = \"Meta\";\n\n public const string EffectiveForces = \"EffectiveForces\";\n\n public const string TotalInputCount = \"TotalInputCount\";\n\n public const string TotalOutputCount = \"TotalOutputCount\";\n\n public const string PhysicsSettingCount = \"PhysicsSettingCount\";\n\n public const string Gravity = \"Gravity\";\n\n public const string Wind = \"Wind\";\n\n public const string VertexCount = \"VertexCount\";\n\n public const string Fps = \"Fps\";\n\n // PhysicsSettings\n public const string PhysicsSettings = \"PhysicsSettings\";\n\n public const string Normalization = \"Normalization\";\n\n public const string Minimum = \"Minimum\";\n\n public const string Maximum = \"Maximum\";\n\n public const string Default = \"Default\";\n\n public const string Reflect = \"Reflect\";\n\n public const string Weight = \"Weight\";\n\n // Input\n public const string Input = \"Input\";\n\n public const string Source = \"Source\";\n\n // Output\n public const string Output = \"Output\";\n\n public const string Scale = \"Scale\";\n\n public const string VertexIndex = \"VertexIndex\";\n\n public const string Destination = \"Destination\";\n\n // Particle\n public const string Vertices = \"Vertices\";\n\n public const string Mobility = \"Mobility\";\n\n public const string Delay = \"Delay\";\n\n public const string Radius = \"Radius\";\n\n public const string Acceleration = \"Acceleration\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IAwaitableAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that can be awaited for new samples and can be flushed.\n/// \npublic interface IAwaitableAudioSource : IAudioSource\n{\n bool IsFlushed { get; }\n\n /// \n /// Waits for new samples to be available.\n /// \n /// The sample count to wait for.\n /// The cancellation token.\n /// The number of times the wait was performed.\n Task WaitForInitializationAsync(CancellationToken cancellationToken);\n\n /// \n /// Waits for the source to have at least the specified number of samples.\n /// \n /// The cancellation token.\n Task WaitForNewSamplesAsync(long sampleCount, CancellationToken cancellationToken);\n\n /// \n /// Waits for the source to be at least the specified duration.\n /// \n /// The cancellation token.\n /// \n Task WaitForNewSamplesAsync(TimeSpan minimumDuration, CancellationToken cancellationToken);\n\n /// \n /// Flushes the stream, indicating that no more data will be written.\n /// \n void Flush();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/JsonContext.cs", "using System.Text.Json.Serialization;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Physics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n[JsonSourceGenerationOptions(WriteIndented = true)]\n[JsonSerializable(typeof(ModelSettingObj))]\npublic partial class ModelSettingObjContext : JsonSerializerContext { }\n\n[JsonSerializable(typeof(CubismMotionObj))]\npublic partial class CubismMotionObjContext : JsonSerializerContext { }\n\n[JsonSerializable(typeof(CubismModelUserDataObj))]\npublic partial class CubismModelUserDataObjContext : JsonSerializerContext { }\n\n[JsonSerializable(typeof(CubismPhysicsObj))]\npublic partial class CubismPhysicsObjContext : JsonSerializerContext { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Type/RectF.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Type;\n\n/// \n/// 矩形形状(座標・長さはfloat値)を定義するクラス\n/// \npublic class RectF\n{\n /// \n /// 高さ\n /// \n public float Height;\n\n /// \n /// 幅\n /// \n public float Width;\n\n /// \n /// 左端X座標\n /// \n public float X;\n\n /// \n /// 上端Y座標\n /// \n public float Y;\n\n public RectF() { }\n\n /// \n /// 引数付きコンストラクタ\n /// \n /// 左端X座標\n /// 上端Y座標\n /// 幅\n /// 高さ\n public RectF(float x, float y, float w, float h)\n {\n X = x;\n Y = y;\n Width = w;\n Height = h;\n }\n\n /// \n /// 矩形に値をセットする\n /// \n /// 矩形のインスタンス\n public void SetRect(RectF r)\n {\n X = r.X;\n Y = r.Y;\n Width = r.Width;\n Height = r.Height;\n }\n\n /// \n /// 矩形中央を軸にして縦横を拡縮する\n /// \n /// 幅方向に拡縮する量\n /// 高さ方向に拡縮する量\n public void Expand(float w, float h)\n {\n X -= w;\n Y -= h;\n Width += w * 2.0f;\n Height += h * 2.0f;\n }\n\n /// \n /// 矩形中央のX座標を取得する\n /// \n public float GetCenterX() { return X + 0.5f * Width; }\n\n /// \n /// 矩形中央のY座標を取得する\n /// \n public float GetCenterY() { return Y + 0.5f * Height; }\n\n /// \n /// 右端のX座標を取得する\n /// \n public float GetRight() { return X + Width; }\n\n /// \n /// 下端のY座標を取得する\n /// \n public float GetBottom() { return Y + Height; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/VertexPositionTexture.cs", "using System.Numerics;\nusing System.Runtime.InteropServices;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\n[StructLayout(LayoutKind.Sequential, Pack = 1)]\npublic readonly struct VertexPositionTexture\n{\n public readonly Vector3 Position;\n\n public readonly Vector2 TextureCoordinate;\n\n public VertexPositionTexture(Vector3 position, Vector2 textureCoordinate)\n {\n Position = position;\n TextureCoordinate = textureCoordinate;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/IRealtimeSpeechTranscriptor.cs", "using PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic interface IRealtimeSpeechTranscriptor\n{\n IAsyncEnumerable TranscribeAsync(IAwaitableAudioSource source, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ActiveOperation.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Data structure for active operations with progress tracking\n/// \npublic class ActiveOperation\n{\n public ActiveOperation(string id, string name)\n {\n Id = id;\n Name = name;\n Progress = 0f;\n CancellationSource = new CancellationTokenSource();\n }\n\n public string Id { get; }\n\n public string Name { get; }\n\n public float Progress { get; set; }\n\n public CancellationTokenSource CancellationSource { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/ISpeechTranscriptorFactory.cs", "namespace PersonaEngine.Lib.ASR.Transcriber;\n\n/// \n/// Factory for creating instances of .\n/// \npublic interface ISpeechTranscriptorFactory : IDisposable\n{\n /// \n /// Creates a new instance of .\n /// \n /// \n ISpeechTranscriptor Create(SpeechTranscriptorOptions options);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioFormat.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents the format of audio data.\n/// \npublic readonly struct AudioFormat\n{\n /// \n /// The number of channels in the audio.\n /// \n public readonly ushort Channels;\n\n /// \n /// The number of bits per sample.\n /// \n public readonly ushort BitsPerSample;\n\n /// \n /// The sample rate in Hz.\n /// \n public readonly uint SampleRate;\n\n /// \n /// Creates a new audio format.\n /// \n public AudioFormat(ushort channels, ushort bitsPerSample, uint sampleRate)\n {\n Channels = channels;\n BitsPerSample = bitsPerSample;\n SampleRate = sampleRate;\n }\n\n /// \n /// Gets the number of bytes per sample.\n /// \n public int BytesPerSample => BitsPerSample / 8;\n\n /// \n /// Gets the number of bytes per frame (a frame contains one sample for each channel).\n /// \n public int BytesPerFrame => BytesPerSample * Channels;\n\n /// \n /// Creates a mono format with the specified bits per sample and sample rate.\n /// \n public static AudioFormat CreateMono(ushort bitsPerSample, uint sampleRate) { return new AudioFormat(1, bitsPerSample, sampleRate); }\n\n /// \n /// Creates a stereo format with the specified bits per sample and sample rate.\n /// \n public static AudioFormat CreateStereo(ushort bitsPerSample, uint sampleRate) { return new AudioFormat(2, bitsPerSample, sampleRate); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/TtsConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record TtsConfiguration\n{\n public string ModelDirectory { get; init; } = Path.Combine(Directory.GetCurrentDirectory(), \"Resources\", \"Models\");\n\n public string EspeakPath { get; init; } = \"espeak-ng\";\n\n public KokoroVoiceOptions Voice { get; init; } = new();\n\n public RVCFilterOptions Rvc { get; init; } = new();\n}\n\npublic record KokoroVoiceOptions\n{\n public string DefaultVoice { get; init; } = \"af_heart\";\n\n public bool UseBritishEnglish { get; init; } = false;\n\n public float DefaultSpeed { get; init; } = 1.0f;\n\n public int MaxPhonemeLength { get; init; } = 510;\n\n public int SampleRate { get; init; } = 24000;\n\n public bool TrimSilence { get; init; } = false;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITtsCache.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for a TTS caching mechanism\n/// \npublic interface ITtsCache : IAsyncDisposable\n{\n /// \n /// Gets or adds an item to the cache\n /// \n /// The type of the item\n /// The cache key\n /// Factory function to create the value if not found\n /// Cancellation token\n /// The cached or newly created value\n Task GetOrAddAsync(\n string key,\n Func> valueFactory,\n CancellationToken cancellationToken = default) where T : class;\n\n /// \n /// Removes an item from the cache\n /// \n /// The cache key to remove\n void Remove(string key);\n\n /// \n /// Clears all items from the cache\n /// \n void Clear();\n\n /// \n /// Gets the current cache statistics\n /// \n /// Tuple with current stats\n (int Size, long Hits, long Misses, long Evictions) GetStatistics();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigurationChangedEventArgs.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Event arguments for configuration changes\n/// \npublic class ConfigurationChangedEventArgs : EventArgs\n{\n public enum ChangeType\n {\n Updated,\n\n Reloaded,\n\n Saved\n }\n\n public ConfigurationChangedEventArgs(string sectionKey, ChangeType type)\n {\n SectionKey = sectionKey;\n Type = type;\n }\n\n public string SectionKey { get; }\n\n public ChangeType Type { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/VisionConfig.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record VisionConfig\n{\n public string WindowTitle { get; init; } = \"Paint\";\n\n public bool Enabled { get; init; } = false;\n\n public TimeSpan CaptureInterval { get; init; } = TimeSpan.FromSeconds(45);\n\n public int CaptureMinPixels { get; init; } = 224 * 224;\n\n public int CaptureMaxPixels { get; init; } = 2048 * 2048;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/EditorStateChangedEventArgs.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Event arguments for editor state changes\n/// \npublic class EditorStateChangedEventArgs : EventArgs\n{\n public EditorStateChangedEventArgs(string stateKey, object oldValue, object newValue)\n {\n StateKey = stateKey;\n OldValue = oldValue;\n NewValue = newValue;\n }\n\n public string StateKey { get; }\n\n public object OldValue { get; }\n\n public object NewValue { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/PartData.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// パーツにまつわる諸々のデータを管理する。\n/// \npublic record PartData\n{\n /// \n /// 連動するパラメータ\n /// \n public readonly List Link = [];\n\n /// \n /// パーツID\n /// \n public required string PartId { get; set; }\n\n /// \n /// パラメータのインデックス\n /// \n public int ParameterIndex { get; set; }\n\n /// \n /// パーツのインデックス\n /// \n public int PartIndex { get; set; }\n\n /// \n /// 初期化する。\n /// \n /// 初期化に使用するモデル\n public void Initialize(CubismModel model)\n {\n ParameterIndex = model.GetParameterIndex(PartId);\n PartIndex = model.GetPartIndex(PartId);\n\n model.SetParameterValue(ParameterIndex, 1);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/SubtitleOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\n/// \n/// Configuration for the subtitle renderer\n/// \npublic class SubtitleOptions\n{\n public string Font { get; set; } = \"DynaPuff_Condensed-Bold.ttf\";\n\n public int FontSize { get; set; } = 72;\n\n public string Color { get; set; } = \"#FFFFFF\";\n\n public string HighlightColor { get; set; } = \"#4FC3F7\";\n\n public int BottomMargin { get; set; } = 50;\n\n public int SideMargin { get; set; } = 100;\n\n public float InterSegmentSpacing { get; set; } = 16f;\n\n public int MaxVisibleLines { get; set; } = 6;\n\n public float AnimationDuration { get; set; } = 0.3f;\n \n public int StrokeThickness { get; set; } = 3;\n\n public int Width { get; set; } = 1920;\n\n public int Height { get; set; } = 1080;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeResult.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Result of phoneme conversion\n/// \npublic class PhonemeResult\n{\n public PhonemeResult(string phonemes, IReadOnlyList tokens)\n {\n Phonemes = phonemes;\n Tokens = tokens;\n }\n\n /// \n /// Phoneme string representation\n /// \n public string Phonemes { get; }\n\n /// \n /// Tokens with phonetic information\n /// \n public IReadOnlyList Tokens { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/AtomicCounter.cs", "using System.Runtime.CompilerServices;\n\nnamespace PersonaEngine.Lib.Utils;\n\n/// \n/// Thread-safe counter implementation.\n/// \npublic class AtomicCounter\n{\n private uint _value;\n\n public uint GetValue() { return _value; }\n\n public uint Increment() { return (uint)Interlocked.Increment(ref Unsafe.As(ref _value)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppDefine.cs", "using PersonaEngine.Lib.Live2D.Framework;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// アプリケーションクラス。\n/// Cubism SDK の管理を行う。\n/// \npublic static class LAppDefine\n{\n // 画面\n public const float ViewScale = 1.0f;\n\n public const float ViewMaxScale = 2.0f;\n\n public const float ViewMinScale = 0.8f;\n\n public const float ViewLogicalLeft = -1.0f;\n\n public const float ViewLogicalRight = 1.0f;\n\n public const float ViewLogicalBottom = -1.0f;\n\n public const float ViewLogicalTop = -1.0f;\n\n public const float ViewLogicalMaxLeft = -2.0f;\n\n public const float ViewLogicalMaxRight = 2.0f;\n\n public const float ViewLogicalMaxBottom = -2.0f;\n\n public const float ViewLogicalMaxTop = 2.0f;\n\n // 外部定義ファイル(json)と合わせる\n public const string MotionGroupIdle = \"Idle\"; // アイドリング\n\n public const string MotionGroupTapBody = \"TapBody\"; // 体をタップしたとき\n\n // 外部定義ファイル(json)と合わせる\n public const string HitAreaNameHead = \"Head\";\n\n public const string HitAreaNameBody = \"Body\";\n\n // MOC3の整合性検証オプション\n public const bool MocConsistencyValidationEnable = true;\n\n // Frameworkから出力するログのレベル設定\n public const LogLevel CubismLoggingLevel = LogLevel.Verbose;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IKokoroVoiceProvider.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic interface IKokoroVoiceProvider : IAsyncDisposable\n{\n Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets all available voice IDs\n /// \n /// List of voice IDs\n Task> GetAvailableVoicesAsync(\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/VadDetectorOptions.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\npublic class VadDetectorOptions\n{\n public TimeSpan MinSpeechDuration { get; set; } = TimeSpan.FromMilliseconds(150);\n\n public TimeSpan MinSilenceDuration { get; set; } = TimeSpan.FromMilliseconds(150);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/IRVCVoiceProvider.cs", "namespace PersonaEngine.Lib.TTS.RVC;\n\npublic interface IRVCVoiceProvider : IAsyncDisposable\n{\n /// \n /// Gets the fullpath to the voice model\n /// \n /// Voice identifier\n /// Cancellation token\n /// Voice model path\n Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets all available voice IDs\n /// \n /// List of voice IDs\n Task> GetAvailableVoicesAsync(\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsCacheOptions.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Options for configuring the TTS memory cache behavior\n/// \npublic class TtsCacheOptions\n{\n /// \n /// Maximum number of items to store in the cache (0 = unlimited)\n /// \n public int MaxItems { get; set; } = 1000;\n\n /// \n /// Time after which cache items expire (null = never expire)\n /// \n public TimeSpan? ItemExpiration { get; set; } = TimeSpan.FromHours(1);\n\n /// \n /// Whether to collect performance metrics\n /// \n public bool CollectMetrics { get; set; } = true;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/WhisperNetSupportedLanguage.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic static class WhisperNetSupportedLanguage\n{\n private static readonly HashSet supportedLanguages = [\n \"en\", \"zh\", \"de\", \"es\", \"ru\", \"ko\", \"fr\", \"ja\", \"pt\", \"tr\", \"pl\", \"ca\", \"nl\",\n \"ar\", \"sv\", \"it\", \"id\", \"hi\", \"fi\", \"vi\", \"he\", \"uk\", \"el\", \"ms\", \"cs\", \"ro\",\n \"da\", \"hu\", \"ta\", \"no\", \"th\", \"ur\", \"hr\", \"bg\", \"lt\", \"la\", \"mi\", \"ml\", \"cy\",\n \"sk\", \"te\", \"fa\", \"lv\", \"bn\", \"sr\", \"az\", \"sl\", \"kn\", \"et\", \"mk\", \"br\", \"eu\",\n \"is\", \"hy\", \"ne\", \"mn\", \"bs\", \"kk\", \"sq\", \"sw\", \"gl\", \"mr\", \"pa\", \"si\", \"km\",\n \"sn\", \"yo\", \"so\", \"af\", \"oc\", \"ka\", \"be\", \"tg\", \"sd\", \"gu\", \"am\", \"yi\", \"lo\",\n \"uz\", \"fo\", \"ht\", \"ps\", \"tk\", \"nn\", \"mt\", \"sa\", \"lb\", \"my\", \"bo\", \"tl\", \"mg\",\n \"as\", \"tt\", \"haw\", \"ln\", \"ha\", \"ba\", \"jw\", \"su\", \"yue\"\n ];\n\n public static bool IsSupported(CultureInfo cultureInfo) { return supportedLanguages.Contains(cultureInfo.TwoLetterISOLanguageName); }\n\n public static IEnumerable GetSupportedLanguages() { return supportedLanguages.Select(x => new CultureInfo(x)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/ILive2DAnimationService.cs", "using PersonaEngine.Lib.Audio.Player;\nusing PersonaEngine.Lib.Live2D.App;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour;\n\n/// \n/// Generic interface for services that animate Live2D model parameters\n/// based on various input sources (audio, text content, emotions, etc.).\n/// \npublic interface ILive2DAnimationService : IDisposable\n{\n /// \n /// Starts the animation processing. This activates the service to\n /// begin listening for events and modifying parameters.\n /// \n void Start(LAppModel model);\n\n /// \n /// Stops the animation processing. Parameter values might be reset to neutral\n /// or held, depending on the implementation.\n /// \n void Stop();\n\n /// \n /// Updates the animation state, typically called once per frame.\n /// This method calculates and applies parameter values to the Live2D model\n /// based on the current input data and timing.\n /// \n /// The time elapsed since the last frame/update, in seconds.\n void Update(float deltaTime);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IPhonemizer.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for converting text to phonemes\n/// \npublic interface IPhonemizer : IDisposable\n{\n /// \n /// Converts text to phoneme representation\n /// \n /// Input text\n /// Cancellation token\n /// Phoneme result\n Task ToPhonemesAsync(\n string text,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IAudioSynthesizer.cs", "using PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for audio synthesis from phonemes\n/// \npublic interface IAudioSynthesizer : IAsyncDisposable\n{\n /// \n /// Synthesizes audio from phonemes\n /// \n /// Phoneme string\n /// Voice identifier\n /// Synthesis options\n /// Cancellation token\n /// Audio data with timing information\n Task SynthesizeAsync(\n string phonemes,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Option.cs", "using PersonaEngine.Lib.Live2D.Framework.Core;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// ログ出力のレベル\n/// \npublic enum LogLevel\n{\n /// \n /// 詳細ログ\n /// \n Verbose = 0,\n\n /// \n /// デバッグログ\n /// \n Debug,\n\n /// \n /// Infoログ\n /// \n Info,\n\n /// \n /// 警告ログ\n /// \n Warning,\n\n /// \n /// エラーログ\n /// \n Error,\n\n /// \n /// ログ出力無効\n /// \n Off\n}\n\n/// \n/// CubismFrameworkに設定するオプション要素を定義するクラス\n/// \npublic class Option\n{\n /// \n /// ログ出力の関数ポイ\n /// \n public required LogFunction LogFunction;\n\n /// \n /// ログ出力レベル設定\n /// \n public LogLevel LoggingLevel;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/PlayerState.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\npublic enum PlayerState\n{\n Uninitialized,\n\n Initialized,\n\n Starting,\n\n Playing,\n\n Stopping,\n\n Stopped,\n\n Error\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/OpenGLApi.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic abstract class OpenGLApi\n{\n public readonly int GL_ACTIVE_TEXTURE = 0x84E0;\n\n public readonly int GL_ARRAY_BUFFER = 0x8892;\n\n public readonly int GL_ARRAY_BUFFER_BINDING = 0x8894;\n\n public readonly int GL_BLEND = 0x0BE2;\n\n public readonly int GL_BLEND_DST_ALPHA = 0x80CA;\n\n public readonly int GL_BLEND_DST_RGB = 0x80C8;\n\n public readonly int GL_BLEND_SRC_ALPHA = 0x80CB;\n\n public readonly int GL_BLEND_SRC_RGB = 0x80C9;\n\n public readonly int GL_CCW = 0x0901;\n\n public readonly int GL_CLAMP_TO_EDGE = 0x812F;\n\n public readonly int GL_COLOR_ATTACHMENT0 = 0x8CE0;\n\n public readonly int GL_COLOR_BUFFER_BIT = 0x4000;\n\n public readonly int GL_COLOR_WRITEMASK = 0x0C23;\n\n public readonly int GL_COMPILE_STATUS = 0x8B81;\n\n public readonly int GL_CULL_FACE = 0x0B44;\n\n public readonly int GL_CURRENT_PROGRAM = 0x8B8D;\n\n public readonly int GL_DEPTH_BUFFER_BIT = 0x0100;\n\n public readonly int GL_DEPTH_TEST = 0x0B71;\n\n public readonly int GL_DST_COLOR = 0x0306;\n\n public readonly int GL_ELEMENT_ARRAY_BUFFER = 0x8893;\n\n public readonly int GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;\n\n public readonly int GL_FALSE = 0;\n\n public readonly int GL_FLOAT = 0x1406;\n\n public readonly int GL_FRAGMENT_SHADER = 0x8B30;\n\n public readonly int GL_FRAMEBUFFER = 0x8D40;\n\n public readonly int GL_FRAMEBUFFER_BINDING = 0x8CA6;\n\n public readonly int GL_FRONT_FACE = 0x0B46;\n\n public readonly int GL_INFO_LOG_LENGTH = 0x8B84;\n\n public readonly int GL_LINEAR = 0x2601;\n\n public readonly int GL_LINEAR_MIPMAP_LINEAR = 0x2703;\n\n public readonly int GL_LINK_STATUS = 0x8B82;\n\n public readonly int GL_ONE = 1;\n\n public readonly int GL_ONE_MINUS_SRC_ALPHA = 0x0303;\n\n public readonly int GL_ONE_MINUS_SRC_COLOR = 0x0301;\n\n public readonly int GL_RGBA = 0x1908;\n\n public readonly int GL_SCISSOR_TEST = 0x0C11;\n\n public readonly int GL_SRC_ALPHA = 0x0302;\n\n public readonly int GL_STATIC_DRAW = 0x88E4;\n\n public readonly int GL_STENCIL_TEST = 0x0B90;\n\n public readonly int GL_TEXTURE_2D = 0x0DE1;\n\n public readonly int GL_TEXTURE_BINDING_2D = 0x8069;\n\n public readonly int GL_TEXTURE_MAG_FILTER = 0x2800;\n\n public readonly int GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;\n\n public readonly int GL_TEXTURE_MIN_FILTER = 0x2801;\n\n public readonly int GL_TEXTURE_WRAP_S = 0x2802;\n\n public readonly int GL_TEXTURE_WRAP_T = 0x2803;\n\n public readonly int GL_TEXTURE0 = 0x84C0;\n\n public readonly int GL_TEXTURE1 = 0x84C1;\n\n public readonly int GL_TRIANGLES = 0x0004;\n\n public readonly int GL_UNSIGNED_BYTE = 0x1401;\n\n public readonly int GL_UNSIGNED_SHORT = 0x1403;\n\n public readonly int GL_VALIDATE_STATUS = 0x8B83;\n\n public readonly int GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;\n\n public readonly int GL_VERTEX_SHADER = 0x8B31;\n\n public readonly int GL_VIEWPORT = 0x0BA2;\n\n public readonly int GL_ZERO = 0;\n\n public abstract bool AlwaysClear { get; }\n\n public abstract bool IsES2 { get; }\n\n public abstract bool IsPhoneES2 { get; }\n\n public abstract void Viewport(int x, int y, int w, int h);\n\n public abstract void ClearColor(float r, float g, float b, float a);\n\n public abstract void Clear(int bit);\n\n public abstract void Enable(int bit);\n\n public abstract void Disable(int bit);\n\n public abstract void EnableVertexAttribArray(int index);\n\n public abstract void DisableVertexAttribArray(int index);\n\n public abstract void GetIntegerv(int bit, out int data);\n\n public abstract void GetIntegerv(int bit, int[] data);\n\n public abstract void ActiveTexture(int bit);\n\n public abstract void GetVertexAttribiv(int index, int bit, out int data);\n\n public abstract bool IsEnabled(int bit);\n\n public abstract void GetBooleanv(int bit, bool[] data);\n\n public abstract void UseProgram(int index);\n\n public abstract void FrontFace(int data);\n\n public abstract void ColorMask(bool a, bool b, bool c, bool d);\n\n public abstract void BindBuffer(int bit, int index);\n\n public abstract void BindTexture(int bit, int index);\n\n public abstract void BlendFuncSeparate(int a, int b, int c, int d);\n\n public abstract void DeleteProgram(int index);\n\n public abstract int GetAttribLocation(int index, string attr);\n\n public abstract int GetUniformLocation(int index, string uni);\n\n public abstract void Uniform1i(int index, int data);\n\n public abstract void VertexAttribPointer(int index, int length, int type, bool b, int size, nint arr);\n\n public abstract void Uniform4f(int index, float a, float b, float c, float d);\n\n public abstract void UniformMatrix4fv(int index, int length, bool b, float[] data);\n\n public abstract int CreateProgram();\n\n public abstract void AttachShader(int a, int b);\n\n public abstract void DeleteShader(int index);\n\n public abstract void DetachShader(int index, int data);\n\n public abstract int CreateShader(int type);\n\n public abstract void ShaderSource(int a, string source);\n\n public abstract void CompileShader(int index);\n\n public abstract unsafe void GetShaderiv(int index, int type, int* length);\n\n public abstract void GetShaderInfoLog(int index, out string log);\n\n public abstract void LinkProgram(int index);\n\n public abstract unsafe void GetProgramiv(int index, int type, int* length);\n\n public abstract void GetProgramInfoLog(int index, out string log);\n\n public abstract void ValidateProgram(int index);\n\n public abstract void DrawElements(int type, int count, int type1, nint arry);\n\n public abstract void BindVertexArrayOES(int data);\n\n public abstract void TexParameterf(int type, int type1, float value);\n\n public abstract void BindFramebuffer(int type, int data);\n\n public abstract int GenTexture();\n\n public abstract void TexImage2D(int type, int a, int type1, int w, int h, int size, int type2, int type3, IntPtr data);\n\n public abstract void TexParameteri(int a, int b, int c);\n\n public abstract int GenFramebuffer();\n\n public abstract void FramebufferTexture2D(int a, int b, int c, int buff, int data);\n\n public abstract void DeleteTexture(int data);\n\n public abstract void DeleteFramebuffer(int fb);\n\n public abstract void BlendFunc(int a, int b);\n\n public abstract void GetWindowSize(out int w, out int h);\n\n public abstract void GenerateMipmap(int a);\n\n public abstract void ClearDepthf(float data);\n\n public abstract int GetError();\n\n public abstract int GenBuffer();\n\n public abstract void BufferData(int type, int v1, nint v2, int type1);\n\n public abstract int GenVertexArray();\n\n public abstract void BindVertexArray(int vertexArray);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismDefaultParameterId.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class CubismDefaultParameterId\n{\n // パーツID\n public const string HitAreaPrefix = \"HitArea\";\n\n public const string HitAreaHead = \"Head\";\n\n public const string HitAreaBody = \"Body\";\n\n public const string PartsIdCore = \"Parts01Core\";\n\n public const string PartsArmPrefix = \"Parts01Arm_\";\n\n public const string PartsArmLPrefix = \"Parts01ArmL_\";\n\n public const string PartsArmRPrefix = \"Parts01ArmR_\";\n\n // パラメータID\n public const string ParamAngleX = \"ParamAngleX\";\n\n public const string ParamAngleY = \"ParamAngleY\";\n\n public const string ParamAngleZ = \"ParamAngleZ\";\n\n public const string ParamEyeLOpen = \"ParamEyeLOpen\";\n\n public const string ParamEyeLSmile = \"ParamEyeLSmile\";\n\n public const string ParamEyeROpen = \"ParamEyeROpen\";\n\n public const string ParamEyeRSmile = \"ParamEyeRSmile\";\n\n public const string ParamEyeBallX = \"ParamEyeBallX\";\n\n public const string ParamEyeBallY = \"ParamEyeBallY\";\n\n public const string ParamEyeBallForm = \"ParamEyeBallForm\";\n\n public const string ParamBrowLY = \"ParamBrowLY\";\n\n public const string ParamBrowRY = \"ParamBrowRY\";\n\n public const string ParamBrowLX = \"ParamBrowLX\";\n\n public const string ParamBrowRX = \"ParamBrowRX\";\n\n public const string ParamBrowLAngle = \"ParamBrowLAngle\";\n\n public const string ParamBrowRAngle = \"ParamBrowRAngle\";\n\n public const string ParamBrowLForm = \"ParamBrowLForm\";\n\n public const string ParamBrowRForm = \"ParamBrowRForm\";\n\n public const string ParamMouthForm = \"ParamMouthForm\";\n\n public const string ParamMouthOpenY = \"ParamMouthOpenY\";\n\n public const string ParamCheek = \"ParamCheek\";\n\n public const string ParamBodyAngleX = \"ParamBodyAngleX\";\n\n public const string ParamBodyAngleY = \"ParamBodyAngleY\";\n\n public const string ParamBodyAngleZ = \"ParamBodyAngleZ\";\n\n public const string ParamBreath = \"ParamBreath\";\n\n public const string ParamArmLA = \"ParamArmLA\";\n\n public const string ParamArmRA = \"ParamArmRA\";\n\n public const string ParamArmLB = \"ParamArmLB\";\n\n public const string ParamArmRB = \"ParamArmRB\";\n\n public const string ParamHandL = \"ParamHandL\";\n\n public const string ParamHandR = \"ParamHandR\";\n\n public const string ParamHairFront = \"ParamHairFront\";\n\n public const string ParamHairSide = \"ParamHairSide\";\n\n public const string ParamHairBack = \"ParamHairBack\";\n\n public const string ParamHairFluffy = \"ParamHairFluffy\";\n\n public const string ParamShoulderY = \"ParamShoulderY\";\n\n public const string ParamBustX = \"ParamBustX\";\n\n public const string ParamBustY = \"ParamBustY\";\n\n public const string ParamBaseX = \"ParamBaseX\";\n\n public const string ParamBaseY = \"ParamBaseY\";\n\n public const string ParamNONE = \"NONE\";\n\n public static readonly string ParamVoiceA = \"ParamA\";\n\n public static readonly string ParamVoiceI = \"ParamI\";\n\n public static readonly string ParamVoiceU = \"ParamU\";\n\n public static readonly string ParamVoiceE = \"ParamE\";\n\n public static readonly string ParamVoiceO = \"ParamO\";\n\n public static readonly string ParamVoiceSilence = \"ParamSilence\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionTiming.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Represents an emotion with its timestamp in the audio\n/// \npublic record EmotionTiming\n{\n /// \n /// Timestamp in seconds when the emotion occurs\n /// \n public double Timestamp { get; set; }\n \n /// \n /// Emotion emoji\n /// \n public string Emotion { get; set; } = string.Empty;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadOptions.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\npublic class SileroVadOptions(string modelPath)\n{\n public string ModelPath { get; set; } = modelPath;\n\n public float ThresholdGap { get; set; } = 0.15f;\n\n public float Threshold { get; set; } = 0.5f;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/RVCFilterOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record RVCFilterOptions\n{\n public string DefaultVoice { get; init; } = \"KasumiVA\";\n\n public bool Enabled { get; set; } = true;\n\n public int HopSize { get; set; } = 64;\n\n public int SpeakerId { get; set; } = 0;\n\n public int F0UpKey { get; set; } = 0;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/BenchmarkResult.cs", "namespace PersonaEngine.Lib.TTS.Profanity;\n\n/// \n/// Holds benchmark statistics for a profanity detection run.\n/// \npublic record BenchmarkResult\n{\n public int Total { get; set; }\n\n public int TruePositives { get; set; }\n\n public int FalsePositives { get; set; }\n\n public int TrueNegatives { get; set; }\n\n public int FalseNegatives { get; set; }\n\n public double Accuracy { get; set; }\n\n public double Precision { get; set; }\n\n public double Recall { get; set; }\n\n public override string ToString()\n {\n return $\"Total: {Total}, TP: {TruePositives}, FP: {FalsePositives}, TN: {TrueNegatives}, FN: {FalseNegatives}, \" +\n $\"Accuracy: {Accuracy:P2}, Precision: {Precision:P2}, Recall: {Recall:P2}\";\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/Live2DOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic class Live2DOptions\n{\n public string ModelPath { get; set; } = \"Resources/Live2D/Avatars\";\n\n public string ModelName { get; set; } = \"angel\";\n\n public int Width { get; set; } = 1920;\n\n public int Height { get; set; } = 1080;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/LlmOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record LlmOptions\n{\n public string TextApiKey { get; set; } = string.Empty;\n\n public string VisionApiKey { get; set; } = string.Empty;\n\n public string TextModel { get; set; } = string.Empty;\n\n public string VisionModel { get; set; } = string.Empty;\n\n public string TextEndpoint { get; set; } = string.Empty;\n\n public string VisionEndpoint { get; set; } = string.Empty;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionMarker.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Stores emotion data extracted from text with its position information\n/// \npublic record EmotionMarker\n{\n /// \n /// Character position in the cleaned text\n /// \n public int Position { get; set; }\n\n /// \n /// Emotion emoji\n /// \n public string Emotion { get; set; } = string.Empty;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/ArrayPoolConfig.cs", "namespace PersonaEngine.Lib.Utils;\n\n/// \n/// Configuration for the ArrayPools used in the library.\n/// \npublic class ArrayPoolConfig\n{\n /// \n /// Determines whether arrays should be cleared before being returned to the pool.\n /// \n /// \n /// Default value is false for performance reasons. If you are working with sensitive data, you may want to set\n /// this to true.\n /// \n public static bool ClearOnReturn { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiTheme.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// UI theme configuration data\n/// \npublic class UiTheme\n{\n public Vector4 TextColor { get; set; } = new(1.0f, 1.0f, 1.0f, 1.0f);\n\n public float WindowRounding { get; set; } = 10.0f;\n\n public float FrameRounding { get; set; } = 5.0f;\n\n public Vector2 WindowPadding { get; set; } = new(8.0f, 8.0f);\n\n public Vector2 FramePadding { get; set; } = new(5.0f, 3.5f);\n\n public Vector2 ItemSpacing { get; set; } = new(5.0f, 4.0f);\n\n // All style properties from TOML\n public float Alpha { get; set; } = 1.0f;\n\n public float DisabledAlpha { get; set; } = 0.1000000014901161f;\n\n public float WindowBorderSize { get; set; } = 0.0f;\n\n public Vector2 WindowMinSize { get; set; } = new(30.0f, 30.0f);\n\n public Vector2 WindowTitleAlign { get; set; } = new(0.5f, 0.5f);\n\n public string WindowMenuButtonPosition { get; set; } = \"Right\";\n\n public float ChildRounding { get; set; } = 5.0f;\n\n public float ChildBorderSize { get; set; } = 1.0f;\n\n public float PopupRounding { get; set; } = 10.0f;\n\n public float PopupBorderSize { get; set; } = 0.0f;\n\n public float FrameBorderSize { get; set; } = 0.0f;\n\n public Vector2 ItemInnerSpacing { get; set; } = new(5.0f, 5.0f);\n\n public Vector2 CellPadding { get; set; } = new(4.0f, 2.0f);\n\n public float IndentSpacing { get; set; } = 5.0f;\n\n public float ColumnsMinSpacing { get; set; } = 5.0f;\n\n public float ScrollbarSize { get; set; } = 15.0f;\n\n public float ScrollbarRounding { get; set; } = 9.0f;\n\n public float GrabMinSize { get; set; } = 15.0f;\n\n public float GrabRounding { get; set; } = 5.0f;\n\n public float TabRounding { get; set; } = 5.0f;\n\n public float TabBorderSize { get; set; } = 0.0f;\n\n public float TabCloseButtonMinWidthSelected { get; set; } = 0.0f;\n\n public float TabCloseButtonMinWidthUnselected { get; set; } = 0.0f;\n\n public string ColorButtonPosition { get; set; } = \"Right\";\n\n public Vector2 ButtonTextAlign { get; set; } = new(0.5f, 0.5f);\n\n public Vector2 SelectableTextAlign { get; set; } = new(0.0f, 0.0f);\n\n // All colors from TOML\n public Vector4 TextDisabledColor { get; set; } = new(1.0f, 1.0f, 1.0f, 0.3605149984359741f);\n\n public Vector4 WindowBgColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 ChildBgColor { get; set; } = new(1.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 PopupBgColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 BorderColor { get; set; } = new(0.424f, 0.380f, 0.573f, 0.54935622215271f);\n\n public Vector4 BorderShadowColor { get; set; } = new(0.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 FrameBgColor { get; set; } = new(0.157f, 0.157f, 0.157f, 1.0f);\n\n public Vector4 FrameBgHoveredColor { get; set; } = new(0.380f, 0.424f, 0.573f, 0.5490196347236633f);\n\n public Vector4 FrameBgActiveColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 TitleBgColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 TitleBgActiveColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 TitleBgCollapsedColor { get; set; } = new(0.259f, 0.259f, 0.259f, 0.0f);\n\n public Vector4 MenuBarBgColor { get; set; } = new(0.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 ScrollbarBgColor { get; set; } = new(0.157f, 0.157f, 0.157f, 0.0f);\n\n public Vector4 ScrollbarGrabColor { get; set; } = new(0.157f, 0.157f, 0.157f, 1.0f);\n\n public Vector4 ScrollbarGrabHoveredColor { get; set; } = new(0.235f, 0.235f, 0.235f, 1.0f);\n\n public Vector4 ScrollbarGrabActiveColor { get; set; } = new(0.294f, 0.294f, 0.294f, 1.0f);\n\n public Vector4 CheckMarkColor { get; set; } = new(0.294f, 0.294f, 0.294f, 1.0f);\n\n public Vector4 SliderGrabColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 SliderGrabActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 ButtonColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 ButtonHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 ButtonActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 HeaderColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 HeaderHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 HeaderActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 SeparatorColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 SeparatorHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 SeparatorActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 ResizeGripColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 ResizeGripHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 ResizeGripActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 TabColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 TabHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 TabActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 TabUnfocusedColor { get; set; } = new(0.0f, 0.451f, 1.0f, 0.0f);\n\n public Vector4 TabUnfocusedActiveColor { get; set; } = new(0.133f, 0.259f, 0.424f, 0.0f);\n\n public Vector4 PlotLinesColor { get; set; } = new(0.294f, 0.294f, 0.294f, 1.0f);\n\n public Vector4 PlotLinesHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 PlotHistogramColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 PlotHistogramHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 TableHeaderBgColor { get; set; } = new(0.188f, 0.188f, 0.200f, 1.0f);\n\n public Vector4 TableBorderStrongColor { get; set; } = new(0.424f, 0.380f, 0.573f, 0.5490196347236633f);\n\n public Vector4 TableBorderLightColor { get; set; } = new(0.424f, 0.380f, 0.573f, 0.2918455004692078f);\n\n public Vector4 TableRowBgColor { get; set; } = new(0.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 TableRowBgAltColor { get; set; } = new(1.0f, 1.0f, 1.0f, 0.03433477878570557f);\n\n public Vector4 TextSelectedBgColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 DragDropTargetColor { get; set; } = new(1.0f, 1.0f, 0.0f, 0.8999999761581421f);\n\n public Vector4 NavWindowingHighlightColor { get; set; } = new(1.0f, 1.0f, 1.0f, 0.699999988079071f);\n\n public Vector4 NavWindowingDimBgColor { get; set; } = new(0.8f, 0.8f, 0.8f, 0.2000000029802322f);\n\n public Vector4 ModalWindowDimBgColor { get; set; } = new(0.8f, 0.8f, 0.8f, 0.3499999940395355f);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/WindowConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic class WindowConfiguration\n{\n public int Width { get; set; } = 1920;\n\n public int Height { get; set; } = 1080;\n\n public string Title { get; set; } = \"Avatar Application\";\n\n public bool Fullscreen { get; set; } = false;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/IVadDetector.cs", "using PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\n/// \n/// Represents a voice activity detection component that can detect voice activity segments in mono-channel audio\n/// samples at 16 kHz.\n/// \npublic interface IVadDetector\n{\n /// \n /// Detects voice activity segments in the given audio source.\n /// \n /// The audio source to analyze.\n /// The cancellation token to observe.\n IAsyncEnumerable DetectSegmentsAsync(IAudioSource source, CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionMarkerInfo.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\ninternal record EmotionMarkerInfo\n{\n public required string MarkerId { get; init; }\n\n public required string Emotion { get; init; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeContext.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemeContext\n{\n public bool UseBritishEnglish { get; set; }\n\n public bool? NextStartsWithVowel { get; set; }\n\n public bool HasToToken { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/MicrophoneConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record MicrophoneConfiguration\n{\n /// \n /// The friendly name of the desired input device.\n /// If null, empty, or whitespace, the default device (DeviceNumber 0) will be used.\n /// \n public string? DeviceName { get; init; } = null;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IVBANPacketBuilder.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Builder for VBAN packets.\n/// \npublic interface IVBANPacketBuilder\n{\n /// \n /// Builds a VBAN packet from audio data.\n /// \n byte[] BuildPacket(ReadOnlyMemory audioData, int sampleRate, int samplesPerChannel, int channels);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IAudioFilter.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic interface IAudioFilter\n{\n int Priority { get; }\n\n void Process(AudioSegment audioSegment);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Vision/IVisualQAService.cs", "namespace PersonaEngine.Lib.Vision;\n\npublic interface IVisualQAService : IAsyncDisposable\n{\n string? ScreenCaption { get; }\n\n Task StartAsync(CancellationToken cancellationToken = default);\n\n Task StopAsync();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/PartColorData.cs", "using PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// テクスチャの色をRGBAで扱うための構造体\n/// \npublic record PartColorData\n{\n public CubismTextureColor Color = new();\n\n public bool IsOverwritten { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/DrawableColorData.cs", "using PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// テクスチャの色をRGBAで扱うための構造体\n/// \npublic record DrawableColorData\n{\n public CubismTextureColor Color = new();\n\n public bool IsOverwritten { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IModelProvider.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for model loading and management\n/// \npublic interface IModelProvider : IAsyncDisposable\n{\n /// \n /// Gets a model by type\n /// \n /// Type of model\n /// Cancellation token\n /// Model resource\n Task GetModelAsync(\n ModelType modelType,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Logging/ResilienceKeys.cs", "using Microsoft.Extensions.Logging;\n\nusing Polly;\n\nnamespace PersonaEngine.Lib.Logging;\n\npublic static class ResilienceKeys\n{\n public static readonly ResiliencePropertyKey SessionId = new(\"session-id\");\n \n public static readonly ResiliencePropertyKey Logger = new(\"logger\");\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroConstants.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroConstants\n{\n public const int BatchSize = 512;\n\n public const int ContextSize = 64;\n\n public const int StateSize = 256;\n\n public const int OutputSize = 1;\n\n public const int SampleRate = 16000;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ISentenceSegmenter.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for sentence segmentation\n/// \npublic interface ISentenceSegmenter\n{\n /// \n /// Splits text into sentences\n /// \n /// Input text\n /// List of sentences\n IReadOnlyList Segment(string text);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PosToken.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Token with part-of-speech information\n/// \npublic class PosToken\n{\n /// \n /// The text of the token\n /// \n public string Text { get; set; } = string.Empty;\n\n /// \n /// Part of speech tag\n /// \n public string? PartOfSpeech { get; set; }\n\n /// \n /// Whitespace after this token\n /// \n public bool IsWhitespace { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IMemoryBackedAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\npublic interface IMemoryBackedAudioSource\n{\n public bool StoresFloats { get; }\n\n public bool StoresBytes { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ILexicon.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for phoneme lexicon lookup\n/// \npublic interface ILexicon\n{\n public (string? Phonemes, int? Rating) ProcessToken(Token token, TokenContext ctx);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigurationSaveException.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Exception thrown when saving configuration fails\n/// \npublic class ConfigurationSaveException : Exception\n{\n public ConfigurationSaveException(string message) : base(message) { }\n\n public ConfigurationSaveException(string message, Exception innerException) : base(message, innerException) { }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/DrawableCullingData.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// テクスチャのカリング設定を管理するための構造体\n/// \npublic record DrawableCullingData\n{\n public bool IsOverwritten { get; set; }\n\n public bool IsCulling { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IMicrophone.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Interface for a microphone audio source.\n/// Extends IAwaitableAudioSource with recording control methods\n/// and device information retrieval.\n/// \npublic interface IMicrophone : IAwaitableAudioSource\n{\n /// \n /// Starts capturing audio from the microphone.\n /// \n void StartRecording();\n\n /// \n /// Stops capturing audio from the microphone.\n /// \n void StopRecording();\n\n /// \n /// Gets a list of available audio input device names.\n /// \n /// An enumerable collection of device names.\n IEnumerable GetAvailableDevices();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioSourceHeader.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Details of the audio source header.\n/// \npublic class AudioSourceHeader\n{\n /// \n /// Gets the number of channels in the current wave file.\n /// \n public ushort Channels { get; set; }\n\n /// \n /// Gets the Sample Rate in the current wave file.\n /// \n public uint SampleRate { get; set; }\n\n /// \n /// Gets the Bits Per Sample in the current wave file.\n /// \n public ushort BitsPerSample { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IPosTagger.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for part-of-speech tagging\n/// \npublic interface IPosTagger : IDisposable\n{\n /// \n /// Tags parts of speech in text\n /// \n Task> TagAsync(string text, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IAudioTransport.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Defines methods for transporting audio data over a network.\n/// \npublic interface IAudioTransport : IAsyncDisposable\n{\n /// \n /// Initializes the transport.\n /// \n Task InitializeAsync();\n\n /// \n /// Sends an audio packet over the transport.\n /// \n /// Audio data to send.\n /// Sample rate of the audio.\n /// Number of samples per channel.\n /// Number of audio channels.\n /// Cancellation token.\n Task SendAudioPacketAsync(\n ReadOnlyMemory audioData,\n int sampleRate,\n int samplesPerChannel,\n int channels,\n CancellationToken cancellationToken);\n\n Task FlushAsync(CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IUiConfigurationManager.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages configuration loading, saving, and access\n/// \npublic interface IUiConfigurationManager\n{\n event EventHandler ConfigurationChanged;\n\n T GetConfiguration(string sectionKey = null);\n\n void UpdateConfiguration(T configuration, string? sectionKey = null);\n\n void SaveConfiguration();\n\n void ReloadConfiguration();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/TextureInfo.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 画像情報構造体\n/// \npublic record TextureInfo\n{\n /// \n /// ファイル名\n /// \n public required string FileName;\n\n /// \n /// 高さ\n /// \n public int Height;\n\n /// \n /// テクスチャID\n /// \n public int ID;\n\n /// \n /// 横幅\n /// \n public int Width;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismShaderSet.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal record CubismShaderSet\n{\n /// \n /// シェーダプログラムに渡す変数のアドレス(Position)\n /// \n internal int AttributePositionLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(TexCoord)\n /// \n internal int AttributeTexCoordLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(Texture0)\n /// \n internal int SamplerTexture0Location;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(Texture1)\n /// \n internal int SamplerTexture1Location;\n\n /// \n /// シェーダプログラムのアドレス\n /// \n internal int ShaderProgram;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(BaseColor)\n /// \n internal int UniformBaseColorLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(ClipMatrix)\n /// \n internal int UniformClipMatrixLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(Matrix)\n /// \n internal int UniformMatrixLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(MultiplyColor)\n /// \n internal int UniformMultiplyColorLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(ScreenColor)\n /// \n internal int UniformScreenColorLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(ChannelFlag)\n /// \n internal int UnifromChannelFlagLocation;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/TranscriptToken.cs", "namespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic class TranscriptToken\n{\n /// \n /// The logaritmic confidence of the token.\n /// \n public float? ConfidenceLog;\n\n /// \n /// The text representation of the token.\n /// \n public string? Text;\n\n /// \n /// The unique identifier for the token for transcriptors that uses IDs\n /// \n /// \n /// The type is object to allow for different types of IDs based on the transcriptor, this ID is not used inside\n /// EchoSharp library.\n /// \n public object? Id { get; set; }\n\n /// \n /// The confidence of the token.\n /// \n public float? Confidence { get; set; }\n\n /// \n /// The confidence of the timestamp of the token.\n /// \n public float TimestampConfidence { get; set; }\n\n /// \n /// The timestamp confidence sum of the token.\n /// \n public float TimestampConfidenceSum { get; set; }\n\n /// \n /// The start time of the token.\n /// \n public TimeSpan StartTime { get; set; }\n\n /// \n /// The duration of the token.\n /// \n public TimeSpan Duration { get; set; }\n\n /// \n /// Dynamic Time Warping timestamp of the token.\n /// \n public long DtwTimestamp { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppPal.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// プラットフォーム依存機能を抽象化する Cubism Platform Abstraction Layer.\n/// ファイル読み込みや時刻取得等のプラットフォームに依存する関数をまとめる\n/// \npublic static class LAppPal\n{\n /// \n /// デルタ時間(前回フレームとの差分)を取得する\n /// \n /// デルタ時間[ms]\n public static float DeltaTime { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITextProcessor.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for text preprocessing\n/// \npublic interface ITextProcessor\n{\n /// \n /// Processes raw text for TTS synthesis\n /// \n /// Input text\n /// Cancellation token\n /// Processed text with sentences\n Task ProcessAsync(string text, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/SpoutConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record SpoutConfiguration\n{\n public required string OutputName { get; init; }\n\n public required int Width { get; init; }\n\n public required int Height { get; init; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserDataNode.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// Jsonから読み込んだユーザデータを記録しておくための構造体\n/// \npublic record CubismModelUserDataNode\n{\n /// \n /// ユーザデータターゲットタイプ\n /// \n public required string TargetType { get; set; }\n\n /// \n /// ユーザデータターゲットのID\n /// \n public required string TargetId { get; set; }\n\n /// \n /// ユーザデータ\n /// \n public required string Value { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IUiThemeManager.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages UI theme settings\n/// \npublic interface IUiThemeManager\n{\n void ApplyTheme();\n\n void SetTheme(UiTheme theme);\n\n UiTheme GetCurrentTheme();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IConfigSectionRegistry.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages registration and access to configuration sections\n/// \npublic interface IConfigSectionRegistry\n{\n void RegisterSection(IConfigSectionEditor section);\n\n void UnregisterSection(string sectionKey);\n\n IConfigSectionEditor GetSection(string sectionKey);\n\n IReadOnlyList GetSections();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/BreathParameterData.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 呼吸のパラメータ情報。\n/// \npublic record BreathParameterData\n{\n /// \n /// 呼吸をひもづけるパラメータIDs\n /// \n public required string ParameterId { get; set; }\n\n /// \n /// 呼吸を正弦波としたときの、波のオフセット\n /// \n public float Offset { get; set; }\n\n /// \n /// 呼吸を正弦波としたときの、波の高さ\n /// \n public float Peak { get; set; }\n\n /// \n /// 呼吸を正弦波としたときの、波の周期\n /// \n public float Cycle { get; set; }\n\n /// \n /// パラメータへの重み\n /// \n public float Weight { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/AudioException.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\npublic class AudioException(string message, Exception? innerException = null) : Exception(message, innerException);\n\npublic class AudioDeviceNotFoundException(string message) : Exception(message);\n\npublic class AudioPlayerInitializationException(string message, Exception? innerException = null) : Exception(message, innerException);"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismCdiJson.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic class CubismCdiJson\n{\n public const string Version = \"Version\";\n\n public const string Parameters = \"Parameters\";\n\n public const string ParameterGroups = \"ParameterGroups\";\n\n public const string Parts = \"Parts\";\n\n public const string Id = \"Id\";\n\n public const string GroupId = \"GroupId\";\n\n public const string Name = \"Name\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IEditorStateManager.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages the state of the configuration editor UI\n/// \npublic interface IEditorStateManager\n{\n bool HasUnsavedChanges { get; }\n\n event EventHandler StateChanged;\n\n void MarkAsChanged(string? sectionKey = null);\n\n void MarkAsSaved();\n\n ActiveOperation? GetActiveOperation();\n\n void RegisterActiveOperation(ActiveOperation operation);\n\n void ClearActiveOperation(string operationId);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/SDKInfo.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class SDKInfo\n{\n public const string Version = \"Cubism 5 SDK for Native R1\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IPlaybackController.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Interface for controlling audio playback scheduling and timing.\n/// \npublic interface IPlaybackController : IDisposable\n{\n /// \n /// Gets the current playback time in seconds.\n /// \n float CurrentTime { get; }\n\n /// \n /// Gets the total number of samples that have been scheduled for playback.\n /// \n long TotalSamplesPlayed { get; }\n\n /// \n /// Gets the current latency in milliseconds.\n /// \n double CurrentLatencyMs { get; }\n\n /// \n /// Gets whether latency information is available.\n /// \n bool HasLatencyInformation { get; }\n\n /// \n /// Event raised when playback time changes significantly.\n /// \n event EventHandler TimeChanged;\n\n /// \n /// Event raised when latency changes significantly.\n /// \n event EventHandler LatencyChanged;\n\n /// \n /// Resets the controller to its initial state.\n /// \n void Reset();\n\n /// \n /// Updates the latency information.\n /// \n /// The latency in milliseconds.\n void UpdateLatency(double latencyMs);\n\n /// \n /// Schedules a packet of audio data for playback.\n /// \n /// The number of samples per channel in the packet.\n /// The sample rate of the audio data.\n /// A token to monitor for cancellation requests.\n /// \n /// A task that completes when the packet is scheduled, with a boolean indicating whether the packet should be\n /// sent.\n /// \n Task SchedulePlaybackAsync(int samplesPerChannel, int sampleRate, CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/IStartupTask.cs", "using Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\npublic interface IStartupTask\n{\n void Execute(GL gl);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IMlSentenceDetector.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for ML-based sentence detection\n/// \npublic interface IMlSentenceDetector : IDisposable\n{\n /// \n /// Detects sentences in text\n /// \n IReadOnlyList Detect(string text);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ModelType.cs", "using System.ComponentModel;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Types of models\n/// \npublic enum ModelType\n{\n [Description(\"kokoro/model_slim.onnx\")]\n KokoroSynthesis,\n\n [Description(\"kokoro/voices\")] KokoroVoices,\n\n [Description(\"kokoro/phoneme_to_id.txt\")]\n KokoroPhonemeMappings,\n\n [Description(\"opennlp\")] OpenNLPDir,\n\n [Description(\"rvc/voices\")] RVCVoices,\n\n [Description(\"rvc/vec-768-layer-12.onnx\")]\n RVCHubert,\n\n [Description(\"rvc/crepe_tiny.onnx\")] RVCCrepeTiny\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IDiscardableAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents a source that can discard frames from the beginning of the audio stream if they are no longer needed.\n/// \npublic interface IDiscardableAudioSource : IAudioSource\n{\n /// \n /// Discards a specified number of frames.\n /// \n /// The number of frames to discard.\n void DiscardFrames(int count);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IConfigSectionEditor.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Interface for configuration section editors\n/// \npublic interface IConfigSectionEditor\n{\n string SectionKey { get; }\n\n string DisplayName { get; }\n\n bool HasUnsavedChanges { get; }\n\n void Initialize();\n\n void Render();\n\n void RenderMenuItems();\n\n void Update(float deltaTime);\n\n void OnConfigurationChanged(ConfigurationChangedEventArgs args);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/INotificationService.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Provides notification services for the UI\n/// \npublic interface INotificationService\n{\n void ShowInfo(string message, Action? action = null, string actionLabel = \"OK\");\n\n void ShowSuccess(string message, Action? action = null, string actionLabel = \"OK\");\n\n void ShowWarning(string message, Action? action = null, string actionLabel = \"OK\");\n\n void ShowError(string message, Action? action = null, string actionLabel = \"OK\");\n\n IReadOnlyList GetActiveNotifications();\n\n void Update(float deltaTime);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismBlendMode.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// カラーブレンディングのモード\n/// \npublic enum CubismBlendMode\n{\n /// \n /// 通常\n /// \n Normal = 0,\n\n /// \n /// 加算\n /// \n Additive = 1,\n\n /// \n /// 乗算\n /// \n Multiplicative = 2,\n\n /// \n /// マスク\n /// \n Mask = 3\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/ILive2DModel.cs", "namespace PersonaEngine.Lib.Live2D;\n\npublic interface ILive2DModel : IDisposable\n{\n string ModelId { get; }\n\n void SetParameter(string paramName, float value);\n\n void Update(float deltaTime);\n\n void Draw();\n\n void SetPosition(float x, float y);\n\n void SetScale(float scale);\n\n void SetRotation(float rotation);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/IF0Predictor.cs", "namespace PersonaEngine.Lib.TTS.RVC;\n\npublic interface IF0Predictor : IDisposable\n{\n void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/EyeState.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\npublic enum EyeState\n{\n /// \n /// 初期状態\n /// \n First = 0,\n\n /// \n /// まばたきしていない状態\n /// \n Interval,\n\n /// \n /// まぶたが閉じていく途中の状態\n /// \n Closing,\n\n /// \n /// まぶたが閉じている状態\n /// \n Closed,\n\n /// \n /// まぶたが開いていく途中の状態\n /// \n Opening\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/SimplePhonemeEntry.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record SimplePhonemeEntry(string Phoneme) : PhonemeEntry;"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITextNormalizer.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for text normalization\n/// \npublic interface ITextNormalizer\n{\n /// \n /// Normalizes text for TTS synthesis\n /// \n /// Input text\n /// Normalized text\n string Normalize(string text);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanitySeverity.cs", "namespace PersonaEngine.Lib.TTS.Profanity;\n\n/// \n/// Represents the severity level of profanity.\n/// \npublic enum ProfanitySeverity\n{\n Clean, // No profanity detected.\n\n Mild, // Some profanity detected.\n\n Moderate, // Moderate profanity detected.\n\n Severe // High level of profanity detected.\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/RenderType.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic enum RenderType\n{\n OpenGL\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/ICubismAllocator.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// メモリアロケーションを抽象化したクラス.\n/// メモリ確保・解放処理をプラットフォーム側で実装して\n/// フレームワークから呼び出すためのインターフェース。\n/// \npublic interface ICubismAllocator\n{\n /// \n /// アラインメント制約なしのヒープ・メモリーを確保します。\n /// \n /// 確保するバイト数\n /// 成功すると割り当てられたメモリのアドレス。 そうでなければ '0'を返す。\n IntPtr Allocate(int size);\n\n /// \n /// アラインメント制約なしのヒープ・メモリーを解放します。\n /// \n /// 解放するメモリのアドレス\n void Deallocate(IntPtr memory);\n\n /// \n /// アラインメント制約ありのヒープ・メモリーを確保します。\n /// \n /// 確保するバイト数\n /// メモリーブロックのアラインメント幅\n /// 成功すると割り当てられたメモリのアドレス。 そうでなければ '0'を返す。\n IntPtr AllocateAligned(int size, int alignment);\n\n /// \n /// アラインメント制約ありのヒープ・メモリーを解放します。\n /// \n /// 解放するメモリのアドレス\n void DeallocateAligned(IntPtr alignedMemory);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/WheelStoppedEventHandler.cs", "namespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic delegate void WheelStoppedEventHandler(string selectedOption);"]], "task_instance_info": {"created_time": "2025-08-20 19:11:55", "created_task_model": "DeepSeek-R1", "function_skeleton": "public bool ShouldAllowBargeIn (BargeInContext context) {}", "code_description": "This code segment functions to: Evaluate input processing events by comparing word count metrics from transcript data against a predefined minimum threshold to determine interruption eligibility during dialog interactions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public bool ShouldAllowBargeIn(BargeInContext context)\n {\n // Split current segment text into words and count them\n var words = context.CurrentSegmentText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n \n // Only allow barge-in if minimum word threshold is met\n return words.Length >= context.MinWordsThreshold;\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-12-19"}, "editdistance_info": {"edit_distance": 21.2598, "calculate_time": "2025-08-20 19:12:19", "true_code_clean": "public bool ShouldAllowBargeIn(BargeInContext context)\n {\n switch ( context.InputEvent )\n {\n case SttSegmentRecognizing segmentRecognizing:\n {\n var wordCount = segmentRecognizing.PartialTranscript.GetWordCount();\n return wordCount >= context.ConversationOptions.BargeInMinWords;\n }\n case SttSegmentRecognized segmentRecognized:\n {\n var wordCount = segmentRecognized.FinalTranscript.GetWordCount();\n return wordCount >= context.ConversationOptions.BargeInMinWords;\n }\n default:\n return false;\n }\n }", "predict_code_clean": "public bool ShouldAllowBargeIn(BargeInContext context)\n {\n var words = context.CurrentSegmentText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n return words.Length >= context.MinWordsThreshold;\n }"}} {"repo_name": "handcrafted-persona-engine", "file_name": "/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/MicrophoneConfigEditor.cs", "inference_info": {"prefix_code": "using System.Diagnostics;\nusing System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for Microphone section configuration.\n/// Allows selection of the audio input device.\n/// \npublic class MicrophoneConfigEditor : ConfigSectionEditorBase\n{\n private const string DefaultDeviceDisplayName = \"(Default Device)\"; // Display name for null/empty device\n\n // --- Dependencies ---\n private readonly IMicrophone _microphone; // Dependency to get device list\n\n private List _availableDevices = new();\n\n // --- State ---\n private MicrophoneConfiguration _currentConfig;\n\n private bool _loadingDevices = false;\n\n private string? _selectedDeviceName; // Can be null for default device\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The configuration manager.\n /// The editor state manager.\n /// The microphone service.\n public MicrophoneConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IMicrophone microphone)\n : base(configManager, stateManager)\n {\n _microphone = microphone ?? throw new ArgumentNullException(nameof(microphone));\n\n // Load initial configuration\n LoadConfiguration();\n }\n\n // --- ConfigSectionEditorBase Implementation ---\n\n /// \n /// Gets the key for the configuration section managed by this editor.\n /// \n public override string SectionKey => \"Microphone\"; // Or your specific key\n\n /// \n /// Gets the display name for this editor section.\n /// \n public override string DisplayName => \"Microphone Settings\";\n\n /// \n /// Initializes the editor, loading necessary data like available devices.\n /// \n public override void Initialize()\n {\n LoadAvailableDevices(); // Load devices on initialization\n }\n\n /// \n /// Renders the ImGui UI for the microphone configuration.\n /// \n ", "suffix_code": "\n\n /// \n /// Updates the editor state (currently unused for this simple editor).\n /// \n /// Time elapsed since the last frame.\n public override void Update(float deltaTime)\n {\n // No per-frame update logic needed for this editor yet\n }\n\n /// \n /// Handles configuration changes, reloading if necessary.\n /// \n /// Event arguments containing change details.\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args); // Call base implementation\n\n // Reload configuration if the source indicates a full reload\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n // Optionally reload devices if the config might affect them,\n // though usually device list is independent of config.\n // LoadAvailableDevices();\n }\n }\n\n /// \n /// Disposes resources used by the editor (currently none specific).\n /// \n public override void Dispose()\n {\n // Unsubscribe from events if any were added\n base.Dispose(); // Call base implementation\n }\n\n // --- Configuration Management ---\n\n /// \n /// Loads the microphone configuration from the configuration manager.\n /// \n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(SectionKey)\n ?? new MicrophoneConfiguration(); // Get or create default\n\n // Update local state from loaded config\n _selectedDeviceName = _currentConfig.DeviceName;\n\n // Ensure the UI reflects the loaded state without marking as changed initially\n MarkAsSaved(); // Reset change tracking after loading\n }\n\n /// \n /// Fetches the list of available microphone devices.\n /// \n private void LoadAvailableDevices()\n {\n if ( _loadingDevices )\n {\n return; // Prevent concurrent loading\n }\n\n try\n {\n _loadingDevices = true;\n // Consider adding an ActiveOperation to StateManager if this takes time\n // var operation = new ActiveOperation(\"load-mic-devices\", \"Loading Microphones\");\n // StateManager.RegisterActiveOperation(operation);\n\n // Get devices using the injected service\n _availableDevices = _microphone.GetAvailableDevices().ToList();\n\n // Ensure the currently selected device still exists\n if ( !string.IsNullOrEmpty(_selectedDeviceName) &&\n !_availableDevices.Contains(_selectedDeviceName) )\n {\n Debug.WriteLine($\"Warning: Configured microphone '{_selectedDeviceName}' not found. Reverting to default.\");\n // Optionally notify the user here\n _selectedDeviceName = null; // Revert to default\n UpdateConfiguration(); // Update the config state\n }\n\n // StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading microphone devices: {ex.Message}\");\n _availableDevices = new List(); // Clear list on error\n // Optionally show an error message to the user via ImGui or logging\n }\n finally\n {\n _loadingDevices = false;\n }\n }\n\n /// \n /// Updates the configuration object and notifies the manager.\n /// \n private void UpdateConfiguration()\n {\n // Create the updated configuration record\n var updatedConfig = _currentConfig with // Use record 'with' expression\n {\n DeviceName = _selectedDeviceName\n };\n\n // Check if the configuration actually changed before updating\n if ( !_currentConfig.Equals(updatedConfig) )\n {\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(_currentConfig, SectionKey);\n MarkAsChanged(); // Mark that there are unsaved changes\n }\n }\n\n /// \n /// Saves the current configuration changes.\n /// \n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved(); // Mark changes as saved\n }\n\n /// \n /// Resets the microphone configuration to default values.\n /// \n private void ResetToDefaults()\n {\n var defaultConfig = new MicrophoneConfiguration(); // Create default config\n\n // Update local state\n _selectedDeviceName = defaultConfig.DeviceName; // Should be null\n\n // Update configuration only if it differs from current\n if ( !_currentConfig.Equals(defaultConfig) )\n {\n _currentConfig = defaultConfig;\n ConfigManager.UpdateConfiguration(_currentConfig, SectionKey);\n MarkAsChanged(); // Mark changes needing save\n }\n else\n {\n // If already default, just ensure saved state is correct\n MarkAsSaved();\n }\n }\n}", "middle_code": "public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n ImGui.Spacing();\n ImGui.SeparatorText(\"Input Device Selection\");\n ImGui.Spacing();\n ImGui.BeginGroup(); \n {\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Input Device:\");\n ImGui.SameLine(120); \n ImGui.SetNextItemWidth(availWidth - 120 - 100); \n var currentSelectionDisplay = string.IsNullOrEmpty(_selectedDeviceName)\n ? DefaultDeviceDisplayName\n : _selectedDeviceName;\n if ( _loadingDevices )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading devices...\";\n ImGui.InputText(\"##DeviceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n if ( ImGui.BeginCombo(\"##DeviceSelector\", currentSelectionDisplay) )\n {\n var isDefaultSelected = string.IsNullOrEmpty(_selectedDeviceName);\n if ( ImGui.Selectable(DefaultDeviceDisplayName, isDefaultSelected) )\n {\n if ( _selectedDeviceName != null ) \n {\n _selectedDeviceName = null;\n UpdateConfiguration();\n }\n }\n if ( isDefaultSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n if ( _availableDevices.Count == 0 && !_loadingDevices )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No input devices found.\");\n }\n else\n {\n foreach ( var device in _availableDevices )\n {\n var isSelected = device == _selectedDeviceName;\n if ( ImGui.Selectable(device, isSelected) )\n {\n if ( _selectedDeviceName != device ) \n {\n _selectedDeviceName = device;\n UpdateConfiguration();\n }\n }\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n ImGui.EndCombo();\n }\n }\n ImGui.SameLine(0, 10); \n if ( ImGui.Button(\"Refresh##Dev\", new Vector2(80, 0)) ) \n {\n LoadAvailableDevices();\n }\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh the list of available input devices.\");\n }\n }\n ImGui.EndGroup(); \n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n float buttonWidth = 150;\n var totalButtonWidth = buttonWidth * 2 + 10; \n var initialPadding = (availWidth - totalButtonWidth) * 0.5f;\n if ( initialPadding < 0 )\n {\n initialPadding = 0;\n }\n ImGui.SetCursorPosX(initialPadding);\n if ( ImGui.Button(\"Reset\", new Vector2(buttonWidth, 0)) )\n {\n ResetToDefaults();\n }\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset microphone settings to default values.\");\n }\n ImGui.SameLine(0, 10); \n var hasChanges = StateManager.HasUnsavedChanges; \n if ( !hasChanges )\n {\n ImGui.BeginDisabled();\n }\n if ( ImGui.Button(\"Save\", new Vector2(buttonWidth, 0)) )\n {\n SaveConfiguration();\n }\n if ( ImGui.IsItemHovered() && hasChanges )\n {\n ImGui.SetTooltip(\"Save the current microphone settings.\");\n }\n if ( !hasChanges )\n {\n ImGui.EndDisabled();\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/TtsConfigEditor.cs", "using System.Diagnostics;\nusing System.Numerics;\nusing System.Threading.Channels;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets.Dialogs;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.RVC;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for TTS section configuration\n/// \npublic class TtsConfigEditor : ConfigSectionEditorBase\n{\n private readonly IAudioOutputAdapter _audioPlayer;\n\n private readonly IRVCVoiceProvider _rvcProvider;\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly ITtsEngine _ttsEngine;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private List _availableRVCs = new();\n\n private List _availableVoices = new();\n\n private TtsConfiguration _currentConfig;\n\n private RVCFilterOptions _currentRvcFilterOptions;\n\n private KokoroVoiceOptions _currentVoiceOptions;\n\n private string _defaultRVC;\n\n private string _defaultVoice;\n\n private string _espeakPath;\n\n private bool _isPlaying = false;\n\n private bool _loadingRvcs = false;\n\n private bool _loadingVoices = false;\n\n private int _maxPhonemeLength;\n\n private string _modelDir;\n\n private ActiveOperation? _playbackOperation = null;\n\n private bool _rvcEnabled;\n\n private int _rvcF0UpKey;\n\n private int _rvcHopSize;\n\n private int _sampleRate;\n\n private float _speechRate;\n\n private string _testText = \"This is a test of the text-to-speech system.\";\n\n private bool _trimSilence;\n\n private bool _useBritishEnglish;\n\n public TtsConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n ITtsEngine ttsEngine,\n IOutputAdapter audioPlayer,\n IKokoroVoiceProvider voiceProvider,\n IUiThemeManager themeManager, IRVCVoiceProvider rvcProvider)\n : base(configManager, stateManager)\n {\n _ttsEngine = ttsEngine;\n _audioPlayer = (IAudioOutputAdapter)audioPlayer;\n _voiceProvider = voiceProvider;\n _themeManager = themeManager;\n _rvcProvider = rvcProvider;\n\n LoadConfiguration();\n\n // _audioPlayerHost.OnPlaybackStarted += OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted += OnPlaybackCompleted;\n }\n\n public override string SectionKey => \"TTS\";\n\n public override string DisplayName => \"TTS Configuration\";\n\n public override void Initialize()\n {\n // Load available voices\n LoadAvailableVoicesAsync();\n LoadAvailableRVCAsync();\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Main layout with tabs for different sections\n if ( ImGui.BeginTabBar(\"TtsConfigTabs\") )\n {\n // Basic settings tab\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettings();\n\n ImGui.EndTabItem();\n }\n\n // Advanced settings tab\n if ( ImGui.BeginTabItem(\"Advanced Settings\") )\n {\n RenderAdvancedSettings();\n ImGui.EndTabItem();\n }\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n // Reset button at bottom\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all TTS settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n public override void Update(float deltaTime)\n {\n // Simplified update just for playback operation\n if ( _playbackOperation != null && _isPlaying )\n {\n _playbackOperation.Progress += deltaTime * 0.1f;\n if ( _playbackOperation.Progress > 0.99f )\n {\n _playbackOperation.Progress = 0.99f;\n }\n }\n }\n\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args);\n\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n }\n }\n\n public override void Dispose()\n {\n // Unsubscribe from audio player events\n // _audioPlayerHost.OnPlaybackStarted -= OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted -= OnPlaybackCompleted;\n\n // Cancel any active playback\n StopPlayback();\n\n base.Dispose();\n }\n\n #region Configuration Management\n\n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(\"TTS\");\n _currentVoiceOptions = _currentConfig.Voice;\n _currentRvcFilterOptions = _currentConfig.Rvc;\n\n // Update local fields from configuration\n _modelDir = _currentConfig.ModelDirectory;\n _espeakPath = _currentConfig.EspeakPath;\n _speechRate = _currentVoiceOptions.DefaultSpeed;\n _sampleRate = _currentVoiceOptions.SampleRate;\n _trimSilence = _currentVoiceOptions.TrimSilence;\n _useBritishEnglish = _currentVoiceOptions.UseBritishEnglish;\n _defaultVoice = _currentVoiceOptions.DefaultVoice;\n _maxPhonemeLength = _currentVoiceOptions.MaxPhonemeLength;\n\n // RVC\n _defaultRVC = _currentRvcFilterOptions.DefaultVoice;\n _rvcEnabled = _currentRvcFilterOptions.Enabled;\n _rvcHopSize = _currentRvcFilterOptions.HopSize;\n _rvcF0UpKey = _currentRvcFilterOptions.F0UpKey;\n }\n\n private async void LoadAvailableVoicesAsync()\n {\n try\n {\n _loadingVoices = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-voices\", \"Loading Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _voiceProvider.GetAvailableVoicesAsync();\n _availableVoices = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableVoices = [];\n }\n finally\n {\n _loadingVoices = false;\n }\n }\n\n private async void LoadAvailableRVCAsync()\n {\n try\n {\n _loadingRvcs = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-rvc\", \"Loading RVC Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _rvcProvider.GetAvailableVoicesAsync();\n _availableRVCs = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableRVCs = [];\n }\n finally\n {\n _loadingRvcs = false;\n }\n }\n\n private void UpdateConfiguration()\n {\n var updatedVoiceOptions = new KokoroVoiceOptions {\n DefaultVoice = _defaultVoice,\n DefaultSpeed = _speechRate,\n SampleRate = _sampleRate,\n TrimSilence = _trimSilence,\n UseBritishEnglish = _useBritishEnglish,\n MaxPhonemeLength = _maxPhonemeLength\n };\n\n var updatedRVCOptions = new RVCFilterOptions { DefaultVoice = _defaultRVC, Enabled = _rvcEnabled, HopSize = _rvcHopSize, F0UpKey = _rvcF0UpKey };\n\n var updatedConfig = new TtsConfiguration { ModelDirectory = _modelDir, EspeakPath = _espeakPath, Voice = updatedVoiceOptions, Rvc = updatedRVCOptions };\n\n _currentRvcFilterOptions = updatedRVCOptions;\n _currentVoiceOptions = updatedVoiceOptions;\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(updatedConfig, SectionKey);\n\n MarkAsChanged();\n }\n\n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved();\n }\n\n private void ResetToDefaults()\n {\n // Create default configuration\n var defaultVoiceOptions = new KokoroVoiceOptions();\n var defaultConfig = new TtsConfiguration();\n\n // Update local state\n _currentVoiceOptions = defaultVoiceOptions;\n _currentConfig = defaultConfig;\n\n // Update UI fields\n _modelDir = defaultConfig.ModelDirectory;\n _espeakPath = defaultConfig.EspeakPath;\n _speechRate = defaultVoiceOptions.DefaultSpeed;\n _sampleRate = defaultVoiceOptions.SampleRate;\n _trimSilence = defaultVoiceOptions.TrimSilence;\n _useBritishEnglish = defaultVoiceOptions.UseBritishEnglish;\n _defaultVoice = defaultVoiceOptions.DefaultVoice;\n _maxPhonemeLength = defaultVoiceOptions.MaxPhonemeLength;\n\n // Update configuration\n ConfigManager.UpdateConfiguration(defaultConfig, \"TTS\");\n MarkAsChanged();\n }\n\n #endregion\n\n #region Playback Controls\n\n private async void StartPlayback()\n {\n if ( _isPlaying || string.IsNullOrWhiteSpace(_testText) )\n {\n return;\n }\n\n try\n {\n // Create a new playback operation\n _playbackOperation = new ActiveOperation(\"tts-playback\", \"Playing TTS\");\n StateManager.RegisterActiveOperation(_playbackOperation);\n\n _isPlaying = true;\n\n var options = _currentVoiceOptions;\n\n var llmInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var ttsOutput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioEvents = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); // Tts Started/Tts Ended - Audio Started/Audio Ended\n\n await llmInput.Writer.WriteAsync(new LlmChunkEvent(Guid.Empty, Guid.Empty, DateTimeOffset.UtcNow, _testText), _playbackOperation.CancellationSource.Token);\n llmInput.Writer.Complete();\n\n _ = Task.Run(async () =>\n {\n await foreach(var ttsOut in ttsOutput.Reader.ReadAllAsync(_playbackOperation.CancellationSource.Token))\n {\n if ( ttsOut is TtsChunkEvent ttsChunk )\n {\n await audioInput.Writer.WriteAsync(ttsChunk, _playbackOperation.CancellationSource.Token);\n }\n }\n });\n\n _ = _ttsEngine.SynthesizeStreamingAsync(\n llmInput,\n ttsOutput,\n Guid.Empty,\n Guid.Empty,\n options,\n _playbackOperation.CancellationSource.Token\n );\n\n await _audioPlayer.SendAsync(audioInput, audioEvents, Guid.Empty, _playbackOperation.CancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"TTS playback cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during TTS playback: {ex.Message}\");\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n }\n\n private void StopPlayback()\n {\n if ( _playbackOperation != null )\n {\n _playbackOperation.CancellationSource.Cancel();\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n\n _isPlaying = false;\n }\n\n private void OnPlaybackStarted(object sender, EventArgs args)\n {\n _isPlaying = true;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 0.0f;\n }\n }\n\n private void OnPlaybackCompleted(object sender, EventArgs args)\n {\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 1.0f;\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n\n #endregion\n\n #region UI Rendering Methods\n\n private void RenderTestingSection()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Playground\");\n ImGui.Spacing();\n\n // Text input frame with light background\n ImGui.Text(\"Test Text:\");\n ImGui.SetNextItemWidth(availWidth);\n ImGui.InputTextMultiline(\"##TestText\", ref _testText, 1000, new Vector2(0, 80));\n\n ImGui.Spacing();\n ImGui.Spacing();\n\n // Controls section with better layout\n ImGui.BeginGroup();\n {\n // Left side: Example selector\n var controlWidth = Math.Min(180, availWidth * 0.4f);\n ImGui.SetNextItemWidth(controlWidth);\n\n if ( ImGui.BeginCombo(\"##exampleLbl\", \"Select Example\") )\n {\n string[] examples = { \"Hello, world!\", \"The quick brown fox jumps over the lazy dog.\", \"Welcome to the text-to-speech system.\", \"How are you doing today?\", \"Today's date is March 3rd, 2025.\" };\n\n foreach ( var example in examples )\n {\n var isSelected = _testText == example;\n if ( ImGui.Selectable(example, ref isSelected) )\n {\n _testText = example;\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.SameLine(0, 15);\n\n var clearDisabled = string.IsNullOrEmpty(_testText);\n if ( clearDisabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( ImGui.Button(\"Clear\", new Vector2(80, 0)) && !string.IsNullOrEmpty(_testText) )\n {\n _testText = \"\";\n }\n\n if ( clearDisabled )\n {\n ImGui.EndDisabled();\n }\n }\n\n ImGui.EndGroup();\n\n ImGui.SameLine(0, 10);\n\n // Playback controls in a styled frame\n {\n // Play/Stop button with color styling\n if ( _isPlaying )\n {\n if ( UiStyler.AnimatedButton(\"Stop\", new Vector2(80, 0), _isPlaying) )\n {\n StopPlayback();\n }\n\n ImGui.SameLine(0, 15);\n ImGui.ProgressBar(_playbackOperation?.Progress ?? 0, new Vector2(-1, 0), \"Playing\");\n }\n else\n {\n var disabled = string.IsNullOrWhiteSpace(_testText);\n if ( disabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( UiStyler.AnimatedButton(\"Play\", new Vector2(80, 0), _isPlaying) )\n {\n StartPlayback();\n }\n\n if ( disabled )\n {\n ImGui.EndDisabled();\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Enter some text to play\");\n }\n }\n }\n }\n }\n\n private void RenderBasicSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // === Voice Selection Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Voice Settings\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingVoices )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading voices...\";\n ImGui.InputText(\"##VoiceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n if ( ImGui.BeginCombo(\"##VoiceSelector\", string.IsNullOrEmpty(_defaultVoice) ? \"\" : _defaultRVC) )\n {\n if ( _availableRVCs.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No voices available\");\n }\n else\n {\n foreach ( var voice in _availableRVCs )\n {\n var isSelected = voice == _defaultRVC;\n if ( ImGui.Selectable(voice, isSelected) )\n {\n _defaultRVC = voice;\n UpdateConfiguration();\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh##RefreshRVC\", new Vector2(-1, 0)) )\n {\n LoadAvailableRVCAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available voices list\");\n }\n\n if ( ImGui.BeginTable(\"RVCProps\", 4, ImGuiTableFlags.SizingFixedFit) )\n {\n ImGui.TableSetupColumn(\"1\", 100f);\n ImGui.TableSetupColumn(\"2\", 200f);\n ImGui.TableSetupColumn(\"3\", 100f);\n ImGui.TableSetupColumn(\"4\", 200f);\n\n // Hop Size\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Hop Size\");\n ImGui.TableNextColumn();\n var fontSizeChanged = ImGui.InputInt(\"##HopSize\", ref _rvcHopSize, 8);\n if ( fontSizeChanged )\n {\n _rvcHopSize = Math.Clamp(_rvcHopSize, 8, 256);\n rvcConfigChanged = true;\n }\n\n // F0 Key\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Pitch\");\n ImGui.TableNextColumn();\n var pitchChanged = ImGui.InputInt(\"##Pitch\", ref _rvcF0UpKey, 1);\n if ( pitchChanged )\n {\n _rvcF0UpKey = Math.Clamp(_rvcF0UpKey, -20, 20);\n rvcConfigChanged = true;\n }\n\n ImGui.EndTable();\n }\n\n if ( !_rvcEnabled )\n {\n ImGui.EndDisabled();\n }\n\n if ( rvcConfigChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n private void RenderAdvancedSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Section header\n ImGui.Spacing();\n ImGui.SeparatorText(\"Advanced TTS Settings\");\n ImGui.Spacing();\n\n var sampleRateChanged = false;\n var phonemeChanged = false;\n\n // ImGui.BeginDisabled();\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Sample Rate:\");\n ImGui.SameLine(200);\n\n string[] sampleRates = [\"16000 Hz (Low quality)\", \"24000 Hz (Standard quality)\", \"32000 Hz (Good quality)\", \"44100 Hz (High quality)\", \"48000 Hz (Studio quality)\"];\n int[] rateValues = [16000, 24000, 32000, 44100, 48000];\n\n var currentIdx = Array.IndexOf(rateValues, _sampleRate);\n if ( currentIdx < 0 )\n {\n currentIdx = 1; // Default to 24000 Hz\n }\n\n ImGui.SetNextItemWidth(availWidth - 200);\n\n if ( ImGui.BeginCombo(\"##SampleRate\", sampleRates[currentIdx]) )\n {\n for ( var i = 0; i < sampleRates.Length; i++ )\n {\n var isSelected = i == currentIdx;\n if ( ImGui.Selectable(sampleRates[i], isSelected) )\n {\n _sampleRate = rateValues[i];\n sampleRateChanged = true;\n }\n\n // Show additional info on hover\n if ( ImGui.IsItemHovered() )\n {\n var tooltipText = i switch {\n 0 => \"Low quality, minimal resource usage\",\n 1 => \"Standard quality, recommended for most uses\",\n 2 => \"Good quality, balanced resource usage\",\n 3 => \"High quality, CD audio standard\",\n 4 => \"Studio quality, higher resource usage\",\n _ => \"\"\n };\n\n ImGui.SetTooltip(tooltipText);\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.EndDisabled();\n }\n\n ImGui.EndGroup();\n\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Max Phoneme Length:\");\n ImGui.SameLine(200);\n\n ImGui.SetNextItemWidth(120);\n phonemeChanged = ImGui.InputInt(\"##MaxPhonemeLength\", ref _maxPhonemeLength);\n ImGui.EndDisabled();\n\n // Clamp value to valid range\n if ( phonemeChanged )\n {\n var oldValue = _maxPhonemeLength;\n _maxPhonemeLength = Math.Clamp(_maxPhonemeLength, 1, 2048);\n\n if ( oldValue != _maxPhonemeLength )\n {\n ImGui.TextColored(new Vector4(1.0f, 0.7f, 0.3f, 1.0f),\n \"Value clamped to valid range (1-2048)\");\n }\n }\n\n // Helper text\n ImGui.Spacing();\n ImGui.TextWrapped(\"This is already setup correctly to work with Kokoro. Shouldn't have to change!\");\n\n // === Paths & Resources Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Paths & Resources\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n // Model directory\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Model Directory:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var modelDirChanged = ImGui.InputText(\"##ModelDir\", ref _modelDir, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##ModelDir\", new Vector2(-1, 0)) )\n {\n var fileDialog = new OpenFolderDialog(_modelDir);\n fileDialog.Show();\n if ( fileDialog.SelectedFolder != null )\n {\n _modelDir = fileDialog.SelectedFolder;\n modelDirChanged = true;\n }\n }\n\n // Espeak path\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Espeak Path:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var espeakPathChanged = ImGui.InputText(\"##EspeakPath\", ref _espeakPath, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##EspeakPath\", new Vector2(-1, 0)) )\n {\n // In a real app, this would open a file browser dialog\n Console.WriteLine(\"Open file browser for Espeak Path\");\n }\n\n // Apply changes if needed\n if ( modelDirChanged || espeakPathChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n ImGui.EndGroup();\n\n if ( sampleRateChanged || phonemeChanged )\n {\n UpdateConfiguration();\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/RouletteWheelEditor.cs", "using System.Diagnostics;\nusing System.Drawing;\nusing System.Numerics;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class RouletteWheelEditor : ConfigSectionEditorBase\n{\n private readonly string[] _anchorOptions = { \"TopLeft\", \"TopCenter\", \"TopRight\", \"MiddleLeft\", \"MiddleCenter\", \"MiddleRight\", \"BottomLeft\", \"BottomCenter\", \"BottomRight\" };\n\n private readonly FontProvider _fontProvider;\n\n private readonly string[] _positionOptions = { \"Center\", \"Custom Position\", \"Anchor Position\" };\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly RouletteWheel.RouletteWheel _wheel;\n\n private bool _animateToggle;\n\n private float _animationDuration;\n\n private List _availableFonts = new();\n\n private RouletteWheelOptions _currentConfig;\n\n private bool _defaultEnabled;\n\n private string _fontName;\n\n private int _fontSize;\n\n private int _height;\n\n private bool _loadingFonts = false;\n\n private float _minRotations;\n\n private string _newSectionLabel = string.Empty;\n\n private bool _radialTextOrientation = true;\n\n private float _rotationDegrees;\n\n private string[] _sectionLabels;\n\n private int _selectedAnchor = 4;\n\n private int _selectedPositionOption = 0;\n\n private int _selectedSection = 0;\n\n private float _spinDuration;\n\n private ActiveOperation? _spinningOperation = null;\n\n private int _strokeWidth;\n\n private string _textColor;\n\n private float _textScale;\n\n private bool _useAdaptiveSize = true;\n\n private int _width;\n\n private float _xPosition = 0.5f;\n\n private float _yPosition = 0.5f;\n\n public RouletteWheelEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IUiThemeManager themeManager,\n RouletteWheel.RouletteWheel wheel,\n FontProvider fontProvider)\n : base(configManager, stateManager)\n {\n _wheel = wheel;\n _themeManager = themeManager;\n _fontProvider = fontProvider;\n\n _currentConfig = ConfigManager.GetConfiguration(\"RouletteWheel\");\n LoadConfiguration(_currentConfig);\n }\n\n public override string SectionKey => \"Roulette\";\n\n public override string DisplayName => \"Roulette Configuration\";\n\n public override void Initialize() { LoadAvailableFontsAsync(); }\n\n private async void Spin(int? targetSection = null)\n {\n if ( _wheel.IsSpinning )\n {\n return;\n }\n\n try\n {\n _spinningOperation = new ActiveOperation(\"wheel-spinning\", \"Spinning Wheel\");\n StateManager.RegisterActiveOperation(_spinningOperation);\n await _wheel.SpinAsync(targetSection);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"Spinning cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during spinning: {ex.Message}\");\n\n if ( _spinningOperation != null )\n {\n StateManager.ClearActiveOperation(_spinningOperation.Id);\n _spinningOperation = null;\n }\n }\n }\n\n private async void LoadAvailableFontsAsync()\n {\n try\n {\n _loadingFonts = true;\n\n var operation = new ActiveOperation(\"load-fonts\", \"Loading Fonts\");\n StateManager.RegisterActiveOperation(operation);\n\n var fonts = await _fontProvider.GetAvailableFontsAsync();\n _availableFonts = fonts.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading fonts: {ex.Message}\");\n _availableFonts = [];\n }\n finally\n {\n _loadingFonts = false;\n }\n }\n\n private void LoadConfiguration(RouletteWheelOptions config)\n {\n _width = config.Width;\n _height = config.Height;\n _fontName = config.Font;\n _fontSize = config.FontSize;\n _textScale = config.TextScale;\n _textColor = config.TextColor;\n _strokeWidth = config.TextStroke;\n _useAdaptiveSize = config.AdaptiveText;\n _radialTextOrientation = config.RadialTextOrientation;\n _sectionLabels = config.SectionLabels;\n _spinDuration = config.SpinDuration;\n _minRotations = config.MinRotations;\n _animateToggle = config.AnimateToggle;\n _animationDuration = config.AnimationDuration;\n _defaultEnabled = config.Enabled;\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n if ( ImGui.BeginTabBar(\"RouletteConfigTabs\") )\n {\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettingsTab();\n RenderSectionsTab();\n RenderBehaviorTab();\n RenderStyleTab();\n\n ImGui.EndTabItem();\n }\n\n RenderPositioningTab();\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all Wheel settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n private void RenderBasicSettingsTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n bool widthChanged,\n heightChanged;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Wheel Dimensions\");\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(125);\n widthChanged = ImGui.InputInt(\"Width##WheelWidth\", ref _width, 10);\n if ( widthChanged )\n {\n _width = Math.Max(50, _width); // Minimum width\n }\n\n ImGui.SameLine();\n\n ImGui.SetCursorPosX(availWidth - 175);\n if ( ImGui.Button(\"Equal Dimensions\", new Vector2(175, 0)) )\n {\n var size = Math.Max(_width, _height);\n _width = _height = size;\n _wheel.SetDiameter(size);\n widthChanged = true;\n heightChanged = true;\n }\n\n ImGui.SetNextItemWidth(125);\n heightChanged = ImGui.InputInt(\"Height##WheelHeight\", ref _height, 10);\n if ( heightChanged )\n {\n _height = Math.Max(50, _height); // Minimum height\n }\n\n if ( widthChanged || heightChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderSectionsTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n var sectionsChanged = false;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Wheel Sections\");\n ImGui.Spacing();\n\n if ( _sectionLabels.Length > 0 )\n {\n ImGui.BeginChild(\"SectionsList\", new Vector2(0, 0), ImGuiChildFlags.AutoResizeY);\n\n for ( var i = 0; i < _sectionLabels.Length; i++ )\n {\n ImGui.PushID(i);\n\n var tempLabel = _sectionLabels[i];\n ImGui.SetNextItemWidth(availWidth - 10 - 30);\n if ( ImGui.InputText(\"##SectionLabel\", ref tempLabel, 128) )\n {\n _sectionLabels[i] = tempLabel;\n sectionsChanged = true;\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"X##RemoveSection\" + i, new Vector2(30, 0)) )\n {\n var newLabels = new string[_sectionLabels.Length - 1];\n Array.Copy(_sectionLabels, 0, newLabels, 0, i);\n Array.Copy(_sectionLabels, i + 1, newLabels, i, _sectionLabels.Length - i - 1);\n _sectionLabels = newLabels;\n sectionsChanged = true;\n }\n\n ImGui.PopID();\n }\n\n ImGui.EndChild();\n }\n else\n {\n TextHelper.TextCenteredH(\"No sections defined. Add your first section below.\");\n }\n\n // Add new section\n ImGui.Spacing();\n // ImGui.Separator();\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(availWidth - 80 - 10);\n ImGui.InputText(\"##NewSectionLabel\", ref _newSectionLabel, 128);\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Add\", new Vector2(80, 0)) && !string.IsNullOrWhiteSpace(_newSectionLabel) )\n {\n // Add the new section\n var newLabels = new string[(_sectionLabels?.Length ?? 0) + 1];\n if ( _sectionLabels is { Length: > 0 } )\n {\n Array.Copy(_sectionLabels, newLabels, _sectionLabels.Length);\n }\n\n newLabels[^1] = _newSectionLabel;\n _sectionLabels = newLabels;\n _newSectionLabel = string.Empty;\n sectionsChanged = true;\n }\n\n if ( sectionsChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderStyleTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n var configChanged = false;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Text Appearance\");\n ImGui.Spacing();\n\n // Font selection with refresh button\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingFonts )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading fonts...\";\n ImGui.InputText(\"##Font\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n var fontChanged = false;\n if ( ImGui.BeginCombo(\"##Font\", string.IsNullOrEmpty(_fontName) ? \"\" : _defaultVoice) )\n {\n if ( _availableVoices.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No voices available\");\n }\n else\n {\n foreach ( var voice in _availableVoices )\n {\n var isSelected = voice == _defaultVoice;\n if ( ImGui.Selectable(voice, isSelected) )\n {\n _defaultVoice = voice;\n UpdateConfiguration();\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh##VoiceRefresh\", new Vector2(-1, 0)) )\n {\n LoadAvailableVoicesAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available voices list\");\n }\n\n // Speech rate slider with better styling\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Speech Rate:\");\n ImGui.SameLine(120);\n\n ImGui.SetNextItemWidth(availWidth - 120 - 120);\n var rateChanged = ImGui.SliderFloat(\"##SpeechRate\", ref _speechRate, 0.5f, 2.0f, \"%.2f\");\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Reset##Rate\", new Vector2(-1, 0)) )\n {\n _speechRate = 1.0f;\n rateChanged = true;\n }\n\n // Voice options with checkboxes in a consistent layout\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Options:\");\n ImGui.SameLine(120);\n\n // Trim silence\n var trimChanged = ImGui.Checkbox(\"Trim Silence\", ref _trimSilence);\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Remove silence from beginning and end of speech\");\n }\n\n ImGui.SameLine(0, 50);\n\n // British English\n var britishChanged = ImGui.Checkbox(\"Use British English\", ref _useBritishEnglish);\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Use British English pronunciation instead of American English\");\n }\n\n // Apply changes if needed\n if ( rateChanged || trimChanged || britishChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n\n // === RVC Selection Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"RVC Settings\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n var rvcConfigChanged = ImGui.Checkbox(\"Enable Voice Change\", ref _rvcEnabled);\n\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( !_rvcEnabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( _loadingVoices )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading voices...\";\n ImGui.InputText(\"##RVCLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n if ( ImGui.BeginCombo(\"##RVCSelector\", string.IsNullOrEmpty(_defaultRVC) ? \"\" : _fontName) )\n {\n if ( _availableFonts.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No fonts available\");\n }\n else\n {\n foreach ( var font in _availableFonts )\n {\n var isSelected = font == _fontName;\n if ( ImGui.Selectable(font, isSelected) )\n {\n _fontName = font;\n fontChanged = true;\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n\n configChanged |= fontChanged;\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh\", new Vector2(-1, 0)) )\n {\n LoadAvailableFontsAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available fonts list\");\n }\n }\n\n ImGui.Spacing();\n\n // ImGui.SetCursorPosX((availWidth - 110f - 200f - 110f - 200f) * .5f);\n // Create a 2-column table for consistent alignment\n if ( ImGui.BeginTable(\"StyleProperties\", 4, ImGuiTableFlags.SizingFixedFit) )\n {\n ImGui.TableSetupColumn(\"1\", 110f);\n ImGui.TableSetupColumn(\"2\", 200f);\n ImGui.TableSetupColumn(\"3\", 120f);\n ImGui.TableSetupColumn(\"4\", 220f);\n\n // Font Size\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Font Size\");\n ImGui.TableNextColumn();\n var fontSizeChanged = ImGui.InputInt(\"##FontSize\", ref _fontSize, 1);\n if ( fontSizeChanged )\n {\n _fontSize = Math.Clamp(_fontSize, 1, 72);\n configChanged = true;\n }\n\n // Text Scale\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Scale\");\n ImGui.TableNextColumn();\n var scaleChanged = ImGui.SliderFloat(\"##Scale\", ref _textScale, 0.5f, 2.0f, \"%.1f\");\n configChanged |= scaleChanged;\n\n // Text Color\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Color\");\n ImGui.TableNextColumn();\n var color = ColorTranslator.FromHtml(_textColor);\n var colorVec = new Vector4(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f);\n var colorChanged = ImGui.ColorEdit4(\"##Color\", ref colorVec, ImGuiColorEditFlags.DisplayHex);\n if ( colorChanged )\n {\n _textColor = $\"#{(int)(colorVec.W * 255):X2}{(int)(colorVec.X * 255):X2}{(int)(colorVec.Y * 255):X2}{(int)(colorVec.Z * 255):X2}\";\n configChanged = true;\n }\n\n // Stroke Width\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Stroke Width\");\n ImGui.TableNextColumn();\n var strokeChanged = ImGui.InputInt(\"##StrokeWidth\", ref _strokeWidth, 1);\n if ( strokeChanged )\n {\n _strokeWidth = Math.Clamp(_strokeWidth, 0, 5);\n configChanged = true;\n }\n\n ImGui.EndTable();\n }\n\n ImGui.Spacing();\n\n // Checkbox options in two columns\n var checkboxWidth = availWidth / 2 - 10;\n var adaptSizeChanged = ImGui.Checkbox(\"Adaptive Size\", ref _useAdaptiveSize);\n ImGui.SameLine(checkboxWidth + 43);\n var radialOrienChanged = ImGui.Checkbox(\"Radial Orientation\", ref _radialTextOrientation);\n\n configChanged |= adaptSizeChanged | radialOrienChanged;\n\n // Apply configuration changes if needed\n if ( configChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderPositioningTab()\n {\n if ( ImGui.BeginTabItem(\"Position & Rotation\") )\n {\n ImGui.Text(\"Wheel Position\");\n ImGui.Separator();\n\n // Position method selector\n ImGui.Combo(\"Position Method\", ref _selectedPositionOption, _positionOptions, _positionOptions.Length);\n\n ImGui.Spacing();\n\n // Different UI based on position method\n switch ( _selectedPositionOption )\n {\n case 0: // Center\n if ( ImGui.Button(\"Center in Viewport\", new Vector2(200, 0)) )\n {\n _wheel.CenterInViewport();\n }\n\n break;\n\n case 1: // Custom Position\n ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X * 0.4f);\n ImGui.SliderFloat(\"X Position %\", ref _xPosition, 0.0f, 1.0f, \"%.2f\");\n\n ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X * 0.4f);\n ImGui.SliderFloat(\"Y Position %\", ref _yPosition, 0.0f, 1.0f, \"%.2f\");\n\n if ( ImGui.Button(\"Apply Position\", new Vector2(200, 0)) )\n {\n _wheel.PositionByPercentage(_xPosition, _yPosition);\n }\n\n break;\n\n case 2: // Anchor Position\n ImGui.Combo(\"Anchor Point\", ref _selectedAnchor, _anchorOptions, _anchorOptions.Length);\n\n if ( ImGui.Button(\"Apply Anchor\", new Vector2(200, 0)) )\n {\n // This would need a conversion from index to the actual ViewportAnchor enum\n // For now, just showing the concept\n // _wheel.PositionAt((ViewportAnchor)_selectedAnchor, new Vector2(0, 0));\n\n // Simple implementation for demo purposes:\n switch ( _selectedAnchor )\n {\n case 0:\n _wheel.PositionByPercentage(0.0f, 0.0f);\n\n break; // TopLeft\n case 1:\n _wheel.PositionByPercentage(0.5f, 0.0f);\n\n break; // TopCenter\n case 2:\n _wheel.PositionByPercentage(1.0f, 0.0f);\n\n break; // TopRight\n case 3:\n _wheel.PositionByPercentage(0.0f, 0.5f);\n\n break; // MiddleLeft\n case 4:\n _wheel.PositionByPercentage(0.5f, 0.5f);\n\n break; // MiddleCenter\n case 5:\n _wheel.PositionByPercentage(1.0f, 0.5f);\n\n break; // MiddleRight\n case 6:\n _wheel.PositionByPercentage(0.0f, 1.0f);\n\n break; // BottomLeft\n case 7:\n _wheel.PositionByPercentage(0.5f, 1.0f);\n\n break; // BottomCenter\n case 8:\n _wheel.PositionByPercentage(1.0f, 1.0f);\n\n break; // BottomRight\n }\n }\n\n break;\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Text(\"Wheel Rotation\");\n\n // Display current rotation\n ImGui.Text($\"Current Rotation: {_rotationDegrees:F1}°\");\n\n // Rotation slider\n ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X * 0.7f);\n if ( ImGui.SliderFloat(\"Rotation (degrees)\", ref _rotationDegrees, 0.0f, 360.0f, \"%.1f°\") )\n {\n _wheel.RotateByDegrees(_rotationDegrees - _wheel.RotationDegrees);\n }\n\n // Quick rotation buttons\n if ( ImGui.Button(\"+45°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(45);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"+90°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(90);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"-45°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(-45);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"-90°\", new Vector2(60, 0)) )\n {\n _wheel.RotateByDegrees(-90);\n _rotationDegrees = _wheel.RotationDegrees;\n }\n\n ImGui.EndTabItem();\n }\n }\n\n private void RenderBehaviorTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Spin Configuration\");\n ImGui.Spacing();\n\n // Spin duration\n ImGui.SetNextItemWidth(125);\n var spinDurationChanged = ImGui.SliderFloat(\"Spin Duration (sec)\", ref _spinDuration, 1.0f, 10.0f, \"%.1f\");\n\n // Min rotations\n ImGui.SetNextItemWidth(125);\n var minRotChanged = ImGui.SliderFloat(\"Min Rotations\", ref _minRotations, 1.0f, 10.0f, \"%.0f\");\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Animation Settings\");\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(125);\n var aniDurChanged = ImGui.SliderFloat(\"Animation Duration (sec)\", ref _animationDuration, 0.1f, 2.0f, \"%.1f\");\n\n ImGui.SameLine();\n ImGui.SetCursorPosX(availWidth - 200);\n\n // Animation toggle\n ImGui.SetNextItemWidth(200);\n var aniShowHideChanged = ImGui.Checkbox(\"Animate Show/Hide\", ref _animateToggle);\n\n ImGui.SetCursorPosX(availWidth - 200);\n\n ImGui.SetNextItemWidth(200);\n var defaultEnabledChanged = ImGui.Checkbox(\"Default Enabled\", ref _defaultEnabled);\n\n if ( spinDurationChanged || minRotChanged || aniDurChanged || aniShowHideChanged || defaultEnabledChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderTestingSection()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Playground\");\n ImGui.Spacing();\n\n if ( _sectionLabels.Length > 0 )\n {\n ImGui.SetNextItemWidth(availWidth - 155);\n ImGui.Combo(\"##TargetSection\", ref _selectedSection, _sectionLabels, _sectionLabels.Length);\n\n ImGui.SameLine(0, 5);\n\n if ( _wheel.IsSpinning )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Spin to Selected\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Spin to Selected\", new Vector2(150, 0)) )\n {\n Spin(_selectedSection);\n }\n\n ImGui.Spacing();\n ImGui.SetCursorPosX(availWidth - 150);\n\n if ( _wheel.IsSpinning )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Spin Random\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Spin Random\", new Vector2(150, 0)) )\n {\n Spin();\n }\n\n ImGui.SameLine(-1, 0);\n\n if ( _wheel.IsEnabled )\n {\n if ( ImGui.Button(\"Hide Wheel\", new Vector2(155, 0)) )\n {\n _wheel.Disable();\n }\n }\n else\n {\n if ( ImGui.Button(\"Show Wheel\", new Vector2(155, 0)) )\n {\n _wheel.Enable();\n }\n }\n\n if ( _wheel.IsSpinning )\n {\n ImGui.SameLine(0, 10);\n ImGui.SetNextItemWidth(availWidth - 155 - 150 - 10 - 5);\n ImGui.ProgressBar(_spinningOperation?.Progress ?? 0, new Vector2(0, 0), \"Spinning...\");\n }\n }\n else\n {\n var txt = \"Add sections to test spinning\";\n ImGui.SetCursorPosX((availWidth - ImGui.CalcTextSize(txt).X) * 0.5f);\n ImGui.TextColored(new Vector4(1, 0.3f, 0.3f, 1), txt);\n }\n }\n\n private void UpdateConfiguration()\n {\n var updatedConfig = _currentConfig with {\n Font = _fontName,\n FontSize = _fontSize,\n TextColor = _textColor,\n TextScale = _textScale,\n TextStroke = _strokeWidth,\n AdaptiveText = _useAdaptiveSize,\n RadialTextOrientation = _radialTextOrientation,\n SectionLabels = _sectionLabels,\n SpinDuration = _spinDuration,\n MinRotations = _minRotations,\n Enabled = _defaultEnabled,\n Width = _width,\n Height = _height,\n RotationDegrees = _rotationDegrees,\n AnimateToggle = _animateToggle,\n AnimationDuration = _animationDuration\n };\n\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(updatedConfig, SectionKey);\n\n MarkAsChanged();\n }\n\n public override void Update(float deltaTime)\n {\n if ( _spinningOperation != null && _wheel.IsSpinning )\n {\n _spinningOperation.Progress = _wheel.Progress;\n }\n }\n\n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved();\n }\n\n private void ResetToDefaults()\n {\n var defaultConfig = new RouletteWheelOptions();\n _currentConfig = defaultConfig;\n\n LoadConfiguration(_currentConfig);\n\n ConfigManager.UpdateConfiguration(defaultConfig, SectionKey);\n MarkAsChanged();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysics.cs", "using System.Numerics;\nusing System.Text.Json;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// 物理演算のクラス。\n/// \npublic class CubismPhysics\n{\n /// physics types tags.\n public const string PhysicsTypeTagX = \"X\";\n\n public const string PhysicsTypeTagY = \"Y\";\n\n public const string PhysicsTypeTagAngle = \"Angle\";\n\n /// Constant of air resistance.\n public const float AirResistance = 5.0f;\n\n /// Constant of maximum weight of input and output ratio.\n public const float MaximumWeight = 100.0f;\n\n /// Constant of threshold of movement.\n public const float MovementThreshold = 0.001f;\n\n /// Constant of maximum allowed delta time\n public const float MaxDeltaTime = 5.0f;\n\n /// \n /// 最新の振り子計算の結果\n /// \n private readonly List _currentRigOutputs = [];\n\n /// \n /// 物理演算のデータ\n /// \n private readonly CubismPhysicsRig _physicsRig;\n\n /// \n /// 一つ前の振り子計算の結果\n /// \n private readonly List _previousRigOutputs = [];\n\n /// \n /// 物理演算が処理していない時間\n /// \n private float _currentRemainTime;\n\n /// \n /// Evaluateで利用するパラメータのキャッシュs\n /// \n private float[] _parameterCaches = [];\n\n /// \n /// UpdateParticlesが動くときの入力をキャッシュ\n /// \n private float[] _parameterInputCaches = [];\n\n /// \n /// 重力方向\n /// \n public Vector2 Gravity;\n\n /// \n /// 風の方向\n /// \n public Vector2 Wind;\n\n /// \n /// インスタンスを作成する。\n /// \n /// physics3.jsonが読み込まれいるバッファ\n public CubismPhysics(string buffer)\n {\n // set default options.\n Gravity.Y = -1.0f;\n Gravity.X = 0;\n Wind.X = 0;\n Wind.Y = 0;\n _currentRemainTime = 0.0f;\n\n using var stream = File.Open(buffer, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismPhysicsObjContext.Default.CubismPhysicsObj)\n ?? throw new Exception(\"Load Physics error\");\n\n _physicsRig = new CubismPhysicsRig {\n Gravity = obj.Meta.EffectiveForces.Gravity,\n Wind = obj.Meta.EffectiveForces.Wind,\n SubRigCount = obj.Meta.PhysicsSettingCount,\n Fps = obj.Meta.Fps,\n Settings = new CubismPhysicsSubRig[obj.Meta.PhysicsSettingCount],\n Inputs = new CubismPhysicsInput[obj.Meta.TotalInputCount],\n Outputs = new CubismPhysicsOutput[obj.Meta.TotalOutputCount],\n Particles = new CubismPhysicsParticle[obj.Meta.VertexCount]\n };\n\n _currentRigOutputs.Clear();\n _previousRigOutputs.Clear();\n\n int inputIndex = 0,\n outputIndex = 0,\n particleIndex = 0;\n\n for ( var i = 0; i < _physicsRig.Settings.Length; ++i )\n {\n var set = obj.PhysicsSettings[i];\n _physicsRig.Settings[i] = new CubismPhysicsSubRig {\n NormalizationPosition = new CubismPhysicsNormalization { Minimum = set.Normalization.Position.Minimum, Maximum = set.Normalization.Position.Maximum, Default = set.Normalization.Position.Default },\n NormalizationAngle = new CubismPhysicsNormalization { Minimum = set.Normalization.Angle.Minimum, Maximum = set.Normalization.Angle.Maximum, Default = set.Normalization.Angle.Default },\n // Input\n InputCount = set.Input.Count,\n BaseInputIndex = inputIndex\n };\n\n for ( var j = 0; j < _physicsRig.Settings[i].InputCount; ++j )\n {\n var input = set.Input[j];\n _physicsRig.Inputs[inputIndex + j] = new CubismPhysicsInput { SourceParameterIndex = -1, Weight = input.Weight, Reflect = input.Reflect, Source = new CubismPhysicsParameter { TargetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter, Id = input.Source.Id } };\n\n if ( input.Type == PhysicsTypeTagX )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_X;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputTranslationXFromNormalizedParameterValue;\n }\n else if ( input.Type == PhysicsTypeTagY )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Y;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputTranslationYFromNormalizedParameterValue;\n }\n else if ( input.Type == PhysicsTypeTagAngle )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Angle;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputAngleFromNormalizedParameterValue;\n }\n }\n\n inputIndex += _physicsRig.Settings[i].InputCount;\n\n // Output\n _physicsRig.Settings[i].OutputCount = set.Output.Count;\n _physicsRig.Settings[i].BaseOutputIndex = outputIndex;\n\n _currentRigOutputs.Add(new float[set.Output.Count]);\n _previousRigOutputs.Add(new float[set.Output.Count]);\n\n for ( var j = 0; j < _physicsRig.Settings[i].OutputCount; ++j )\n {\n var output = set.Output[j];\n _physicsRig.Outputs[outputIndex + j] = new CubismPhysicsOutput {\n DestinationParameterIndex = -1,\n VertexIndex = output.VertexIndex,\n AngleScale = output.Scale,\n Weight = output.Weight,\n Destination = new CubismPhysicsParameter { TargetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter, Id = output.Destination.Id },\n Reflect = output.Reflect\n };\n\n var key = output.Type;\n if ( key == PhysicsTypeTagX )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_X;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputTranslationX;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleTranslationX;\n }\n else if ( key == PhysicsTypeTagY )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Y;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputTranslationY;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleTranslationY;\n }\n else if ( key == PhysicsTypeTagAngle )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Angle;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputAngle;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleAngle;\n }\n }\n\n outputIndex += _physicsRig.Settings[i].OutputCount;\n\n // Particle\n _physicsRig.Settings[i].ParticleCount = set.Vertices.Count;\n _physicsRig.Settings[i].BaseParticleIndex = particleIndex;\n for ( var j = 0; j < _physicsRig.Settings[i].ParticleCount; ++j )\n {\n var par = set.Vertices[j];\n _physicsRig.Particles[particleIndex + j] = new CubismPhysicsParticle {\n Mobility = par.Mobility,\n Delay = par.Delay,\n Acceleration = par.Acceleration,\n Radius = par.Radius,\n Position = par.Position\n };\n }\n\n particleIndex += _physicsRig.Settings[i].ParticleCount;\n }\n\n Initialize();\n\n _physicsRig.Gravity.Y = 0;\n }\n\n /// \n /// パラメータをリセットする。\n /// \n public void Reset()\n {\n // set default options.\n Gravity.Y = -1.0f;\n Gravity.X = 0.0f;\n Wind.X = 0.0f;\n Wind.Y = 0.0f;\n\n _physicsRig.Gravity.X = 0.0f;\n _physicsRig.Gravity.Y = 0.0f;\n _physicsRig.Wind.X = 0.0f;\n _physicsRig.Wind.Y = 0.0f;\n\n Initialize();\n }\n\n /// \n /// 現在のパラメータ値で物理演算が安定化する状態を演算する。\n /// \n /// 物理演算の結果を適用するモデル\n public unsafe void Stabilization(CubismModel model)\n {\n float totalAngle;\n float weight;\n float radAngle;\n float outputValue;\n Vector2 totalTranslation;\n int i,\n settingIndex,\n particleIndex;\n\n float* parameterValues;\n float* parameterMaximumValues;\n float* parameterMinimumValues;\n float* parameterDefaultValues;\n\n parameterValues = CubismCore.GetParameterValues(model.Model);\n parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n parameterDefaultValues = CubismCore.GetParameterDefaultValues(model.Model);\n\n if ( _parameterCaches.Length < model.GetParameterCount() )\n {\n _parameterCaches = new float[model.GetParameterCount()];\n }\n\n if ( _parameterInputCaches.Length < model.GetParameterCount() )\n {\n _parameterInputCaches = new float[model.GetParameterCount()];\n }\n\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterCaches[j] = parameterValues[j];\n _parameterInputCaches[j] = parameterValues[j];\n }\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n totalAngle = 0.0f;\n totalTranslation.X = 0.0f;\n totalTranslation.Y = 0.0f;\n\n var currentSetting = _physicsRig.Settings[settingIndex];\n var currentInputIndex = currentSetting.BaseInputIndex;\n var currentOutputIndex = currentSetting.BaseOutputIndex;\n var currentParticleIndex = currentSetting.BaseParticleIndex;\n\n // Load input parameters\n for ( i = 0; i < currentSetting.InputCount; ++i )\n {\n weight = _physicsRig.Inputs[i + currentInputIndex].Weight / MaximumWeight;\n\n if ( _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex == -1 )\n {\n _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex = model.GetParameterIndex(_physicsRig.Inputs[i + currentInputIndex].Source.Id);\n }\n\n _physicsRig.Inputs[i + currentInputIndex].GetNormalizedParameterValue(\n ref totalTranslation,\n ref totalAngle,\n parameterValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMinimumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMaximumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterDefaultValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n currentSetting.NormalizationPosition,\n currentSetting.NormalizationAngle,\n _physicsRig.Inputs[i + currentInputIndex].Reflect,\n weight\n );\n\n _parameterCaches[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex] =\n parameterValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex];\n }\n\n radAngle = CubismMath.DegreesToRadian(-totalAngle);\n\n totalTranslation.X = totalTranslation.X * MathF.Cos(radAngle) - totalTranslation.Y * MathF.Sin(radAngle);\n totalTranslation.Y = totalTranslation.X * MathF.Sin(radAngle) + totalTranslation.Y * MathF.Cos(radAngle);\n\n // Calculate particles position.\n UpdateParticlesForStabilization(\n _physicsRig.Particles,\n currentSetting.BaseParticleIndex,\n currentSetting.ParticleCount,\n totalTranslation,\n totalAngle,\n Wind,\n MovementThreshold * currentSetting.NormalizationPosition.Maximum\n );\n\n // Update output parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n particleIndex = _physicsRig.Outputs[i + currentOutputIndex].VertexIndex;\n\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex = model.GetParameterIndex(\n _physicsRig.Outputs[i + currentOutputIndex].Destination.Id);\n }\n\n if ( particleIndex < 1 || particleIndex >= currentSetting.ParticleCount )\n {\n continue;\n }\n\n Vector2 translation = new() { X = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.X - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.X, Y = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.Y - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.Y };\n\n outputValue = _physicsRig.Outputs[i + currentOutputIndex].GetValue(\n translation,\n _physicsRig.Particles,\n currentParticleIndex,\n particleIndex,\n _physicsRig.Outputs[i + currentOutputIndex].Reflect,\n Gravity\n );\n\n _currentRigOutputs[settingIndex][i] = outputValue;\n _previousRigOutputs[settingIndex][i] = outputValue;\n\n UpdateOutputParameterValue(\n ref parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n outputValue,\n _physicsRig.Outputs[i + currentOutputIndex]);\n\n _parameterCaches[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex] = parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex];\n }\n }\n }\n\n /// \n /// 物理演算を評価する。\n /// Pendulum interpolation weights\n /// 振り子の計算結果は保存され、パラメータへの出力は保存された前回の結果で補間されます。\n /// The result of the pendulum calculation is saved and\n /// the output to the parameters is interpolated with the saved previous result of the pendulum calculation.\n /// 図で示すと[1]と[2]で補間されます。\n /// The figure shows the interpolation between [1] and [2].\n /// 補間の重みは最新の振り子計算タイミングと次回のタイミングの間で見た現在時間で決定する。\n /// The weight of the interpolation are determined by the current time seen between\n /// the latest pendulum calculation timing and the next timing.\n /// 図で示すと[2]と[4]の間でみた(3)の位置の重みになる。\n /// Figure shows the weight of position (3) as seen between [2] and [4].\n /// 解釈として振り子計算のタイミングと重み計算のタイミングがズレる。\n /// As an interpretation, the pendulum calculation and weights are misaligned.\n /// physics3.jsonにFPS情報が存在しない場合は常に前の振り子状態で設定される。\n /// If there is no FPS information in physics3.json, it is always set in the previous pendulum state.\n /// この仕様は補間範囲を逸脱したことが原因の震えたような見た目を回避を目的にしている。\n /// The purpose of this specification is to avoid the quivering appearance caused by deviations from the interpolation\n /// range.\n /// ------------ time -------------->\n /// |+++++|------|\n /// <- weight\n /// ==[1]====#=====[2]---(3)----(4)\n /// ^ output contents\n /// \n /// 1 :_previousRigOutputs\n /// 2 :_currentRigOutputs\n /// 3 :_currentRemainTime ( now rendering)\n /// 4 :next particles timing\n /// \n /// @ param model\n /// @ param deltaTimeSeconds rendering delta time.\n /// \n /// 物理演算の結果を適用するモデル\n /// デルタ時間[秒]\n public unsafe void Evaluate(CubismModel model, float deltaTimeSeconds)\n {\n float totalAngle;\n float weight;\n float radAngle;\n float outputValue;\n Vector2 totalTranslation;\n int i,\n settingIndex,\n particleIndex;\n\n if ( 0.0f >= deltaTimeSeconds )\n {\n return;\n }\n\n float physicsDeltaTime;\n _currentRemainTime += deltaTimeSeconds;\n if ( _currentRemainTime > MaxDeltaTime )\n {\n _currentRemainTime = 0.0f;\n }\n\n var parameterValues = CubismCore.GetParameterValues(model.Model);\n var parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n var parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n var parameterDefaultValues = CubismCore.GetParameterDefaultValues(model.Model);\n\n if ( _parameterCaches.Length < model.GetParameterCount() )\n {\n _parameterCaches = new float[model.GetParameterCount()];\n }\n\n if ( _parameterInputCaches.Length < model.GetParameterCount() )\n {\n _parameterInputCaches = new float[model.GetParameterCount()];\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterInputCaches[j] = parameterValues[j];\n }\n }\n\n if ( _physicsRig.Fps > 0.0f )\n {\n physicsDeltaTime = 1.0f / _physicsRig.Fps;\n }\n else\n {\n physicsDeltaTime = deltaTimeSeconds;\n }\n\n CubismPhysicsSubRig currentSetting;\n CubismPhysicsOutput currentOutputs;\n\n while ( _currentRemainTime >= physicsDeltaTime )\n {\n // copyRigOutputs _currentRigOutputs to _previousRigOutputs\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n if ( currentSetting.BaseOutputIndex >= _physicsRig.Outputs.Length )\n {\n continue;\n }\n\n currentOutputs = _physicsRig.Outputs[currentSetting.BaseOutputIndex];\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n _previousRigOutputs[settingIndex][i] = _currentRigOutputs[settingIndex][i];\n }\n }\n\n // 入力キャッシュとパラメータで線形補間してUpdateParticlesするタイミングでの入力を計算する。\n // Calculate the input at the timing to UpdateParticles by linear interpolation with the _parameterInputCaches and parameterValues.\n // _parameterCachesはグループ間での値の伝搬の役割があるので_parameterInputCachesとの分離が必要。\n // _parameterCaches needs to be separated from _parameterInputCaches because of its role in propagating values between groups.\n var inputWeight = physicsDeltaTime / _currentRemainTime;\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterCaches[j] = _parameterInputCaches[j] * (1.0f - inputWeight) + parameterValues[j] * inputWeight;\n _parameterInputCaches[j] = _parameterCaches[j];\n }\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n totalAngle = 0.0f;\n totalTranslation.X = 0.0f;\n totalTranslation.Y = 0.0f;\n currentSetting = _physicsRig.Settings[settingIndex];\n var currentInputIndex = currentSetting.BaseInputIndex;\n var currentOutputIndex = currentSetting.BaseOutputIndex;\n var currentParticleIndex = currentSetting.BaseParticleIndex;\n\n // Load input parameters.\n for ( i = 0; i < currentSetting.InputCount; ++i )\n {\n weight = _physicsRig.Inputs[i + currentInputIndex].Weight / MaximumWeight;\n\n if ( _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex == -1 )\n {\n _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex = model.GetParameterIndex(_physicsRig.Inputs[i + currentInputIndex].Source.Id);\n }\n\n _physicsRig.Inputs[i + currentInputIndex].GetNormalizedParameterValue(\n ref totalTranslation,\n ref totalAngle,\n _parameterCaches[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMinimumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMaximumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterDefaultValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n currentSetting.NormalizationPosition,\n currentSetting.NormalizationAngle,\n _physicsRig.Inputs[i + currentInputIndex].Reflect,\n weight\n );\n }\n\n radAngle = CubismMath.DegreesToRadian(-totalAngle);\n\n totalTranslation.X = totalTranslation.X * MathF.Cos(radAngle) - totalTranslation.Y * MathF.Sin(radAngle);\n totalTranslation.Y = totalTranslation.X * MathF.Sin(radAngle) + totalTranslation.Y * MathF.Cos(radAngle);\n\n // Calculate particles position.\n UpdateParticles(\n _physicsRig.Particles,\n currentParticleIndex,\n currentSetting.ParticleCount,\n totalTranslation,\n totalAngle,\n Wind,\n MovementThreshold * currentSetting.NormalizationPosition.Maximum,\n physicsDeltaTime,\n AirResistance\n );\n\n // Update output parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n particleIndex = _physicsRig.Outputs[i + currentOutputIndex].VertexIndex;\n\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex = model.GetParameterIndex(_physicsRig.Outputs[i + currentOutputIndex].Destination.Id);\n }\n\n if ( particleIndex < 1 || particleIndex >= currentSetting.ParticleCount )\n {\n continue;\n }\n\n Vector2 translation;\n translation.X = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.X - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.X;\n translation.Y = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.Y - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.Y;\n\n outputValue = _physicsRig.Outputs[i + currentOutputIndex].GetValue(\n translation,\n _physicsRig.Particles,\n currentParticleIndex,\n particleIndex,\n _physicsRig.Outputs[i + currentOutputIndex].Reflect,\n Gravity\n );\n\n _currentRigOutputs[settingIndex][i] = outputValue;\n\n UpdateOutputParameterValue(\n ref _parameterCaches[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n outputValue,\n _physicsRig.Outputs[i + currentOutputIndex]);\n }\n }\n\n _currentRemainTime -= physicsDeltaTime;\n }\n\n var alpha = _currentRemainTime / physicsDeltaTime;\n Interpolate(model, alpha);\n }\n\n /// \n /// オプションを設定する。\n /// \n public void SetOptions(Vector2 gravity, Vector2 wind)\n {\n Gravity = gravity;\n Wind = wind;\n }\n\n /// \n /// オプションを取得する。\n /// \n /// オプション\n public (Vector2 Gravity, Vector2 Wind) GetOptions() { return (Gravity, Wind); }\n\n /// \n /// 初期化する。\n /// \n private void Initialize()\n {\n CubismPhysicsSubRig currentSetting;\n int i,\n settingIndex;\n\n Vector2 radius;\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n var index = currentSetting.BaseParticleIndex;\n\n // Initialize the top of particle.\n _physicsRig.Particles[index].InitialPosition = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[index].LastPosition = _physicsRig.Particles[index].InitialPosition;\n _physicsRig.Particles[index].LastGravity = new Vector2(0.0f, -1.0f);\n _physicsRig.Particles[index].LastGravity.Y *= -1.0f;\n _physicsRig.Particles[index].Velocity = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[index].Force = new Vector2(0.0f, 0.0f);\n\n // Initialize particles.\n for ( i = 1; i < currentSetting.ParticleCount; ++i )\n {\n radius = new Vector2(0.0f, _physicsRig.Particles[i + index].Radius);\n _physicsRig.Particles[i + index].InitialPosition = _physicsRig.Particles[i - 1 + index].InitialPosition + radius;\n _physicsRig.Particles[i + index].Position = _physicsRig.Particles[i + index].InitialPosition;\n _physicsRig.Particles[i + index].LastPosition = _physicsRig.Particles[i + index].InitialPosition;\n _physicsRig.Particles[i + index].LastGravity = new Vector2(0.0f, -1.0f);\n _physicsRig.Particles[i + index].LastGravity.Y *= -1.0f;\n _physicsRig.Particles[i + index].Velocity = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[i + index].Force = new Vector2(0.0f, 0.0f);\n }\n }\n }\n\n /// \n /// 振り子演算の最新の結果と一つ前の結果から指定した重みで適用する。\n /// \n /// 物理演算の結果を適用するモデル\n /// 最新結果の重み\n private unsafe void Interpolate(CubismModel model, float weight)\n {\n int i,\n settingIndex;\n\n float* parameterValues;\n float* parameterMaximumValues;\n float* parameterMinimumValues;\n\n int currentOutputIndex;\n CubismPhysicsSubRig currentSetting;\n\n parameterValues = CubismCore.GetParameterValues(model.Model);\n parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n currentOutputIndex = currentSetting.BaseOutputIndex;\n\n // Load input parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n continue;\n }\n\n var value = _previousRigOutputs[settingIndex][i] * (1 - weight) + _currentRigOutputs[settingIndex][i] * weight;\n\n UpdateOutputParameterValue(\n ref parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n value,\n _physicsRig.Outputs[i + currentOutputIndex]\n );\n }\n }\n }\n\n private float GetRangeValue(float min, float max)\n {\n var maxValue = CubismMath.Max(min, max);\n var minValue = CubismMath.Min(min, max);\n\n return MathF.Abs(maxValue - minValue);\n }\n\n /// Gets sign.\n /// \n /// @param value Evaluation target value.\n /// \n /// @return Sign of value.\n private static int Sign(float value)\n {\n var ret = 0;\n\n if ( value > 0.0f )\n {\n ret = 1;\n }\n else if ( value < 0.0f )\n {\n ret = -1;\n }\n\n return ret;\n }\n\n private float GetDefaultValue(float min, float max)\n {\n var minValue = CubismMath.Min(min, max);\n\n return minValue + GetRangeValue(min, max) / 2.0f;\n }\n\n private float NormalizeParameterValue(\n float value,\n float parameterMinimum,\n float parameterMaximum,\n float parameterDefault,\n float normalizedMinimum,\n float normalizedMaximum,\n float normalizedDefault,\n bool isInverted)\n {\n var result = 0.0f;\n\n var maxValue = CubismMath.Max(parameterMaximum, parameterMinimum);\n\n if ( maxValue < value )\n {\n value = maxValue;\n }\n\n var minValue = CubismMath.Min(parameterMaximum, parameterMinimum);\n\n if ( minValue > value )\n {\n value = minValue;\n }\n\n var minNormValue = CubismMath.Min(normalizedMinimum, normalizedMaximum);\n var maxNormValue = CubismMath.Max(normalizedMinimum, normalizedMaximum);\n var middleNormValue = normalizedDefault;\n\n var middleValue = GetDefaultValue(minValue, maxValue);\n var paramValue = value - middleValue;\n\n switch ( Sign(paramValue) )\n {\n case 1:\n {\n var nLength = maxNormValue - middleNormValue;\n var pLength = maxValue - middleValue;\n if ( pLength != 0.0f )\n {\n result = paramValue * (nLength / pLength);\n result += middleNormValue;\n }\n\n break;\n }\n case -1:\n {\n var nLength = minNormValue - middleNormValue;\n var pLength = minValue - middleValue;\n if ( pLength != 0.0f )\n {\n result = paramValue * (nLength / pLength);\n result += middleNormValue;\n }\n\n break;\n }\n case 0:\n {\n result = middleNormValue;\n\n break;\n }\n }\n\n return isInverted ? result : result * -1.0f;\n }\n\n private void GetInputTranslationXFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle, bool isInverted,\n float weight)\n {\n targetTranslation.X += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationPosition.Minimum,\n normalizationPosition.Maximum,\n normalizationPosition.Default,\n isInverted\n ) * weight;\n }\n\n private void GetInputTranslationYFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted, float weight)\n {\n targetTranslation.Y += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationPosition.Minimum,\n normalizationPosition.Maximum,\n normalizationPosition.Default,\n isInverted\n ) * weight;\n }\n\n private void GetInputAngleFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted, float weight)\n {\n targetAngle += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationAngle.Minimum,\n normalizationAngle.Maximum,\n normalizationAngle.Default,\n isInverted\n ) * weight;\n }\n\n private float GetOutputTranslationX(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n var outputValue = translation.X;\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputTranslationY(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n var outputValue = translation.Y;\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputAngle(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n float outputValue;\n\n if ( particleIndex >= 2 )\n {\n parentGravity = particles[particleIndex - 1 + start].Position - particles[particleIndex - 2 + start].Position;\n }\n else\n {\n parentGravity *= -1.0f;\n }\n\n outputValue = CubismMath.DirectionToRadian(parentGravity, translation);\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputScaleTranslationX(Vector2 translationScale, float angleScale) { return translationScale.X; }\n\n private float GetOutputScaleTranslationY(Vector2 translationScale, float angleScale) { return translationScale.Y; }\n\n private float GetOutputScaleAngle(Vector2 translationScale, float angleScale) { return angleScale; }\n\n /// Updates particles.\n /// \n /// @param strand Target array of particle.\n /// @param strandCount Count of particle.\n /// @param totalTranslation Total translation value.\n /// @param totalAngle Total angle.\n /// @param windDirection Direction of wind.\n /// @param thresholdValue Threshold of movement.\n /// @param deltaTimeSeconds Delta time.\n /// @param airResistance Air resistance.\n private static void UpdateParticles(CubismPhysicsParticle[] strand, int start, int strandCount, Vector2 totalTranslation, float totalAngle,\n Vector2 windDirection, float thresholdValue, float deltaTimeSeconds, float airResistance)\n {\n int i;\n float totalRadian;\n float delay;\n float radian;\n Vector2 currentGravity;\n Vector2 direction;\n Vector2 velocity;\n Vector2 force;\n Vector2 newDirection;\n\n strand[start].Position = totalTranslation;\n\n totalRadian = CubismMath.DegreesToRadian(totalAngle);\n currentGravity = CubismMath.RadianToDirection(totalRadian);\n currentGravity = Vector2.Normalize(currentGravity);\n\n for ( i = 1; i < strandCount; ++i )\n {\n strand[i + start].Force = currentGravity * strand[i + start].Acceleration + windDirection;\n\n strand[i + start].LastPosition = strand[i + start].Position;\n\n delay = strand[i + start].Delay * deltaTimeSeconds * 30.0f;\n\n direction.X = strand[i + start].Position.X - strand[i - 1 + start].Position.X;\n direction.Y = strand[i + start].Position.Y - strand[i - 1 + start].Position.Y;\n\n radian = CubismMath.DirectionToRadian(strand[i + start].LastGravity, currentGravity) / airResistance;\n\n direction.X = MathF.Cos(radian) * direction.X - direction.Y * MathF.Sin(radian);\n direction.Y = MathF.Sin(radian) * direction.X + direction.Y * MathF.Cos(radian);\n\n strand[i + start].Position = strand[i - 1 + start].Position + direction;\n\n velocity.X = strand[i + start].Velocity.X * delay;\n velocity.Y = strand[i + start].Velocity.Y * delay;\n force = strand[i + start].Force * delay * delay;\n\n strand[i + start].Position = strand[i + start].Position + velocity + force;\n\n newDirection = strand[i + start].Position - strand[i - 1 + start].Position;\n\n newDirection = Vector2.Normalize(newDirection);\n\n strand[i + start].Position = strand[i - 1 + start].Position + newDirection * strand[i + start].Radius;\n\n if ( MathF.Abs(strand[i + start].Position.X) < thresholdValue )\n {\n strand[i + start].Position.X = 0.0f;\n }\n\n if ( delay != 0.0f )\n {\n strand[i + start].Velocity.X = strand[i + start].Position.X - strand[i + start].LastPosition.X;\n strand[i + start].Velocity.Y = strand[i + start].Position.Y - strand[i + start].LastPosition.Y;\n strand[i + start].Velocity /= delay;\n strand[i + start].Velocity *= strand[i + start].Mobility;\n }\n\n strand[i + start].Force = new Vector2(0.0f, 0.0f);\n strand[i + start].LastGravity = currentGravity;\n }\n }\n\n /**\n * Updates particles for stabilization.\n * \n * @param strand Target array of particle.\n * @param strandCount Count of particle.\n * @param totalTranslation Total translation value.\n * @param totalAngle Total angle.\n * @param windDirection Direction of Wind.\n * @param thresholdValue Threshold of movement.\n */\n private static void UpdateParticlesForStabilization(CubismPhysicsParticle[] strand, int start, int strandCount, Vector2 totalTranslation, float totalAngle,\n Vector2 windDirection, float thresholdValue)\n {\n int i;\n float totalRadian;\n Vector2 currentGravity;\n Vector2 force;\n\n strand[start].Position = totalTranslation;\n\n totalRadian = CubismMath.DegreesToRadian(totalAngle);\n currentGravity = CubismMath.RadianToDirection(totalRadian);\n currentGravity = Vector2.Normalize(currentGravity);\n\n for ( i = 1; i < strandCount; ++i )\n {\n strand[i + start].Force = currentGravity * strand[i + start].Acceleration + windDirection;\n\n strand[i + start].LastPosition = strand[i + start].Position;\n\n strand[i + start].Velocity = new Vector2(0.0f, 0.0f);\n\n force = strand[i + start].Force;\n force = Vector2.Normalize(force);\n\n force *= strand[i + start].Radius;\n strand[i + start].Position = strand[i - 1].Position + force;\n\n if ( MathF.Abs(strand[i + start].Position.X) < thresholdValue )\n {\n strand[i + start].Position.X = 0.0f;\n }\n\n strand[i + start].Force = new Vector2(0.0f, 0.0f);\n strand[i + start].LastGravity = currentGravity;\n }\n }\n\n /// Updates output parameter value.\n /// \n /// @param parameterValue Target parameter value.\n /// @param parameterValueMinimum Minimum of parameter value.\n /// @param parameterValueMaximum Maximum of parameter value.\n /// @param translation Translation value.\n private static void UpdateOutputParameterValue(ref float parameterValue, float parameterValueMinimum, float parameterValueMaximum,\n float translation, CubismPhysicsOutput output)\n {\n float outputScale;\n float value;\n float weight;\n\n outputScale = output.GetScale(output.TranslationScale, output.AngleScale);\n\n value = translation * outputScale;\n\n if ( value < parameterValueMinimum )\n {\n if ( value < output.ValueBelowMinimum )\n {\n output.ValueBelowMinimum = value;\n }\n\n value = parameterValueMinimum;\n }\n else if ( value > parameterValueMaximum )\n {\n if ( value > output.ValueExceededMaximum )\n {\n output.ValueExceededMaximum = value;\n }\n\n value = parameterValueMaximum;\n }\n\n weight = output.Weight / MaximumWeight;\n\n if ( weight >= 1.0f )\n {\n parameterValue = value;\n }\n else\n {\n value = parameterValue * (1.0f - weight) + value * weight;\n parameterValue = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Live2DManager.cs", "using Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.Live2D.Behaviour;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\nusing PersonaEngine.Lib.UI;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.Live2D;\n\npublic class Live2DManager : IRenderComponent\n{\n private readonly IList _live2DAnimationServices;\n\n private readonly IOptionsMonitor _options;\n\n private LAppDelegate? _lapp;\n\n public Live2DManager(IOptionsMonitor options, IEnumerable live2DAnimationServices)\n {\n _options = options;\n _live2DAnimationServices = live2DAnimationServices.ToList();\n }\n\n public bool UseSpout => true;\n\n public string SpoutTarget => \"Live2D\";\n\n public int Priority => 100;\n\n public void Update(float deltaTime) { }\n\n public void Render(float deltaTime)\n {\n if ( _lapp == null )\n {\n return;\n }\n\n _lapp.Update(deltaTime);\n _lapp.Run();\n }\n\n public void Resize() { _lapp?.Resize(); }\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n var config = _options.CurrentValue;\n _lapp = new LAppDelegate(new SilkNetApi(gl, config.Width, config.Height), _ => { }) { BGColor = new CubismTextureColor(0, 0, 0, 0) };\n\n LoadModel(config.ModelPath, config.ModelName);\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n }\n\n /// \n /// Loads a Live2D model from the given path.\n /// \n public void LoadModel(string modelPath, string modelName)\n {\n if ( _lapp == null )\n {\n throw new InvalidOperationException(\"Live2DManager is not initialized.\");\n }\n\n var model = _lapp.Live2dManager.LoadModel(modelPath, modelName);\n model.RandomMotion = false;\n model.CustomValueUpdate = true;\n\n // model.ModelMatrix.Translate(0.0f, -1.8f);\n model.ModelMatrix.ScaleRelative(0.7f, 0.7f);\n\n Resize();\n\n foreach ( var animationService in _live2DAnimationServices )\n {\n model.ValueUpdate += _ => animationService.Update(LAppPal.DeltaTime);\n animationService.Start(model);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Adapters/Audio/Output/PortaudioOutputAdapter.cs", "using System.Runtime.InteropServices;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Audio.Player;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nusing PortAudioSharp;\n\nusing Stream = PortAudioSharp.Stream;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Output;\n\npublic class PortaudioOutputAdapter(ILogger logger, IAudioProgressNotifier progressNotifier) : IAudioOutputAdapter\n{\n private const int DefaultSampleRate = 24000;\n\n private const int DefaultFrameBufferSize = 1024;\n\n private readonly float[] _frameBuffer = new float[DefaultFrameBufferSize];\n\n private Stream? _audioStream;\n\n private AudioBuffer? _currentBuffer;\n\n private ChannelReader? _currentReader;\n\n private Guid _currentTurnId;\n\n private long _framesOfChunkPlayed;\n\n private TaskCompletionSource? _playbackCompletion;\n\n private CancellationTokenSource? _playbackCts;\n\n private volatile bool _producerCompleted;\n\n private Channel? _progressChannel;\n\n private Guid _sessionId;\n\n public ValueTask DisposeAsync()\n {\n try\n {\n _audioStream = null;\n }\n catch\n {\n /* ignored */\n }\n\n return ValueTask.CompletedTask;\n }\n\n public Guid AdapterId { get; } = Guid.NewGuid();\n\n public ValueTask InitializeAsync(Guid sessionId, CancellationToken cancellationToken)\n {\n _sessionId = sessionId;\n\n try\n {\n PortAudio.Initialize();\n var deviceIndex = PortAudio.DefaultOutputDevice;\n if ( deviceIndex == PortAudio.NoDevice )\n {\n throw new AudioDeviceNotFoundException(\"No default PortAudio output device found.\");\n }\n\n var deviceInfo = PortAudio.GetDeviceInfo(deviceIndex);\n logger.LogDebug(\"Using PortAudio output device: {DeviceName} (Index: {DeviceIndex})\", deviceInfo.name, deviceIndex);\n\n var parameters = new StreamParameters {\n device = deviceIndex,\n channelCount = 1,\n sampleFormat = SampleFormat.Float32,\n suggestedLatency = deviceInfo.defaultLowOutputLatency,\n hostApiSpecificStreamInfo = IntPtr.Zero\n };\n\n _audioStream = new Stream(\n null,\n parameters,\n DefaultSampleRate,\n DefaultFrameBufferSize,\n StreamFlags.ClipOff,\n AudioCallback,\n IntPtr.Zero);\n }\n catch (Exception ex)\n {\n logger.LogError(ex, \"Failed to initialize PortAudio or create stream.\");\n\n try\n {\n PortAudio.Terminate();\n }\n catch\n {\n // ignored\n }\n\n throw new AudioPlayerInitializationException(\"Failed to initialize PortAudio audio system.\", ex);\n }\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StartAsync(CancellationToken cancellationToken)\n {\n // Don't start it here, SendAsync will handle it.\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StopAsync(CancellationToken cancellationToken)\n {\n // Don't stop it here, SendAsync's cleanup or cancellation will handle it.\n // If a hard stop independent of SendAsync is needed, cancellation of SendAsync's token is the way.\n\n return ValueTask.CompletedTask;\n }\n\n public async Task SendAsync(ChannelReader inputReader, ChannelWriter outputWriter, Guid turnId, CancellationToken cancellationToken = default)\n {\n if ( _audioStream == null )\n {\n throw new InvalidOperationException(\"Audio stream is not initialized.\");\n }\n\n _currentTurnId = turnId;\n _currentReader = inputReader;\n\n _progressChannel = Channel.CreateBounded(new BoundedChannelOptions(10) { SingleReader = true, SingleWriter = true });\n\n _playbackCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _playbackCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);\n\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n var localPlaybackCts = _playbackCts;\n var localCompletion = _playbackCompletion;\n using var eventLoopCts = new CancellationTokenSource();\n var progressPumpTask = ProgressEventsLoop(eventLoopCts.Token);\n\n try\n {\n _audioStream.Start();\n\n while ( await inputReader.WaitToReadAsync(localPlaybackCts.Token).ConfigureAwait(false) )\n {\n if ( !firstChunk )\n {\n continue;\n }\n\n var firstChunkEvent = new AudioPlaybackStartedEvent(_sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, localPlaybackCts.Token).ConfigureAwait(false);\n\n firstChunk = false;\n }\n\n _producerCompleted = true;\n\n await localCompletion.Task.ConfigureAwait(false);\n await progressPumpTask.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n\n eventLoopCts.CancelAfter(250);\n\n await localCompletion.Task.ConfigureAwait(false);\n await progressPumpTask.ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n\n await outputWriter.WriteAsync(new ErrorOutputEvent(_sessionId, turnId, DateTimeOffset.UtcNow, ex), CancellationToken.None).ConfigureAwait(false);\n }\n finally\n {\n CleanupPlayback();\n\n if ( !firstChunk )\n {\n await outputWriter.WriteAsync(new AudioPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, completedReason), CancellationToken.None).ConfigureAwait(false);\n }\n }\n }\n\n private async ValueTask ProgressEventsLoop(CancellationToken ct = default)\n {\n var eventsReader = _progressChannel!.Reader;\n\n await foreach ( var progressEvent in eventsReader.ReadAllAsync(ct).ConfigureAwait(false) )\n {\n if ( ct.IsCancellationRequested )\n {\n break;\n }\n\n switch ( progressEvent )\n {\n case AudioChunkPlaybackStartedEvent startedArgs:\n progressNotifier.RaiseChunkStarted(this, startedArgs);\n\n break;\n case AudioChunkPlaybackEndedEvent endedArgs:\n progressNotifier.RaiseChunkEnded(this, endedArgs);\n\n break;\n case AudioPlaybackProgressEvent progressArgs:\n progressNotifier.RaiseProgress(this, progressArgs);\n\n break;\n }\n }\n }\n\n private void CleanupPlayback()\n {\n _audioStream?.Stop();\n\n _currentTurnId = Guid.Empty;\n _currentReader = null;\n\n _progressChannel?.Writer.TryComplete();\n _producerCompleted = false;\n _framesOfChunkPlayed = 0;\n _currentBuffer = null;\n\n _playbackCts?.Cancel();\n _playbackCts?.Dispose();\n _playbackCts = null;\n\n Array.Clear(_frameBuffer, 0, DefaultFrameBufferSize);\n }\n\n private StreamCallbackResult AudioCallback(IntPtr input, IntPtr output, uint framecount, ref StreamCallbackTimeInfo timeinfo, StreamCallbackFlags statusflags, IntPtr userdataptr)\n {\n var framesRequested = (int)framecount;\n var framesWritten = 0;\n\n var turnId = _currentTurnId;\n var reader = _currentReader;\n var completionSource = _playbackCompletion;\n var currentPlaybackCts = _playbackCts;\n var ct = currentPlaybackCts?.Token ?? CancellationToken.None;\n var progressWriter = _progressChannel!.Writer;\n\n if ( reader == null )\n {\n completionSource?.TrySetResult(false);\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n while ( framesWritten < framesRequested )\n {\n if ( ct.IsCancellationRequested )\n {\n FillSilence();\n completionSource?.TrySetResult(false);\n\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n if ( _currentBuffer == null )\n {\n if ( reader.TryRead(out var chunk) )\n {\n _currentBuffer = new AudioBuffer(chunk.Chunk.AudioData, chunk.Chunk);\n progressWriter.TryWrite(new AudioChunkPlaybackStartedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, chunk.Chunk));\n }\n else\n {\n if ( _producerCompleted )\n {\n FillSilence();\n completionSource?.TrySetResult(true);\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n FillSilence();\n }\n }\n\n if ( _currentBuffer == null )\n {\n return StreamCallbackResult.Continue;\n }\n\n var framesToCopy = Math.Min(framesRequested - framesWritten, _currentBuffer.Remaining);\n var sourceSpan = _currentBuffer.Data.Span.Slice(_currentBuffer.Position, framesToCopy);\n var destinationSpan = _frameBuffer.AsSpan(framesWritten, framesToCopy);\n sourceSpan.CopyTo(destinationSpan);\n _currentBuffer.Advance(framesToCopy);\n framesWritten += framesToCopy;\n\n if ( _currentBuffer.IsFinished )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n _framesOfChunkPlayed = 0;\n _currentBuffer = null;\n }\n }\n\n Marshal.Copy(_frameBuffer, 0, output, framesRequested);\n\n _framesOfChunkPlayed += framesRequested;\n var currentTime = TimeSpan.FromSeconds((double)_framesOfChunkPlayed / DefaultSampleRate);\n progressWriter.TryWrite(new AudioPlaybackProgressEvent(_sessionId, turnId, DateTimeOffset.UtcNow, currentTime));\n\n if ( _currentBuffer == null && _producerCompleted )\n {\n completionSource?.TrySetResult(true);\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n if ( ct.IsCancellationRequested )\n {\n completionSource?.TrySetResult(false);\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n return StreamCallbackResult.Continue;\n\n void FillSilence()\n {\n if ( framesWritten < framesRequested )\n {\n Array.Clear(_frameBuffer, framesWritten, framesRequested - framesWritten);\n }\n\n Marshal.Copy(_frameBuffer, 0, output, framesRequested);\n }\n }\n\n private sealed class AudioBuffer(Memory data, AudioSegment segment)\n {\n public Memory Data { get; } = data;\n\n public AudioSegment Segment { get; } = segment;\n\n public int Position { get; private set; } = 0;\n\n public int Remaining => Data.Length - Position;\n\n public bool IsFinished => Position >= Data.Length;\n\n public void Advance(int count) { Position += count; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppLive2DManager.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// サンプルアプリケーションにおいてCubismModelを管理するクラス\n/// モデル生成と破棄、タップイベントの処理、モデル切り替えを行う。\n/// \n/// \n/// コンストラクタ\n/// \npublic class LAppLive2DManager(LAppDelegate lapp) : IDisposable\n{\n /// \n /// モデルインスタンスのコンテナ\n /// \n private readonly List _models = [];\n\n private readonly CubismMatrix44 _projection = new();\n\n /// \n /// モデル描画に用いるView行列\n /// \n public CubismMatrix44 ViewMatrix { get; } = new();\n\n public void Dispose() { ReleaseAllModel(); }\n\n public event Action? MotionFinished;\n\n /// \n /// 現在のシーンで保持しているモデルを返す\n /// \n /// モデルリストのインデックス値\n /// モデルのインスタンスを返す。インデックス値が範囲外の場合はNULLを返す。\n public LAppModel GetModel(int no) { return _models[no]; }\n\n /// \n /// 現在のシーンで保持しているすべてのモデルを解放する\n /// \n public void ReleaseAllModel()\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n _models[i].Dispose();\n }\n\n _models.Clear();\n }\n\n /// \n /// 画面をドラッグしたときの処理\n /// \n /// 画面のX座標\n /// 画面のY座標\n public void OnDrag(float x, float y)\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n var model = GetModel(i);\n\n model.SetDragging(x, y);\n }\n }\n\n /// \n /// 画面をタップしたときの処理\n /// \n /// 画面のX座標\n /// 画面のY座標\n public void OnTap(float x, float y)\n {\n CubismLog.Debug($\"[Live2D]tap point: x:{x:0.00} y:{y:0.00}\");\n\n for ( var i = 0; i < _models.Count; i++ )\n {\n if ( _models[i].HitTest(LAppDefine.HitAreaNameHead, x, y) )\n {\n CubismLog.Debug($\"[Live2D]hit area: [{LAppDefine.HitAreaNameHead}]\");\n _models[i].SetRandomExpression();\n }\n else if ( _models[i].HitTest(LAppDefine.HitAreaNameBody, x, y) )\n {\n CubismLog.Debug($\"[Live2D]hit area: [{LAppDefine.HitAreaNameBody}]\");\n _models[i].StartRandomMotion(LAppDefine.MotionGroupTapBody, MotionPriority.PriorityNormal, OnFinishedMotion);\n }\n }\n }\n\n private void OnFinishedMotion(CubismModel model, ACubismMotion self)\n {\n CubismLog.Info($\"[Live2D]Motion Finished: {self}\");\n MotionFinished?.Invoke(model, self);\n }\n\n /// \n /// 画面を更新するときの処理\n /// モデルの更新処理および描画処理を行う\n /// \n public void OnUpdate()\n {\n lapp.GL.GetWindowSize(out var width, out var height);\n\n var modelCount = _models.Count;\n foreach ( var model in _models )\n {\n _projection.LoadIdentity();\n\n if ( model.Model.GetCanvasWidth() > 1.0f && width < height )\n {\n // 横に長いモデルを縦長ウィンドウに表示する際モデルの横サイズでscaleを算出する\n model.ModelMatrix.SetWidth(2.0f);\n _projection.Scale(1.0f, (float)width / height);\n }\n else\n {\n _projection.Scale((float)height / width, 1.0f);\n }\n\n // 必要があればここで乗算\n if ( ViewMatrix != null )\n {\n _projection.MultiplyByMatrix(ViewMatrix);\n }\n\n model.Update();\n model.Draw(_projection); // 参照渡しなのでprojectionは変質する\n }\n }\n\n public LAppModel LoadModel(string dir, string name)\n {\n CubismLog.Debug($\"[Live2D]model load: {name}\");\n\n // ModelDir[]に保持したディレクトリ名から\n // model3.jsonのパスを決定する.\n // ディレクトリ名とmodel3.jsonの名前を一致させておくこと.\n if ( !dir.EndsWith('\\\\') && !dir.EndsWith('/') )\n {\n dir = Path.GetFullPath(dir + '/');\n }\n\n var modelJsonName = Path.GetFullPath($\"{dir}{name}\");\n if ( !File.Exists(modelJsonName) )\n {\n modelJsonName = Path.GetFullPath($\"{dir}{name}.model3.json\");\n }\n\n if ( !File.Exists(modelJsonName) )\n {\n dir = Path.GetFullPath(dir + name + '/');\n modelJsonName = Path.GetFullPath($\"{dir}{name}.model3.json\");\n }\n\n if ( !File.Exists(modelJsonName) )\n {\n throw new Exception($\"[Live2D]File not found: {modelJsonName}\");\n }\n\n var model = new LAppModel(lapp, dir, modelJsonName);\n _models.Add(model);\n\n return model;\n }\n\n public void RemoveModel(int index)\n {\n if ( _models.Count > index )\n {\n var model = _models[index];\n _models.RemoveAt(index);\n model.Dispose();\n }\n }\n\n /// \n /// モデル個数を得る\n /// \n /// 所持モデル個数\n public int GetModelNum() { return _models.Count; }\n\n public async void StartSpeaking(string filePath)\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n _models[i]._wavFileHandler.Start(filePath);\n await _models[i]._wavFileHandler.LoadWavFile(filePath);\n _models[i].StartMotion(LAppDefine.MotionGroupIdle, 0, MotionPriority.PriorityIdle, OnFinishedMotion);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Lexicon.cs", "using System.Collections.Frozen;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic partial class Lexicon : ILexicon, IDisposable\n{\n private static readonly Regex _suffixRegex = SuffixRegex();\n\n private static readonly Regex _doubleConsonantIngRegex = DoubleConsonantIngRegex();\n\n private static readonly Regex _vsRegex = VersusRegex();\n\n private readonly (double Min, double Max) _capStresses = (0.5, 2.0);\n\n private readonly Lock _dictionaryLock = new();\n\n private readonly LruCache _stemCache;\n\n private readonly IOptionsMonitor _ttsConfig;\n\n private readonly IOptionsMonitor _voiceOptions;\n\n private readonly IDisposable? _voiceOptionsChangeToken;\n\n private readonly LruCache _wordCache;\n\n private volatile bool _british;\n\n private volatile IReadOnlyDictionary? _golds;\n\n private volatile IReadOnlyDictionary? _silvers;\n\n private volatile HashSet _vocab;\n\n public Lexicon(\n IOptionsMonitor ttsConfig,\n IOptionsMonitor voiceOptions)\n {\n _ttsConfig = ttsConfig;\n _voiceOptions = voiceOptions;\n\n // Initialize caches - size based on typical working set\n _wordCache = new LruCache(2048, StringComparer.Ordinal);\n _stemCache = new LruCache(512, StringComparer.Ordinal);\n\n // Initial load of dictionaries\n LoadDictionaries();\n\n // Register for configuration changes\n _voiceOptionsChangeToken = _voiceOptions.OnChange(options =>\n {\n var currentBritish = options.UseBritishEnglish;\n if ( _british != currentBritish )\n {\n LoadDictionaries();\n }\n });\n }\n\n public void Dispose() { _voiceOptionsChangeToken?.Dispose(); }\n\n public (string? Phonemes, int? Rating) ProcessToken(Token token, TokenContext ctx)\n {\n // Ensure dictionaries are loaded\n if ( _golds == null || _silvers == null )\n {\n LoadDictionaries();\n }\n\n // Normalize text: replace special quotes with straight quotes and normalize Unicode\n var word = (token.Text ?? token.Alias ?? \"\").Replace('\\u2018', '\\'').Replace('\\u2019', '\\'');\n word = word.Normalize(NormalizationForm.FormKC);\n\n // Calculate stress based on capitalization\n var stress = token.Stress;\n if ( stress == null && word != word.ToLower() )\n {\n stress = word == word.ToUpper() ? _capStresses.Max : _capStresses.Min;\n }\n\n // Call GetWord directly - it already handles all the necessary phoneme lookups, \n // stemming, and special cases\n return GetWord(\n word,\n token.Tag,\n stress,\n ctx,\n token.IsHead,\n token.Currency,\n token.NumFlags);\n }\n\n private void LoadDictionaries()\n {\n lock (_dictionaryLock)\n {\n var voiceOptions = _voiceOptions.CurrentValue;\n var ttsConfig = _ttsConfig.CurrentValue;\n var british = voiceOptions.UseBritishEnglish;\n\n // Double-check after acquiring lock to avoid unnecessary reloads\n if ( _golds != null && _british == british )\n {\n return;\n }\n\n // Update settings\n _british = british;\n _vocab = british ? PhonemizerConstants.GbVocab : PhonemizerConstants.UsVocab;\n\n // Construct paths\n var lexiconPrefix = british ? \"gb\" : \"us\";\n var primaryPath = Path.Combine(ttsConfig.ModelDirectory, $\"{lexiconPrefix}_gold.json\");\n var secondaryPath = Path.Combine(ttsConfig.ModelDirectory, $\"{lexiconPrefix}_silver.json\");\n\n // Use JsonSerializer with custom options\n var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, Converters = { new PhonemeEntryConverter() } };\n\n // Load dictionaries\n _golds = LoadAndGrowDictionary(primaryPath, options);\n _silvers = LoadAndGrowDictionary(secondaryPath, options);\n\n // Clear caches when dictionaries change\n _wordCache.Clear();\n _stemCache.Clear();\n }\n }\n\n private IReadOnlyDictionary LoadAndGrowDictionary(string path, JsonSerializerOptions options)\n {\n using var fileStream = File.OpenRead(path);\n\n // Deserialize with custom converter\n var rawDict = JsonSerializer.Deserialize>(fileStream);\n if ( rawDict == null )\n {\n throw new InvalidOperationException($\"Failed to deserialize lexicon from {path}\");\n }\n\n // Convert to strongly typed entries\n var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);\n foreach ( var (key, element) in rawDict )\n {\n if ( key.Length >= 2 )\n {\n dict[key] = PhonemeEntry.FromJsonElement(element);\n }\n }\n\n // Grow the dictionary with additional forms\n var extended = new Dictionary(StringComparer.OrdinalIgnoreCase);\n foreach ( var (key, value) in dict )\n {\n if ( key.Length < 2 )\n {\n continue;\n }\n\n if ( key == key.ToLower() )\n {\n var capitalized = LexiconUtils.Capitalize(key);\n if ( key != capitalized && !dict.ContainsKey(capitalized) )\n {\n extended[capitalized] = value;\n }\n }\n else if ( key == LexiconUtils.Capitalize(key.ToLower()) )\n {\n var lower = key.ToLower();\n if ( !dict.ContainsKey(lower) )\n {\n extended[lower] = value;\n }\n }\n }\n\n // Combine original and extended entries\n foreach ( var (key, value) in extended )\n {\n dict[key] = value;\n }\n\n // Return as frozen dictionary for performance\n return dict.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string? Phonemes, int? Rating) GetWord(\n string word,\n string tag,\n double? stress,\n TokenContext ctx,\n bool isHead,\n string? currency,\n string numFlags)\n {\n // Cache lookup - create a composite key for context-dependent lookups\n var cacheKey = $\"{word}|{tag}|{stress}|{ctx.FutureVowel}|{ctx.FutureTo}|{currency}|{numFlags}\";\n if ( _wordCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n // 1. Check special cases first\n var specialCase = GetSpecialCase(word, tag, stress, ctx);\n if ( specialCase.Phonemes != null )\n {\n var finalResult = (AppendCurrency(specialCase.Phonemes, currency), specialCase.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 2. Check if word is in dictionaries\n if ( IsKnown(word, tag) )\n {\n var result = Lookup(word, tag, stress, ctx);\n if ( result.Phonemes != null )\n {\n var finalResult = (ApplyStress(AppendCurrency(result.Phonemes, currency), stress), result.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 3. Check for apostrophe s at the end (possessives)\n if ( EndsWith(word, \"s'\") && IsKnown(word[..^2] + \"'s\", tag) )\n {\n var result = Lookup(word[..^2] + \"'s\", tag, stress, ctx);\n if ( result.Phonemes != null )\n {\n var finalResult = (AppendCurrency(result.Phonemes, currency), result.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 4. Check for words ending with apostrophe\n if ( EndsWith(word, \"'\") && IsKnown(word[..^1], tag) )\n {\n var result = Lookup(word[..^1], tag, stress, ctx);\n if ( result.Phonemes != null )\n {\n var finalResult = (AppendCurrency(result.Phonemes, currency), result.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 5. Try stemming for -s suffix\n var stemS = StemS(word, tag, stress, ctx);\n if ( stemS.Item1 != null )\n {\n var finalResult = (AppendCurrency(stemS.Item1, currency), stemS.Item2);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 6. Try stemming for -ed suffix\n var stemEd = StemEd(word, tag, stress, ctx);\n if ( stemEd.Item1 != null )\n {\n var finalResult = (AppendCurrency(stemEd.Item1, currency), stemEd.Item2);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 7. Try stemming for -ing suffix\n var stemIng = StemIng(word, tag, stress ?? 0.5, ctx);\n if ( stemIng.Item1 != null )\n {\n var finalResult = (AppendCurrency(stemIng.Item1, currency), stemIng.Item2);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 8. Handle numbers\n if ( IsNumber(word, isHead) )\n {\n var result = GetNumber(word, currency, isHead, numFlags);\n _wordCache[cacheKey] = result;\n\n return result;\n }\n\n // 9. Handle acronyms and capitalized words\n var isAllUpper = word.Length > 1 && word == word.ToUpper() && word.ToUpper() != word.ToLower();\n if ( isAllUpper )\n {\n var (nnpPhonemes, nnpRating) = GetNNP(word);\n if ( nnpPhonemes != null )\n {\n var finalResult = (AppendCurrency(nnpPhonemes, currency), nnpRating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 10. Try lowercase version if word has some uppercase letters\n if ( word != word.ToLower() && (word == word.ToUpper() || word[1..] == word[1..].ToLower()) )\n {\n var lowercaseResult = Lookup(word.ToLower(), tag, stress, ctx);\n if ( lowercaseResult.Phonemes != null )\n {\n var finalResult = (AppendCurrency(lowercaseResult.Phonemes, currency), lowercaseResult.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // No match found\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string? Phonemes, int? Rating) GetSpecialCase(string word, string tag, double? stress, TokenContext ctx)\n {\n // Handle special cases with optimized lookups\n var wordSpan = word.AsSpan();\n\n // Special symbols\n if ( tag == \"ADD\" && PhonemizerConstants.AddSymbols.TryGetValue(word, out var addSymbol) )\n {\n return Lookup(addSymbol, null, -0.5, ctx);\n }\n\n if ( PhonemizerConstants.Symbols.TryGetValue(word, out var symbol) )\n {\n return Lookup(symbol, null, null, ctx);\n }\n\n if ( wordSpan.Contains('.') && IsAllLettersOrDots(wordSpan) && MaxSubstringLength(wordSpan, '.') < 3 )\n {\n return GetNNP(word);\n }\n\n switch ( word )\n {\n case \"a\":\n case \"A\" when tag == \"DT\":\n return (\"ɐ\", 4);\n case \"I\" when tag == \"PRP\":\n return ($\"{PhonemizerConstants.SecondaryStress}I\", 4);\n case \"am\" or \"Am\" or \"AM\" when tag.StartsWith(\"NN\"):\n return GetNNP(word);\n case \"am\" or \"Am\" or \"AM\" when ctx.FutureVowel != null && word == \"am\" && stress is not > 0:\n return (\"ɐm\", 4);\n case \"am\" or \"Am\" or \"AM\" when _golds.TryGetValue(\"am\", out var amEntry) && amEntry is SimplePhonemeEntry simpleAm:\n return (simpleAm.Phoneme, 4);\n case \"am\" or \"Am\" or \"AM\":\n return (\"ɐm\", 4);\n case (\"an\" or \"An\" or \"AN\") and \"AN\" when tag.StartsWith(\"NN\"):\n return GetNNP(word);\n case \"an\" or \"An\" or \"AN\":\n return (\"ɐn\", 4);\n case \"by\" or \"By\" or \"BY\" when LexiconUtils.GetParentTag(tag) == \"ADV\":\n return (\"bˈI\", 4);\n case \"to\":\n case \"To\":\n case \"TO\" when tag is \"TO\" or \"IN\":\n switch ( ctx.FutureVowel )\n {\n case null:\n {\n if ( _golds.TryGetValue(\"to\", out var toEntry) && toEntry is SimplePhonemeEntry simpleTo )\n {\n return (simpleTo.Phoneme, 4);\n }\n\n break;\n }\n case false:\n return (\"tə\", 4);\n default:\n return (\"tʊ\", 4);\n }\n\n break;\n case \"the\":\n case \"The\":\n case \"THE\" when tag == \"DT\":\n return (ctx.FutureVowel == true ? \"ði\" : \"ðə\", 4);\n }\n\n if ( tag == \"IN\" && _vsRegex.IsMatch(word) )\n {\n return Lookup(\"versus\", null, null, ctx);\n }\n\n if ( word is \"used\" or \"Used\" or \"USED\" )\n {\n if ( tag is \"VBD\" or \"JJ\" && ctx.FutureTo )\n {\n if ( _golds.TryGetValue(\"used\", out var usedEntry) && usedEntry is ContextualPhonemeEntry contextualUsed )\n {\n return (contextualUsed.GetForm(\"VBD\", null), 4);\n }\n }\n\n if ( _golds.TryGetValue(\"used\", out var usedDefaultEntry) && usedDefaultEntry is ContextualPhonemeEntry contextualDefault )\n {\n return (contextualDefault.GetForm(\"DEFAULT\", null), 4);\n }\n }\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsAllLettersOrDots(ReadOnlySpan word)\n {\n foreach ( var c in word )\n {\n if ( c != '.' && !char.IsLetter(c) )\n {\n return false;\n }\n }\n\n return true;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private int MaxSubstringLength(ReadOnlySpan text, char separator)\n {\n var maxLength = 0;\n var start = 0;\n\n for ( var i = 0; i < text.Length; i++ )\n {\n if ( text[i] == separator )\n {\n maxLength = Math.Max(maxLength, i - start);\n start = i + 1;\n }\n }\n\n // Check the last segment\n maxLength = Math.Max(maxLength, text.Length - start);\n\n return maxLength;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string? Phonemes, int? Rating) Lookup(string word, string? tag, double? stress, TokenContext ctx)\n {\n var isNNP = false;\n if ( word == word.ToUpper() && !_golds.ContainsKey(word) )\n {\n word = word.ToLower();\n isNNP = tag == \"NNP\";\n }\n\n PhonemeEntry? entry = null;\n var rating = 4;\n\n if ( _golds.TryGetValue(word, out entry) )\n {\n // Found in gold dictionary\n }\n else if ( !isNNP && _silvers.TryGetValue(word, out entry) )\n {\n rating = 3;\n }\n\n if ( entry == null )\n {\n if ( isNNP )\n {\n return GetNNP(word);\n }\n\n return (null, null);\n }\n\n string? phonemes = null;\n\n switch ( entry )\n {\n case SimplePhonemeEntry simple:\n phonemes = simple.Phoneme;\n\n break;\n\n case ContextualPhonemeEntry contextual:\n phonemes = contextual.GetForm(tag, ctx);\n\n break;\n }\n\n if ( phonemes == null || (isNNP && !phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return GetNNP(word);\n }\n\n return (ApplyStress(phonemes, stress), rating);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsKnown(string word, string tag)\n {\n if ( _golds.ContainsKey(word) || PhonemizerConstants.Symbols.ContainsKey(word) || _silvers.ContainsKey(word) )\n {\n return true;\n }\n\n if ( !word.All(c => char.IsLetter(c)) || !word.All(IsValidCharacter) )\n {\n return false;\n }\n\n if ( word.Length == 1 )\n {\n return true;\n }\n\n if ( word == word.ToUpper() && _golds.ContainsKey(word.ToLower()) )\n {\n return true;\n }\n\n return word.Length > 1 && word[1..] == word[1..].ToUpper();\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsValidCharacter(char c)\n {\n // Check if character is valid for lexicon\n return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '\\'' || c == '-' || c == '_';\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string ApplyStress(string phonemes, double? stress)\n {\n if ( phonemes == null )\n {\n return \"\";\n }\n\n if ( stress == null )\n {\n return phonemes;\n }\n\n // Early return conditions\n if ( (stress == 0 || stress == 1) && !ContainsStressMarkers(phonemes) )\n {\n return phonemes;\n }\n\n // Remove all stress for very negative stress\n if ( stress < -1 )\n {\n return phonemes\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty);\n }\n\n // Lower stress level for -1 or 0\n if ( stress == -1 || (stress is 0 or -0.5 && phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return phonemes\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), PhonemizerConstants.SecondaryStress.ToString());\n }\n\n // Add secondary stress for unstressed phonemes\n if ( stress is 0 or 0.5 or 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !ContainsVowel(phonemes) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.SecondaryStress + phonemes);\n }\n\n // Upgrade secondary stress to primary\n if ( stress >= 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n return phonemes.Replace(\n PhonemizerConstants.SecondaryStress.ToString(),\n PhonemizerConstants.PrimaryStress.ToString());\n }\n\n // Add primary stress for high stress values\n if ( stress > 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !ContainsVowel(phonemes) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.PrimaryStress + phonemes);\n }\n\n return phonemes;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool ContainsStressMarkers(string phonemes)\n {\n return phonemes.Contains(PhonemizerConstants.PrimaryStress) ||\n phonemes.Contains(PhonemizerConstants.SecondaryStress);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool ContainsVowel(string phonemes) { return phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)); }\n\n private string RestressPhonemes(string phonemes)\n {\n // Optimization: Avoid allocations if there are no stress markers\n if ( !ContainsStressMarkers(phonemes) )\n {\n return phonemes;\n }\n\n var chars = phonemes.ToCharArray();\n var charPositions = new List<(int Position, char Char)>(chars.Length);\n\n for ( var i = 0; i < chars.Length; i++ )\n {\n charPositions.Add((i, chars[i]));\n }\n\n var stressPositions = new Dictionary();\n for ( var i = 0; i < charPositions.Count; i++ )\n {\n if ( PhonemizerConstants.Stresses.Contains(charPositions[i].Char) )\n {\n // Find the next vowel\n var vowelPos = -1;\n for ( var j = i + 1; j < charPositions.Count; j++ )\n {\n if ( PhonemizerConstants.Vowels.Contains(charPositions[j].Char) )\n {\n vowelPos = j;\n\n break;\n }\n }\n\n if ( vowelPos != -1 )\n {\n stressPositions[charPositions[i].Position] = charPositions[vowelPos].Position;\n charPositions[i] = ((int)(vowelPos - 0.5), charPositions[i].Char);\n }\n }\n }\n\n charPositions.Sort((a, b) => a.Position.CompareTo(b.Position));\n\n return new string(charPositions.Select(cp => cp.Char).ToArray());\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool EndsWith(string word, string suffix) { return word.Length > suffix.Length && word.EndsWith(suffix, StringComparison.Ordinal); }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) GetNNP(string word)\n {\n // Early exit for extremely short or long words\n if ( word.Length < 1 || word.Length > 20 )\n {\n return (null, null);\n }\n\n // Cache lookups for acronyms\n var cacheKey = $\"NNP_{word}\";\n if ( _wordCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n // Collect phonemes for each letter\n var phoneticLetters = new List();\n\n foreach ( var c in word )\n {\n if ( !char.IsLetter(c) )\n {\n continue;\n }\n\n if ( _golds.TryGetValue(c.ToString().ToUpper(), out var letterEntry) )\n {\n if ( letterEntry is SimplePhonemeEntry simpleEntry )\n {\n phoneticLetters.Add(simpleEntry.Phoneme);\n }\n else\n {\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n }\n else\n {\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n }\n\n if ( phoneticLetters.Count == 0 )\n {\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n // Join and apply stress\n var phonemes = string.Join(\"\", phoneticLetters);\n var result = ApplyStress(phonemes, 0);\n\n // Split by secondary stress and join with primary stress\n // This matches the Python implementation more closely\n var parts = result.Split(PhonemizerConstants.SecondaryStress);\n if ( parts.Length > 1 )\n {\n // Taking only the last split, as in Python's rsplit(SECONDARY_STRESS, 1)\n var lastIdx = result.LastIndexOf(PhonemizerConstants.SecondaryStress);\n var beginning = result.Substring(0, lastIdx);\n var end = result.Substring(lastIdx + 1);\n result = beginning + PhonemizerConstants.PrimaryStress + end;\n }\n\n _wordCache[cacheKey] = (result, 3);\n\n return (result, 3);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string? S(string? stem)\n {\n // https://en.wiktionary.org/wiki/-s\n if ( string.IsNullOrEmpty(stem) )\n {\n return null;\n }\n\n // Cache result for frequently used stems\n var cacheKey = $\"S_{stem}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) && cached.Phonemes != null )\n {\n return cached.Phonemes;\n }\n\n string? result;\n if ( \"ptkfθ\".Contains(stem[^1]) )\n {\n result = stem + \"s\";\n }\n else if ( \"szʃʒʧʤ\".Contains(stem[^1]) )\n {\n result = stem + (_british ? \"ɪ\" : \"ᵻ\") + \"z\";\n }\n else\n {\n result = stem + \"z\";\n }\n\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) StemS(string word, string tag, double? stress, TokenContext ctx)\n {\n // Cache lookup\n var cacheKey = $\"StemS_{word}_{tag}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n string stem;\n\n if ( word.Length > 2 && EndsWith(word, \"s\") && !EndsWith(word, \"ss\") && IsKnown(word[..^1], tag) )\n {\n stem = word[..^1];\n }\n else if ( (EndsWith(word, \"'s\") ||\n (word.Length > 4 && EndsWith(word, \"es\") && !EndsWith(word, \"ies\"))) &&\n IsKnown(word[..^2], tag) )\n {\n stem = word[..^2];\n }\n else if ( word.Length > 4 && EndsWith(word, \"ies\") && IsKnown(word[..^3] + \"y\", tag) )\n {\n stem = word[..^3] + \"y\";\n }\n else\n {\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n var (stemPhonemes, rating) = Lookup(stem, tag, stress, ctx);\n if ( stemPhonemes != null )\n {\n var result = (S(stemPhonemes), rating);\n _stemCache[cacheKey] = result;\n\n return result;\n }\n\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string? Ed(string? stem)\n {\n // https://en.wiktionary.org/wiki/-ed\n if ( string.IsNullOrEmpty(stem) )\n {\n return null;\n }\n\n // Cache result for frequently used stems\n var cacheKey = $\"Ed_{stem}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) && cached.Phonemes != null )\n {\n return cached.Phonemes;\n }\n\n string? result;\n if ( \"pkfθʃsʧ\".Contains(stem[^1]) )\n {\n result = stem + \"t\";\n }\n else if ( stem[^1] == 'd' )\n {\n result = stem + (_british ? \"ɪ\" : \"ᵻ\") + \"d\";\n }\n else if ( stem[^1] != 't' )\n {\n result = stem + \"d\";\n }\n else if ( _british || stem.Length < 2 )\n {\n result = stem + \"ɪd\";\n }\n else if ( PhonemizerConstants.UsTaus.Contains(stem[^2]) )\n {\n result = stem[..^1] + \"ɾᵻd\";\n }\n else\n {\n result = stem + \"ᵻd\";\n }\n\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) StemEd(string word, string tag, double? stress, TokenContext ctx)\n {\n // Cache lookup\n var cacheKey = $\"StemEd_{word}_{tag}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n string stem;\n\n if ( EndsWith(word, \"d\") && !EndsWith(word, \"dd\") && IsKnown(word[..^1], tag) )\n {\n stem = word[..^1];\n }\n else if ( EndsWith(word, \"ed\") && !EndsWith(word, \"eed\") && IsKnown(word[..^2], tag) )\n {\n stem = word[..^2];\n }\n else\n {\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n var (stemPhonemes, rating) = Lookup(stem, tag, stress, ctx);\n if ( stemPhonemes != null )\n {\n var result = (Ed(stemPhonemes), rating);\n _stemCache[cacheKey] = result;\n\n return result;\n }\n\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string? Ing(string? stem)\n {\n if ( string.IsNullOrEmpty(stem) )\n {\n return null;\n }\n\n // Cache result for frequently used stems\n var cacheKey = $\"Ing_{stem}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) && cached.Phonemes != null )\n {\n return cached.Phonemes;\n }\n\n string? result;\n if ( _british )\n {\n if ( stem[^1] == 'ə' || stem[^1] == 'ː' )\n {\n _stemCache[cacheKey] = (null, null);\n\n return null;\n }\n }\n else if ( stem.Length > 1 && stem[^1] == 't' && PhonemizerConstants.UsTaus.Contains(stem[^2]) )\n {\n result = stem[..^1] + \"ɾɪŋ\";\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n result = stem + \"ɪŋ\";\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) StemIng(string word, string tag, double stress, TokenContext ctx)\n {\n // Cache lookup\n var cacheKey = $\"StemIng_{word}_{tag}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n string stem;\n\n if ( EndsWith(word, \"ing\") && IsKnown(word[..^3], tag) )\n {\n stem = word[..^3];\n }\n else if ( EndsWith(word, \"ing\") && IsKnown(word[..^3] + \"e\", tag) )\n {\n stem = word[..^3] + \"e\";\n }\n else if ( _doubleConsonantIngRegex.IsMatch(word) && IsKnown(word[..^4], tag) )\n {\n stem = word[..^4];\n }\n else\n {\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n var (stemPhonemes, rating) = Lookup(stem, tag, stress, ctx);\n if ( stemPhonemes != null )\n {\n var result = (Ing(stemPhonemes), rating);\n _stemCache[cacheKey] = result;\n\n return result;\n }\n\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsNumber(string word, bool isHead)\n {\n // Quick check for any digit\n if ( !word.Any(char.IsDigit) )\n {\n return false;\n }\n\n // Check for valid number format with possible suffixes\n var end = word.Length;\n\n // Check for common suffixes\n foreach ( var suffix in PhonemizerConstants.Ordinals )\n {\n if ( EndsWith(word, suffix) )\n {\n end -= suffix.Length;\n\n break;\n }\n }\n\n if ( EndsWith(word, \"'s\") )\n {\n end -= 2;\n }\n else if ( EndsWith(word, \"s\") )\n {\n end -= 1;\n }\n else if ( EndsWith(word, \"ing\") )\n {\n end -= 3;\n }\n else if ( EndsWith(word, \"'d\") || EndsWith(word, \"ed\") )\n {\n end -= 2;\n }\n\n // Validate characters in the number portion\n for ( var i = 0; i < end; i++ )\n {\n var c = word[i];\n if ( !(char.IsDigit(c) || c == ',' || c == '.' || (isHead && i == 0 && c == '-')) )\n {\n return false;\n }\n }\n\n return true;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static bool IsCurrency(string word)\n {\n if ( !word.Contains('.') )\n {\n return true;\n }\n\n if ( word.Count(c => c == '.') > 1 )\n {\n return false;\n }\n\n var cents = word.Split('.')[1];\n\n return cents.Length < 3 || cents.All(c => c == '0');\n }\n\n private (string?, int?) GetNumber(string word, string? currency, bool isHead, string numFlags)\n {\n // Process suffix (like 'st', 'nd', 'rd', 'th')\n var suffixMatch = _suffixRegex.Match(word);\n var suffix = suffixMatch.Success ? suffixMatch.Value : null;\n\n if ( suffix != null )\n {\n word = word[..^suffix.Length];\n }\n\n var result = new List<(string Phoneme, int Rating)>();\n\n // Handle negative numbers\n if ( word.StartsWith('-') )\n {\n ExtendResult(\"minus\");\n word = word[1..];\n }\n\n // Main number processing logic\n if ( !isHead && !word.Contains('.') )\n {\n var num = word.Replace(\",\", \"\");\n\n // Handle leading zeros or longer numbers digit by digit\n if ( num[0] == '0' || num.Length > 3 )\n {\n foreach ( var digit in num )\n {\n if ( !ExtendResult(digit.ToString(), false) )\n {\n return (null, null);\n }\n }\n }\n // Handle 3-digit numbers that don't end with \"00\"\n else if ( num.Length == 3 && !num.EndsWith(\"00\") )\n {\n // Handle first digit + \"hundred\"\n if ( !ExtendResult(num[0].ToString()) )\n {\n return (null, null);\n }\n\n if ( !ExtendResult(\"hundred\") )\n {\n return (null, null);\n }\n\n // Handle remaining digits\n if ( num[1] == '0' )\n {\n // Special case: x0y\n if ( !ExtendResult(\"O\", specialRating: -2) )\n {\n return (null, null);\n }\n\n if ( !ExtendResult(num[2].ToString(), false) )\n {\n return (null, null);\n }\n }\n else\n {\n // Handle last two digits as a number\n if ( !ExtendNum(int.Parse(num.Substring(1, 2)), false) )\n {\n return (null, null);\n }\n }\n }\n else\n {\n // Standard number conversion\n if ( !ExtendNum(int.Parse(num)) )\n {\n return (null, null);\n }\n }\n }\n else if ( word.Count(c => c == '.') > 1 || !isHead )\n {\n // Handle multiple decimal points or non-head position\n var parts = word.Replace(\",\", \"\").Split('.');\n var isFirst = true;\n\n foreach ( var part in parts )\n {\n if ( string.IsNullOrEmpty(part) )\n {\n continue;\n }\n\n if ( part[0] == '0' || (part.Length != 2 && part.Any(n => n != '0')) )\n {\n // Handle digit by digit\n foreach ( var digit in part )\n {\n if ( !ExtendResult(digit.ToString(), false) )\n {\n return (null, null);\n }\n }\n }\n else\n {\n // Standard number conversion\n if ( !ExtendNum(int.Parse(part), isFirst) )\n {\n return (null, null);\n }\n }\n\n isFirst = false;\n }\n }\n else if ( currency != null && PhonemizerConstants.Currencies.TryGetValue(currency, out var currencyPair) && IsCurrency(word) )\n {\n // Parse the parts\n var parts = word.Replace(\",\", \"\")\n .Split('.')\n .Select(p => string.IsNullOrEmpty(p) ? 0 : int.Parse(p))\n .ToList();\n\n while ( parts.Count < 2 )\n {\n parts.Add(0);\n }\n\n // Filter out zero parts\n var nonZeroParts = parts.Take(2)\n .Select((value, index) => (Value: value, Unit: index == 0 ? currencyPair.Dollar : currencyPair.Cent))\n .Where(p => p.Value != 0)\n .ToList();\n\n for ( var i = 0; i < nonZeroParts.Count; i++ )\n {\n var (value, unit) = nonZeroParts[i];\n\n if ( i > 0 && !ExtendResult(\"and\") )\n {\n return (null, null);\n }\n\n // Convert number to words\n if ( !ExtendNum(value, i == 0) )\n {\n return (null, null);\n }\n\n // Add currency unit\n if ( Math.Abs(value) != 1 && unit != \"pence\" )\n {\n var (unitPhonemes, unitRating) = StemS(unit + \"s\", null, null, null);\n if ( unitPhonemes != null )\n {\n result.Add((unitPhonemes, unitRating.Value));\n }\n else\n {\n return (null, null);\n }\n }\n else\n {\n if ( !ExtendResult(unit) )\n {\n return (null, null);\n }\n }\n }\n }\n else\n {\n // Standard number handling for most cases\n string wordsForm;\n\n if ( int.TryParse(word.Replace(\",\", \"\"), out var number) )\n {\n // Choose conversion type\n var to = \"cardinal\";\n if ( suffix != null && PhonemizerConstants.Ordinals.Contains(suffix) )\n {\n to = \"ordinal\";\n }\n else if ( result.Count == 0 && word.Length == 4 )\n {\n to = \"year\";\n }\n\n wordsForm = Num2Words.Convert(number, to);\n }\n else if ( double.TryParse(word.Replace(\",\", \"\"), out var numberDouble) )\n {\n if ( word.StartsWith(\".\") )\n {\n // Handle \".xx\" format\n wordsForm = \"point \" + string.Join(\" \", word[1..].Select(c => Num2Words.Convert(int.Parse(c.ToString()))));\n }\n else\n {\n wordsForm = Num2Words.Convert(numberDouble);\n }\n }\n else\n {\n return (null, null);\n }\n\n // Process the words form\n if ( !ExtendNum(wordsForm, escape: true) )\n {\n return (null, null);\n }\n }\n\n if ( result.Count == 0 )\n {\n return (null, null);\n }\n\n // Join the phonemes and handle suffix\n var combinedPhoneme = string.Join(\" \", result.Select(r => r.Phoneme));\n var minRating = result.Min(r => r.Rating);\n\n // Apply suffix transformations\n return suffix switch {\n \"s\" or \"'s\" => (S(combinedPhoneme), minRating),\n \"ed\" or \"'d\" => (Ed(combinedPhoneme), minRating),\n \"ing\" => (Ing(combinedPhoneme), minRating),\n _ => (combinedPhoneme, minRating)\n };\n\n // Helper method to extend number words\n bool ExtendNum(object num, bool first = true, bool escape = false)\n {\n var wordsForm = escape ? num.ToString()! : Num2Words.Convert(Convert.ToInt32(num));\n var splits = wordsForm.Split(new[] { ' ', '-' }, StringSplitOptions.RemoveEmptyEntries);\n\n for ( var i = 0; i < splits.Length; i++ )\n {\n var w = splits[i];\n\n if ( w != \"and\" || numFlags.Contains('&') )\n {\n if ( first && i == 0 && splits.Length > 1 && w == \"one\" && numFlags.Contains('a') )\n {\n result.Add((\"ə\", 4));\n }\n else\n {\n double? specialRating = w == \"point\" ? -2.0 : null;\n var (wordPhoneme, wordRating) = Lookup(w, null, specialRating, null);\n if ( wordPhoneme != null )\n {\n result.Add((wordPhoneme, wordRating.Value));\n }\n else\n {\n return false;\n }\n }\n }\n else if ( w == \"and\" && numFlags.Contains('n') && result.Count > 0 )\n {\n // Append \"ən\" to the previous word\n var last = result[^1];\n result[^1] = (last.Phoneme + \"ən\", last.Rating);\n }\n }\n\n return true;\n }\n\n // Helper method to add a single word result\n bool ExtendResult(string word, bool first = true, double? specialRating = null)\n {\n var (phoneme, rating) = Lookup(word, null, specialRating, null);\n if ( phoneme != null )\n {\n result.Add((phoneme, rating.Value));\n\n return true;\n }\n\n return false;\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string AppendCurrency(string phonemes, string? currency)\n {\n if ( string.IsNullOrEmpty(currency) )\n {\n return phonemes;\n }\n\n if ( !PhonemizerConstants.Currencies.TryGetValue(currency, out var currencyPair) )\n {\n return phonemes;\n }\n\n var (stemPhonemes, _) = StemS(currencyPair.Dollar + \"s\", null, null, null);\n if ( stemPhonemes != null )\n {\n return $\"{phonemes} {stemPhonemes}\";\n }\n\n return phonemes;\n }\n\n [GeneratedRegex(@\"(?i)vs\\.?$\", RegexOptions.Compiled, \"en-BE\")]\n private static partial Regex VersusRegex();\n\n [GeneratedRegex(@\"([bcdgklmnprstvxz])\\1ing$|cking$\", RegexOptions.Compiled)]\n private static partial Regex DoubleConsonantIngRegex();\n\n [GeneratedRegex(@\"[a-z']+$\", RegexOptions.Compiled)]\n private static partial Regex SuffixRegex();\n}\n\npublic class LruCache(int capacity, IEqualityComparer comparer)\n where TKey : notnull\n{\n private readonly Dictionary> _cacheMap = new(capacity, comparer);\n\n private readonly LinkedList _lruList = new();\n\n public TValue this[TKey key]\n {\n get\n {\n if ( _cacheMap.TryGetValue(key, out var node) )\n {\n _lruList.Remove(node);\n _lruList.AddFirst(node);\n\n return node.Value.Value;\n }\n\n throw new KeyNotFoundException($\"Key {key} not found in cache\");\n }\n\n set\n {\n if ( _cacheMap.TryGetValue(key, out var existingNode) )\n {\n _lruList.Remove(existingNode);\n _lruList.AddFirst(existingNode);\n existingNode.Value.Value = value;\n\n return;\n }\n\n if ( _cacheMap.Count >= capacity )\n {\n var last = _lruList.Last;\n if ( last != null )\n {\n _cacheMap.Remove(last.Value.Key);\n _lruList.RemoveLast();\n }\n }\n\n var cacheItem = new LruCacheItem(key, value);\n var newNode = new LinkedListNode(cacheItem);\n _lruList.AddFirst(newNode);\n _cacheMap.Add(key, newNode);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public bool TryGetValue(TKey key, out TValue value)\n {\n if ( _cacheMap.TryGetValue(key, out var node) )\n {\n _lruList.Remove(node);\n _lruList.AddFirst(node);\n\n value = node.Value.Value;\n\n return true;\n }\n\n value = default!;\n\n return false;\n }\n\n public void Clear()\n {\n _cacheMap.Clear();\n _lruList.Clear();\n }\n\n private record LruCacheItem(TKey Key, TValue Value)\n {\n public TValue Value { get; set; } = Value;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismExpressionMotion.cs", "using System.Text.Json.Nodes;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// 表情のモーションクラス。\n/// \npublic class CubismExpressionMotion : ACubismMotion\n{\n /// \n /// 加算適用の初期値\n /// \n public const float DefaultAdditiveValue = 0.0f;\n\n /// \n /// 乗算適用の初期値\n /// \n public const float DefaultMultiplyValue = 1.0f;\n\n public const string ExpressionKeyFadeIn = \"FadeInTime\";\n\n public const string ExpressionKeyFadeOut = \"FadeOutTime\";\n\n public const string ExpressionKeyParameters = \"Parameters\";\n\n public const string ExpressionKeyId = \"Id\";\n\n public const string ExpressionKeyValue = \"Value\";\n\n public const string ExpressionKeyBlend = \"Blend\";\n\n public const string BlendValueAdd = \"Add\";\n\n public const string BlendValueMultiply = \"Multiply\";\n\n public const string BlendValueOverwrite = \"Overwrite\";\n\n public const float DefaultFadeTime = 1.0f;\n\n /// \n /// インスタンスを作成する。\n /// \n /// expファイルが読み込まれているバッファ\n public CubismExpressionMotion(string buf)\n {\n using var stream = File.Open(buf, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonNode.Parse(stream) ?? throw new Exception(\"Load ExpressionMotion error\");\n var json = obj.AsObject();\n\n FadeInSeconds = json.ContainsKey(ExpressionKeyFadeIn)\n ? (float)json[ExpressionKeyFadeIn]!\n : DefaultFadeTime; // フェードイン\n\n FadeOutSeconds = json.ContainsKey(ExpressionKeyFadeOut)\n ? (float)json[ExpressionKeyFadeOut]!\n : DefaultFadeTime; // フェードアウト\n\n if ( FadeInSeconds < 0.0f )\n {\n FadeInSeconds = DefaultFadeTime;\n }\n\n if ( FadeOutSeconds < 0.0f )\n {\n FadeOutSeconds = DefaultFadeTime;\n }\n\n // 各パラメータについて\n var list = json[ExpressionKeyParameters]!;\n var parameterCount = list.AsArray().Count;\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n var param = list[i]!;\n var parameterId = CubismFramework.CubismIdManager.GetId(param[ExpressionKeyId]!.ToString()); // パラメータID\n var value = (float)param[ExpressionKeyValue]!; // 値\n\n // 計算方法の設定\n ExpressionBlendType blendType;\n var type = param[ExpressionKeyBlend]?.ToString();\n if ( type == null || type == BlendValueAdd )\n {\n blendType = ExpressionBlendType.Add;\n }\n else if ( type == BlendValueMultiply )\n {\n blendType = ExpressionBlendType.Multiply;\n }\n else if ( type == BlendValueOverwrite )\n {\n blendType = ExpressionBlendType.Overwrite;\n }\n else\n {\n // その他 仕様にない値を設定したときは加算モードにすることで復旧\n blendType = ExpressionBlendType.Add;\n }\n\n // 設定オブジェクトを作成してリストに追加する\n Parameters.Add(new ExpressionParameter { ParameterId = parameterId, BlendType = blendType, Value = value });\n }\n }\n\n /// \n /// 表情のパラメータ情報リスト\n /// \n public List Parameters { get; init; } = [];\n\n /// \n /// 表情のフェードのウェイト値\n /// \n [Obsolete(\"CubismExpressionMotion._fadeWeightが削除予定のため非推奨\\nCubismExpressionMotionManager.getFadeWeight(int index) を使用してください。\")]\n public float FadeWeight { get; private set; }\n\n public override void DoUpdateParameters(CubismModel model, float userTimeSeconds, float weight, CubismMotionQueueEntry motionQueueEntry)\n {\n foreach ( var item in Parameters )\n {\n switch ( item.BlendType )\n {\n case ExpressionBlendType.Add:\n {\n model.AddParameterValue(item.ParameterId, item.Value, weight); // 相対変化 加算\n\n break;\n }\n case ExpressionBlendType.Multiply:\n {\n model.MultiplyParameterValue(item.ParameterId, item.Value, weight); // 相対変化 乗算\n\n break;\n }\n case ExpressionBlendType.Overwrite:\n {\n model.SetParameterValue(item.ParameterId, item.Value, weight); // 絶対変化 上書き\n\n break;\n }\n }\n }\n }\n\n /// \n /// モデルの表情に関するパラメータを計算する。\n /// \n /// 対象のモデル\n /// 対象のモデル\n /// CubismMotionQueueManagerで管理されているモーション\n /// モデルに適用する各パラメータの値\n /// 表情のインデックス\n public void CalculateExpressionParameters(CubismModel model, float userTimeSeconds, CubismMotionQueueEntry? motionQueueEntry,\n List? expressionParameterValues, int expressionIndex, float fadeWeight)\n {\n if ( motionQueueEntry == null || expressionParameterValues == null )\n {\n return;\n }\n\n if ( !motionQueueEntry.Available )\n {\n return;\n }\n\n // CubismExpressionMotion._fadeWeight は廃止予定です。\n // 互換性のために処理は残りますが、実際には使用しておりません。\n FadeWeight = UpdateFadeWeight(motionQueueEntry, userTimeSeconds);\n\n // モデルに適用する値を計算\n for ( var i = 0; i < expressionParameterValues.Count; ++i )\n {\n var expressionParameterValue = expressionParameterValues[i];\n\n if ( expressionParameterValue.ParameterId == null )\n {\n continue;\n }\n\n var currentParameterValue = expressionParameterValue.OverwriteValue =\n model.GetParameterValue(expressionParameterValue.ParameterId);\n\n var expressionParameters = Parameters;\n var parameterIndex = -1;\n for ( var j = 0; j < expressionParameters.Count; ++j )\n {\n if ( expressionParameterValue.ParameterId != expressionParameters[j].ParameterId )\n {\n continue;\n }\n\n parameterIndex = j;\n\n break;\n }\n\n // 再生中のExpressionが参照していないパラメータは初期値を適用\n if ( parameterIndex < 0 )\n {\n if ( expressionIndex == 0 )\n {\n expressionParameterValues[i].AdditiveValue = DefaultAdditiveValue;\n\n expressionParameterValues[i].MultiplyValue = DefaultMultiplyValue;\n\n expressionParameterValues[i].OverwriteValue = currentParameterValue;\n }\n else\n {\n expressionParameterValues[i].AdditiveValue =\n CalculateValue(expressionParameterValue.AdditiveValue, DefaultAdditiveValue, fadeWeight);\n\n expressionParameterValues[i].MultiplyValue =\n CalculateValue(expressionParameterValue.MultiplyValue, DefaultMultiplyValue, fadeWeight);\n\n expressionParameterValues[i].OverwriteValue =\n CalculateValue(expressionParameterValue.OverwriteValue, currentParameterValue, fadeWeight);\n }\n\n continue;\n }\n\n // 値を計算\n var value = expressionParameters[parameterIndex].Value;\n float newAdditiveValue,\n newMultiplyValue,\n newSetValue;\n\n switch ( expressionParameters[parameterIndex].BlendType )\n {\n case ExpressionBlendType.Add:\n newAdditiveValue = value;\n newMultiplyValue = DefaultMultiplyValue;\n newSetValue = currentParameterValue;\n\n break;\n case ExpressionBlendType.Multiply:\n newAdditiveValue = DefaultAdditiveValue;\n newMultiplyValue = value;\n newSetValue = currentParameterValue;\n\n break;\n case ExpressionBlendType.Overwrite:\n newAdditiveValue = DefaultAdditiveValue;\n newMultiplyValue = DefaultMultiplyValue;\n newSetValue = value;\n\n break;\n default:\n return;\n }\n\n if ( expressionIndex == 0 )\n {\n expressionParameterValues[i].AdditiveValue = newAdditiveValue;\n expressionParameterValues[i].MultiplyValue = newMultiplyValue;\n expressionParameterValues[i].OverwriteValue = newSetValue;\n }\n else\n {\n expressionParameterValues[i].AdditiveValue = expressionParameterValue.AdditiveValue * (1.0f - FadeWeight) + newAdditiveValue * FadeWeight;\n expressionParameterValues[i].MultiplyValue = expressionParameterValue.MultiplyValue * (1.0f - FadeWeight) + newMultiplyValue * FadeWeight;\n expressionParameterValues[i].OverwriteValue = expressionParameterValue.OverwriteValue * (1.0f - FadeWeight) + newSetValue * FadeWeight;\n }\n }\n }\n\n private float CalculateValue(float source, float destination, float fadeWeight) { return source * (1.0f - fadeWeight) + destination * fadeWeight; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Session/ConfigureStateMachine.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\nusing Stateless;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Session;\n\npublic partial class ConversationSession\n{\n private readonly StateMachine _stateMachine;\n\n private StateMachine.TriggerWithParameters _inputDetectedTrigger = null!;\n\n private StateMachine.TriggerWithParameters _inputFinalizedTrigger = null!;\n\n private void ConfigureStateMachine()\n {\n _inputDetectedTrigger = _stateMachine.SetTriggerParameters(ConversationTrigger.InputDetected);\n _inputFinalizedTrigger = _stateMachine.SetTriggerParameters(ConversationTrigger.InputFinalized);\n\n var llmChunkReceivedTrigger = _stateMachine.SetTriggerParameters(ConversationTrigger.LlmStreamChunkReceived);\n var ttsChunkReceivedTrigger = _stateMachine.SetTriggerParameters(ConversationTrigger.TtsStreamChunkReceived);\n var errorOccurredTrigger = _stateMachine.SetTriggerParameters(ConversationTrigger.ErrorOccurred);\n\n _stateMachine.Configure(ConversationState.Initial)\n .Permit(ConversationTrigger.InitializeRequested, ConversationState.Initializing)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.Initializing)\n .OnEntryAsync(InitializeSessionAsync, \"Initialize Session Resources\")\n .Permit(ConversationTrigger.InitializeComplete, ConversationState.Idle)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended);\n\n _stateMachine.Configure(ConversationState.Idle)\n .OnEntry(HandleIdle, \"Handle Idle State\")\n .Ignore(ConversationTrigger.LlmStreamEnded)\n .Ignore(ConversationTrigger.TtsStreamEnded)\n .Ignore(ConversationTrigger.AudioStreamEnded)\n .Permit(ConversationTrigger.InputDetected, ConversationState.Listening)\n .Permit(ConversationTrigger.InputFinalized, ConversationState.ProcessingInput)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.Listening)\n .SubstateOf(ConversationState.Idle)\n .Permit(ConversationTrigger.InputFinalized, ConversationState.ProcessingInput)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.PauseRequested, ConversationState.Paused)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error)\n .Ignore(ConversationTrigger.InputDetected);\n\n _stateMachine.Configure(ConversationState.ActiveTurn)\n .PermitIf(_inputDetectedTrigger, ConversationState.Interrupted,\n ShouldAllowBargeIn, \"Barge-In\")\n .PermitIf(_inputFinalizedTrigger, ConversationState.Interrupted,\n ShouldAllowBargeIn, \"Barge-In\");\n\n _stateMachine.Configure(ConversationState.ProcessingInput)\n .SubstateOf(ConversationState.ActiveTurn)\n .OnEntryFromAsync(_inputFinalizedTrigger, PrepareLlmRequestAsync, \"Process Input and Call LLM\")\n .Ignore(ConversationTrigger.LlmStreamEnded)\n .Ignore(ConversationTrigger.TtsStreamEnded)\n .Ignore(ConversationTrigger.AudioStreamEnded)\n .Permit(ConversationTrigger.LlmRequestSent, ConversationState.WaitingForLlm)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.WaitingForLlm)\n .SubstateOf(ConversationState.ActiveTurn)\n .OnEntryFrom(ConversationTrigger.LlmRequestSent, HandleLlmStreamRequested, \"Start LLM\")\n .InternalTransition(ConversationTrigger.TtsRequestSent, HandleTtsStreamRequest)\n .Permit(ConversationTrigger.LlmStreamStarted, ConversationState.StreamingResponse)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.StreamingResponse)\n .SubstateOf(ConversationState.ActiveTurn)\n .InternalTransitionAsync(llmChunkReceivedTrigger, HandleLlmStreamChunkReceived)\n .InternalTransitionAsync(ttsChunkReceivedTrigger, HandleTtsStreamChunkReceived)\n .InternalTransition(ConversationTrigger.TtsStreamEnded, HandleTtsStreamEnded)\n .InternalTransition(ConversationTrigger.LlmStreamEnded, HandleLlmStreamEnded)\n .Ignore(ConversationTrigger.TtsStreamStarted)\n .Permit(ConversationTrigger.AudioStreamStarted, ConversationState.Speaking)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.Speaking)\n .SubstateOf(ConversationState.ActiveTurn)\n .OnExit(CommitSpokenText)\n .InternalTransitionAsync(llmChunkReceivedTrigger, HandleLlmStreamChunkReceived)\n .InternalTransitionAsync(ttsChunkReceivedTrigger, HandleTtsStreamChunkReceived)\n .InternalTransition(ConversationTrigger.TtsStreamStarted, HandleTtsStreamRequest)\n .InternalTransition(ConversationTrigger.TtsStreamEnded, HandleTtsStreamEnded)\n .InternalTransition(ConversationTrigger.LlmStreamEnded, HandleLlmStreamEnded)\n .Permit(ConversationTrigger.AudioStreamEnded, ConversationState.Idle)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.Interrupted)\n .OnEntryFromAsync(_inputDetectedTrigger, HandleInterruptionCancelAndRefireAsync, \"Handle Detected Interruption, Cancel, Refire\")\n .OnEntryFromAsync(_inputFinalizedTrigger, HandleInterruptionCancelAndRefireAsync, \"Handle Finalized Interruption, Cancel, Refire\")\n .OnExitAsync(CancelCurrentTurnProcessingAsync)\n .Ignore(ConversationTrigger.TtsRequestSent)\n .Ignore(ConversationTrigger.LlmStreamChunkReceived)\n .Ignore(ConversationTrigger.TtsStreamChunkReceived)\n .Ignore(ConversationTrigger.LlmStreamStarted)\n .Ignore(ConversationTrigger.TtsStreamStarted)\n .Ignore(ConversationTrigger.AudioStreamStarted)\n .Ignore(ConversationTrigger.LlmStreamEnded)\n .Ignore(ConversationTrigger.TtsStreamEnded)\n .Ignore(ConversationTrigger.AudioStreamEnded)\n .Permit(ConversationTrigger.InputDetected, ConversationState.Listening)\n .Permit(ConversationTrigger.InputFinalized, ConversationState.ProcessingInput)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error);\n\n _stateMachine.Configure(ConversationState.Paused)\n .OnEntryAsync(PauseActivitiesAsync, \"Pause Adapters/Activities\")\n .Permit(ConversationTrigger.ResumeRequested, ConversationState.Idle)\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Permit(ConversationTrigger.ErrorOccurred, ConversationState.Error)\n .OnExitAsync(ResumeActivitiesAsync, \"Resume Adapters/Activities\");\n\n _stateMachine.Configure(ConversationState.Error)\n .OnEntryFromAsync(errorOccurredTrigger, HandleErrorAsync, \"Log Error and Update Context\")\n .OnEntryAsync(CancelCurrentTurnProcessingAsync, \"Ensure Pipeline Cancelled on Error\")\n .Permit(ConversationTrigger.StopRequested, ConversationState.Ended)\n .Ignore(ConversationTrigger.ErrorOccurred);\n\n _stateMachine.Configure(ConversationState.Ended)\n .OnEntryAsync(CancelCurrentTurnProcessingAsync, \"Ensure Pipeline Cancelled on End\")\n .OnEntryAsync(CleanupSessionAsync, \"Stop Adapters and Cleanup Resources\");\n\n _stateMachine.OnUnhandledTriggerAsync(async (state, trigger, unmetGuards) =>\n {\n if ( _stateMachine.IsInState(ConversationState.Ended) || _stateMachine.IsInState(ConversationState.Error) )\n {\n return;\n }\n\n if ( unmetGuards.Count != 0 && unmetGuards.First() == \"Barge-In\" )\n {\n return;\n }\n\n _logger.LogWarning(\"{SessionId} | Unhandled trigger '{Trigger}' in state '{State}'. Unmet guards: [{UnmetGuards}]\",\n SessionId, trigger, state, string.Join(\", \", unmetGuards ?? Array.Empty()));\n\n await _stateMachine.FireAsync(ConversationTrigger.ErrorOccurred, new InvalidOperationException($\"Unhandled trigger {trigger} in state {state}\"));\n });\n\n _stateMachine.OnTransitionedAsync(async transition =>\n {\n _logger.LogDebug(\"{SessionId} | Transitioned: {SourceState} --({Trigger})--> {DestinationState}\",\n SessionId, transition.Source, transition.Trigger, transition.Destination);\n\n await ValueTask.CompletedTask;\n });\n\n _stateMachine.OnTransitioned(LogState);\n }\n\n private void LogState(StateMachine.Transition transition)\n {\n if ( transition.Source == transition.Destination )\n {\n return;\n }\n\n var emoji = transition.Destination switch {\n ConversationState.Initializing => \"🤖\",\n ConversationState.Idle => \"🥱\",\n ConversationState.Listening => \"🧐\",\n ConversationState.ProcessingInput => \"🤔\",\n ConversationState.WaitingForLlm => \"😑\",\n ConversationState.StreamingResponse => \"😃\",\n ConversationState.Speaking => \"🗣️\",\n ConversationState.Interrupted => \"😵\",\n ConversationState.Paused => \"🤐\",\n ConversationState.Error => \"😱\",\n ConversationState.Ended => \"🙃\",\n _ => string.Empty\n };\n\n _logger.LogInformation(\"{SessionId} | {TurnId} | {Emoji} | {DestinationState}\",\n SessionId, _currentTurnId ?? Guid.Empty, emoji, transition.Destination);\n }\n\n private bool ShouldAllowBargeIn(IInputEvent inputEvent)\n {\n var context = new BargeInContext(\n _options,\n _stateMachine.State,\n inputEvent,\n SessionId,\n _currentTurnId\n );\n\n var allow = _bargeInStrategy.ShouldAllowBargeIn(context);\n\n _logger.LogDebug(\"{SessionId} | Barge-in check for trigger {TriggerType} in state {State}. Strategy decided: {Allow}\",\n SessionId, inputEvent.GetType().Name, context.CurrentState, allow);\n\n return allow;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/KokoroVoiceProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Voice provider implementation to manage voice embeddings\n/// \npublic class KokoroVoiceProvider : IKokoroVoiceProvider\n{\n private readonly ITtsCache _cache;\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly ConcurrentDictionary _voicePaths = new();\n\n private bool _disposed;\n\n public KokoroVoiceProvider(\n IModelProvider ittsModelProvider,\n ITtsCache cache,\n ILogger logger)\n {\n _modelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _cache = cache ?? throw new ArgumentNullException(nameof(cache));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n public async Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(voiceId) )\n {\n throw new ArgumentException(\"Voice ID cannot be null or empty\", nameof(voiceId));\n }\n\n try\n {\n // Use cache to avoid repeated loading\n return await _cache.GetOrAddAsync($\"voice_{voiceId}\", async ct =>\n {\n _logger.LogDebug(\"Loading voice data for {VoiceId}\", voiceId);\n\n // Get voice directory\n var voiceDirPath = await GetVoicePathAsync(voiceId, ct);\n\n // Load binary data\n var bytes = await File.ReadAllBytesAsync(voiceDirPath, ct);\n\n // Convert to float array\n var embedding = new float[bytes.Length / sizeof(float)];\n Buffer.BlockCopy(bytes, 0, embedding, 0, bytes.Length);\n\n _logger.LogInformation(\"Loaded voice {VoiceId} with {EmbeddingSize} embedding dimensions\",\n voiceId, embedding.Length);\n\n return new VoiceData(voiceId, embedding);\n }, cancellationToken);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading voice {VoiceId}\", voiceId);\n\n throw;\n }\n }\n\n /// \n public async Task> GetAvailableVoicesAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n // Get voice directory\n var model = await _modelProvider.GetModelAsync(ModelType.KokoroVoices, cancellationToken);\n var voicesDir = model.Path;\n\n if ( !Directory.Exists(voicesDir) )\n {\n _logger.LogWarning(\"Voices directory not found: {Path}\", voicesDir);\n\n return Array.Empty();\n }\n\n // Get all .bin files\n var voiceFiles = Directory.GetFiles(voicesDir, \"*.bin\");\n\n // Extract voice IDs from filenames\n var voiceIds = new List(voiceFiles.Length);\n\n foreach ( var file in voiceFiles )\n {\n var voiceId = Path.GetFileNameWithoutExtension(file);\n voiceIds.Add(voiceId);\n\n // Cache the path for faster lookup\n _voicePaths[voiceId] = file;\n }\n\n _logger.LogInformation(\"Found {Count} available Kokoro voices\", voiceIds.Count);\n\n return voiceIds;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available voices\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voicePaths.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Gets the file path for a voice\n /// \n private async Task GetVoicePathAsync(string voiceId, CancellationToken cancellationToken)\n {\n // Check if path is cached\n if ( _voicePaths.TryGetValue(voiceId, out var cachedPath) )\n {\n return cachedPath;\n }\n\n // Get base directory\n var model = await _modelProvider.GetModelAsync(ModelType.KokoroVoices, cancellationToken);\n var voicesDir = model.Path;\n\n // Build path\n var voicePath = Path.Combine(voicesDir, $\"{voiceId}.bin\");\n\n // Check if file exists\n if ( !File.Exists(voicePath) )\n {\n _logger.LogWarning(\"Voice file not found: {Path}\", voicePath);\n\n throw new FileNotFoundException($\"Voice file not found for {voiceId}\", voicePath);\n }\n\n // Cache the path\n _voicePaths[voiceId] = voicePath;\n\n return voicePath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismUserModel.cs", "using PersonaEngine.Lib.Live2D.Framework.Effect;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Physics;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// ユーザーが実際に使用するモデルの基底クラス。これを継承してユーザーが実装する。\n/// \npublic abstract class CubismUserModel : IDisposable\n{\n /// \n /// X軸方向の加速度\n /// \n protected float _accelerationX;\n\n /// \n /// Y軸方向の加速度\n /// \n protected float _accelerationY;\n\n /// \n /// Z軸方向の加速度\n /// \n protected float _accelerationZ;\n\n /// \n /// 呼吸\n /// \n protected CubismBreath _breath;\n\n /// \n /// マウスドラッグ\n /// \n protected CubismTargetPoint _dragManager;\n\n /// \n /// マウスドラッグのX位置\n /// \n protected float _dragX;\n\n /// \n /// マウスドラッグのY位置\n /// \n protected float _dragY;\n\n /// \n /// 表情管理\n /// \n protected CubismExpressionMotionManager _expressionManager;\n\n /// \n /// 自動まばたき\n /// \n protected CubismEyeBlink? _eyeBlink;\n\n /// \n /// 最後のリップシンクの制御値\n /// \n protected float _lastLipSyncValue;\n\n /// \n /// リップシンクするかどうか\n /// \n protected bool _lipSync;\n\n /// \n /// Mocデータ\n /// \n protected CubismMoc _moc;\n\n /// \n /// MOC3整合性検証するかどうか\n /// \n protected bool _mocConsistency;\n\n /// \n /// ユーザデータ\n /// \n protected CubismModelUserData? _modelUserData;\n\n /// \n /// モーション管理\n /// \n protected CubismMotionManager _motionManager;\n\n /// \n /// 物理演算\n /// \n protected CubismPhysics? _physics;\n\n /// \n /// ポーズ管理\n /// \n protected CubismPose? _pose;\n\n /// \n /// コンストラクタ。\n /// \n public CubismUserModel()\n {\n _lipSync = true;\n\n Opacity = 1.0f;\n\n // モーションマネージャーを作成\n // MotionQueueManagerクラスからの継承なので使い方は同じ\n _motionManager = new CubismMotionManager();\n _motionManager.SetEventCallback(CubismDefaultMotionEventCallback, this);\n\n // 表情モーションマネージャを作成\n _expressionManager = new CubismExpressionMotionManager();\n\n // ドラッグによるアニメーション\n _dragManager = new CubismTargetPoint();\n }\n\n /// \n /// レンダラ\n /// \n public CubismRenderer? Renderer { get; private set; }\n\n /// \n /// モデル行列\n /// \n public CubismModelMatrix ModelMatrix { get; protected set; }\n\n /// \n /// Modelインスタンス\n /// \n public CubismModel Model => _moc.Model;\n\n /// \n /// 初期化されたかどうか\n /// \n public bool Initialized { get; set; }\n\n /// \n /// 更新されたかどうか\n /// \n public bool Updating { get; set; }\n\n /// \n /// 不透明度\n /// \n public float Opacity { get; set; }\n\n public void Dispose()\n {\n _moc.Dispose();\n\n DeleteRenderer();\n }\n\n /// \n /// CubismMotionQueueManagerにイベント用に登録するためのCallback。\n /// CubismUserModelの継承先のEventFiredを呼ぶ。\n /// \n /// 発火したイベントの文字列データ\n /// CubismUserModelを継承したインスタンスを想定\n public static void CubismDefaultMotionEventCallback(CubismUserModel? customData, string eventValue) { customData?.MotionEventFired(eventValue); }\n\n /// \n /// マウスドラッグの情報を設定する。\n /// \n /// ドラッグしているカーソルのX位置\n /// ドラッグしているカーソルのY位置\n public void SetDragging(float x, float y) { _dragManager.Set(x, y); }\n\n /// \n /// 加速度の情報を設定する。\n /// \n /// X軸方向の加速度\n /// Y軸方向の加速度\n /// Z軸方向の加速度\n protected void SetAcceleration(float x, float y, float z)\n {\n _accelerationX = x;\n _accelerationY = y;\n _accelerationZ = z;\n }\n\n /// \n /// モデルデータを読み込む。\n /// \n /// moc3ファイルが読み込まれているバッファ\n /// MOCの整合性チェックフラグ(初期値 : false)\n protected void LoadModel(byte[] buffer, bool shouldCheckMocConsistency = false)\n {\n _moc = new CubismMoc(buffer, shouldCheckMocConsistency);\n Model.SaveParameters();\n ModelMatrix = new CubismModelMatrix(Model.GetCanvasWidth(), Model.GetCanvasHeight());\n }\n\n /// \n /// ポーズデータを読み込む。\n /// \n /// pose3.jsonが読み込まれているバッファ\n protected void LoadPose(string buffer) { _pose = new CubismPose(buffer); }\n\n /// \n /// 物理演算データを読み込む。\n /// \n /// physics3.jsonが読み込まれているバッファ\n protected void LoadPhysics(string buffer) { _physics = new CubismPhysics(buffer); }\n\n /// \n /// ユーザーデータを読み込む。\n /// \n /// userdata3.jsonが読み込まれているバッファ\n protected void LoadUserData(string buffer) { _modelUserData = new CubismModelUserData(buffer); }\n\n /// \n /// 指定した位置にDrawableがヒットしているかどうかを取得する。\n /// \n /// 検証したいDrawableのID\n /// X位置\n /// Y位置\n /// \n /// true ヒットしている\n /// false ヒットしていない\n /// \n public unsafe bool IsHit(string drawableId, float pointX, float pointY)\n {\n var drawIndex = Model.GetDrawableIndex(drawableId);\n\n if ( drawIndex < 0 )\n {\n return false; // 存在しない場合はfalse\n }\n\n var count = Model.GetDrawableVertexCount(drawIndex);\n var vertices = Model.GetDrawableVertices(drawIndex);\n\n var left = vertices[0];\n var right = vertices[0];\n var top = vertices[1];\n var bottom = vertices[1];\n\n for ( var j = 1; j < count; ++j )\n {\n var x = vertices[CubismFramework.VertexOffset + j * CubismFramework.VertexStep];\n var y = vertices[CubismFramework.VertexOffset + j * CubismFramework.VertexStep + 1];\n\n if ( x < left )\n {\n left = x; // Min x\n }\n\n if ( x > right )\n {\n right = x; // Max x\n }\n\n if ( y < top )\n {\n top = y; // Min y\n }\n\n if ( y > bottom )\n {\n bottom = y; // Max y\n }\n }\n\n var tx = ModelMatrix.InvertTransformX(pointX);\n var ty = ModelMatrix.InvertTransformY(pointY);\n\n return left <= tx && tx <= right && top <= ty && ty <= bottom;\n }\n\n /// \n /// レンダラを生成して初期化を実行する。\n /// \n protected void CreateRenderer(CubismRenderer renderer)\n {\n if ( Renderer != null )\n {\n DeleteRenderer();\n }\n\n Renderer = renderer;\n }\n\n /// \n /// レンダラを解放する。\n /// \n protected void DeleteRenderer()\n {\n if ( Renderer != null )\n {\n Renderer.Dispose();\n Renderer = null;\n }\n }\n\n /// \n /// Eventが再生処理時にあった場合の処理をする。\n /// 継承で上書きすることを想定している。\n /// 上書きしない場合はログ出力をする。\n /// \n /// 発火したイベントの文字列データ\n protected abstract void MotionEventFired(string eventValue);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleTimeline.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Manages active subtitle segments, updates their state based on time,\n/// determines visible lines, and calculates their positions.\n/// \npublic class SubtitleTimeline\n{\n private readonly List _activeSegments = new();\n\n private readonly float _bottomMargin;\n\n private readonly FSColor _highlightColor;\n\n private readonly float _interSegmentSpacing;\n\n private readonly float _lineSpacing;\n\n private readonly Lock _lock = new();\n\n private readonly int _maxVisibleLines;\n\n private readonly FSColor _normalColor;\n\n private readonly TextMeasurer _textMeasurer;\n\n private readonly List _visibleLinesCache;\n\n private readonly IWordAnimator _wordAnimator;\n\n public SubtitleTimeline(\n int maxVisibleLines,\n float bottomMargin,\n float lineSpacing,\n float interSegmentSpacing,\n TextMeasurer textMeasurer,\n IWordAnimator wordAnimator,\n FSColor highlightColor,\n FSColor normalColor)\n {\n _maxVisibleLines = Math.Max(1, maxVisibleLines);\n _bottomMargin = bottomMargin;\n _lineSpacing = lineSpacing;\n _interSegmentSpacing = interSegmentSpacing;\n _textMeasurer = textMeasurer;\n _wordAnimator = wordAnimator;\n _highlightColor = highlightColor;\n _normalColor = normalColor;\n\n _visibleLinesCache = new List(_maxVisibleLines * 2);\n }\n\n public void AddSegment(SubtitleSegment segment)\n {\n lock (_lock)\n {\n _activeSegments.Add(segment);\n }\n }\n\n public void RemoveSegment(object originalSegmentIdentifier)\n {\n lock (_lock)\n {\n _activeSegments.RemoveAll(s => ReferenceEquals(s.OriginalAudioSegment, originalSegmentIdentifier) || s.OriginalAudioSegment.Equals(originalSegmentIdentifier));\n\n // TODO: If using object pooling for segments/lines/words, return them to the pool here.\n }\n }\n\n /// \n /// Updates the animation progress and state of words in active segments.\n /// \n public void Update(float currentTime)\n {\n lock (_lock)\n {\n for ( var i = _activeSegments.Count - 1; i >= 0; i-- )\n {\n var segment = _activeSegments[i];\n\n // Optimization: Potentially skip segments that are entirely in the past?\n // if (segment.EstimatedEndTime < currentTime - someBuffer) continue;\n // Optimization: Potentially skip segments entirely in the future?\n // if (segment.AbsoluteStartTime > currentTime + someBuffer) continue;\n\n for ( var j = 0; j < segment.Lines.Count; j++ )\n {\n var line = segment.Lines[j];\n // Use ref local for structs to avoid copying if SubtitleWordInfo is a struct\n // Requires Words to be an array or Span for direct ref access.\n // With List, we modify the copy and then update the list element.\n for ( var k = 0; k < line.Words.Count; k++ )\n {\n var word = line.Words[k];\n\n if ( word.HasStarted(currentTime) )\n {\n if ( word.IsComplete(currentTime) )\n {\n word.AnimationProgress = 1.0f;\n }\n else\n {\n var elapsed = currentTime - word.AbsoluteStartTime;\n word.AnimationProgress = Math.Clamp(elapsed / word.Duration, 0.0f, 1.0f);\n }\n }\n else\n {\n word.AnimationProgress = 0.0f;\n }\n\n word.CurrentScale = _wordAnimator.CalculateScale(word.AnimationProgress);\n word.CurrentColor = _wordAnimator.CalculateColor(_highlightColor, _normalColor, word.AnimationProgress);\n\n line.Words[k] = word;\n }\n }\n }\n }\n }\n\n public List GetVisibleLinesAndPosition(float currentTime, int viewportWidth, int viewportHeight)\n {\n _visibleLinesCache.Clear();\n\n lock (_lock)\n {\n for ( var i = _activeSegments.Count - 1; i >= 0; i-- )\n {\n var segment = _activeSegments[i];\n\n // Optimization: If segment hasn't started, none of its lines are visible.\n if ( segment.AbsoluteStartTime > currentTime )\n {\n continue;\n }\n\n for ( var j = segment.Lines.Count - 1; j >= 0; j-- )\n {\n var line = segment.Lines[j];\n\n if ( line.Words.Count > 0 && line.Words[0].HasStarted(currentTime) )\n {\n _visibleLinesCache.Add(line);\n if ( _visibleLinesCache.Count >= _maxVisibleLines )\n {\n goto FoundEnoughLines;\n }\n }\n\n // Optimization: If the first word of this line hasn't started,\n // earlier lines in the *same segment* also won't have started yet.\n // (Assumes words within a line are chronologically ordered).\n // else if (line.Words.Count > 0)\n // {\n // break; // Stop checking lines in this segment\n // }\n }\n }\n }\n\n FoundEnoughLines:\n\n _visibleLinesCache.Reverse();\n\n var currentBaselineY = viewportHeight - _bottomMargin;\n\n for ( var i = _visibleLinesCache.Count - 1; i >= 0; i-- )\n {\n var line = _visibleLinesCache[i];\n line.BaselineY = currentBaselineY;\n\n var currentX = (viewportWidth - line.TotalWidth) / 2.0f;\n\n for ( var k = 0; k < line.Words.Count; k++ )\n {\n var word = line.Words[k];\n\n var wordCenterX = currentX + word.Size.X / 2.0f;\n var wordCenterY = currentBaselineY - _textMeasurer.LineHeight / 2.0f;\n\n word.Position = new Vector2(wordCenterX, wordCenterY);\n line.Words[k] = word;\n currentX += word.Size.X;\n }\n\n currentBaselineY -= _lineSpacing;\n\n if ( i > 0 && _visibleLinesCache[i - 1].SegmentIndex != line.SegmentIndex )\n {\n currentBaselineY -= _interSegmentSpacing;\n }\n }\n\n return _visibleLinesCache;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsEngine.cs", "using System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.LLM;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Main TTS engine implementation\n/// \npublic class TtsEngine : ITtsEngine\n{\n private readonly IList _audioFilters;\n\n private readonly ILogger _logger;\n\n private readonly IOptionsMonitor _options;\n\n private readonly IPhonemizer _phonemizer;\n\n private readonly IAudioSynthesizer _synthesizer;\n\n private readonly IList _textFilters;\n\n private readonly ITextProcessor _textProcessor;\n\n private readonly SemaphoreSlim _throttle;\n\n private bool _disposed;\n\n public TtsEngine(\n ITextProcessor textProcessor,\n IPhonemizer phonemizer,\n IAudioSynthesizer synthesizer,\n IOptionsMonitor options,\n IEnumerable audioFilters,\n IEnumerable textFilters,\n ILoggerFactory loggerFactory)\n {\n _textProcessor = textProcessor ?? throw new ArgumentNullException(nameof(textProcessor));\n _phonemizer = phonemizer ?? throw new ArgumentNullException(nameof(phonemizer));\n _synthesizer = synthesizer ?? throw new ArgumentNullException(nameof(synthesizer));\n _options = options;\n _audioFilters = audioFilters.OrderByDescending(x => x.Priority).ToList();\n _textFilters = textFilters.OrderByDescending(x => x.Priority).ToList();\n _logger = loggerFactory?.CreateLogger() ?? throw new ArgumentNullException(nameof(loggerFactory));\n\n _throttle = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount);\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _throttle.Dispose();\n _disposed = true;\n }\n\n public async Task SynthesizeStreamingAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default\n )\n {\n var textBuffer = new StringBuilder(4096);\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n\n try\n {\n await foreach ( var (_, _, _, textChunk) in inputReader.ReadAllAsync(cancellationToken).ConfigureAwait(false) )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n break;\n }\n\n if ( string.IsNullOrEmpty(textChunk) )\n {\n continue;\n }\n\n textBuffer.Append(textChunk);\n var currentText = textBuffer.ToString();\n\n var processedText = await _textProcessor.ProcessAsync(currentText, cancellationToken);\n var sentences = processedText.Sentences;\n\n if ( sentences.Count <= 1 )\n {\n continue;\n }\n\n // Process all sentences except the last one(which might be incomplete)\n for ( var i = 0; i < sentences.Count - 1; i++ )\n {\n var sentence = sentences[i].Trim();\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n continue;\n }\n\n await foreach ( var segment in ProcessSentenceAsync(sentence, options, cancellationToken) )\n {\n ApplyAudioFilters(segment);\n\n if ( firstChunk )\n {\n var firstChunkEvent = new TtsStreamStartEvent(sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, cancellationToken).ConfigureAwait(false);\n\n firstChunk = false;\n }\n\n var chunkEvent = new TtsChunkEvent(sessionId, turnId, DateTimeOffset.UtcNow, segment);\n await outputWriter.WriteAsync(chunkEvent, cancellationToken).ConfigureAwait(false);\n }\n }\n\n textBuffer.Clear();\n textBuffer.Append(sentences[^1]);\n }\n\n var remainingText = textBuffer.ToString().Trim();\n if ( !string.IsNullOrEmpty(remainingText) )\n {\n await foreach ( var segment in ProcessSentenceAsync(remainingText, options, cancellationToken) )\n {\n ApplyAudioFilters(segment);\n\n if ( firstChunk )\n {\n var firstChunkEvent = new TtsStreamStartEvent(sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, cancellationToken).ConfigureAwait(false);\n\n firstChunk = false;\n }\n \n var chunkEvent = new TtsChunkEvent(sessionId, turnId, DateTimeOffset.UtcNow, segment);\n await outputWriter.WriteAsync(chunkEvent, cancellationToken).ConfigureAwait(false);\n }\n }\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n\n await outputWriter.WriteAsync(new ErrorOutputEvent(sessionId, turnId, DateTimeOffset.UtcNow, ex), cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n if ( !firstChunk )\n {\n await outputWriter.WriteAsync(new TtsStreamEndEvent(sessionId, turnId, DateTimeOffset.UtcNow, completedReason), cancellationToken).ConfigureAwait(false);\n }\n }\n\n return completedReason;\n }\n\n /// \n /// Processes a single sentence for synthesis\n /// \n private async IAsyncEnumerable ProcessSentenceAsync(\n string sentence,\n KokoroVoiceOptions? options = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n yield break;\n }\n\n await _throttle.WaitAsync(cancellationToken);\n\n var currentOptions = options ?? _options.CurrentValue;\n\n try\n {\n // Apply text filters before processing\n var processedText = sentence;\n var textFilterResults = new List(_textFilters.Count);\n\n foreach ( var textFilter in _textFilters )\n {\n var filterResult = await textFilter.ProcessAsync(processedText, cancellationToken);\n processedText = filterResult.ProcessedText;\n\n textFilterResults.Add(filterResult);\n }\n\n // Get phonemes\n var phonemeResult = await _phonemizer.ToPhonemesAsync(processedText, cancellationToken);\n\n // Process each phoneme chunk\n foreach ( var phonemeChunk in SplitPhonemes(phonemeResult.Phonemes, 510) )\n {\n // Get audio\n var audioData = await _synthesizer.SynthesizeAsync(\n phonemeChunk,\n currentOptions,\n cancellationToken);\n\n // Apply timing\n ApplyTokenTimings(\n phonemeResult.Tokens,\n currentOptions,\n audioData.PhonemeTimings);\n\n // Return segment\n var segment = new AudioSegment(\n audioData.Samples,\n options?.SampleRate ?? _options.CurrentValue.SampleRate,\n phonemeResult.Tokens);\n\n for ( var index = 0; index < _textFilters.Count; index++ )\n {\n var textFilter = _textFilters[index];\n var textFilterResult = textFilterResults[index];\n await textFilter.PostProcessAsync(textFilterResult, segment, cancellationToken);\n }\n\n yield return segment;\n }\n }\n finally\n {\n _throttle.Release();\n }\n }\n\n /// \n /// Splits phonemes into manageable chunks\n /// \n private IEnumerable SplitPhonemes(string phonemes, int maxLength)\n {\n if ( string.IsNullOrEmpty(phonemes) )\n {\n yield return string.Empty;\n\n yield break;\n }\n\n if ( phonemes.Length <= maxLength )\n {\n yield return phonemes;\n\n yield break;\n }\n\n var currentIndex = 0;\n while ( currentIndex < phonemes.Length )\n {\n var remainingLength = phonemes.Length - currentIndex;\n var chunkSize = Math.Min(maxLength, remainingLength);\n\n // Find a good breakpoint (whitespace or punctuation)\n if ( chunkSize < remainingLength && chunkSize > 10 )\n {\n // Look backwards from the end to find a good breakpoint\n for ( var i = currentIndex + chunkSize - 1; i > currentIndex + 10; i-- )\n {\n if ( char.IsWhiteSpace(phonemes[i]) || IsPunctuation(phonemes[i]) )\n {\n chunkSize = i - currentIndex + 1;\n\n break;\n }\n }\n }\n\n yield return phonemes.Substring(currentIndex, chunkSize);\n currentIndex += chunkSize;\n }\n }\n\n private bool IsPunctuation(char c) { return \".,:;!?-—()[]{}\\\"'\".Contains(c); }\n\n private void ApplyAudioFilters(AudioSegment audioSegment)\n {\n foreach ( var audioFilter in _audioFilters )\n {\n audioFilter.Process(audioSegment);\n }\n }\n\n /// \n /// Applies timing information to tokens\n /// \n private void ApplyTokenTimings(\n IReadOnlyList tokens,\n KokoroVoiceOptions options,\n ReadOnlyMemory phonemeTimings)\n {\n // Skip if no timing information\n if ( tokens.Count == 0 || phonemeTimings.Length < 3 )\n {\n return;\n }\n\n var timingsSpan = phonemeTimings.Span;\n\n // Magic scaling factor for timing conversion\n const int TIME_DIVISOR = 80;\n\n // Start with boundary tokens (often token)\n var leftTime = options.TrimSilence ? 0 : 2 * Math.Max(0, timingsSpan[0] - 3);\n var rightTime = leftTime;\n\n // Process each token\n var timingIndex = 1;\n foreach ( var token in tokens )\n {\n // Skip tokens without phonemes\n if ( string.IsNullOrEmpty(token.Phonemes) )\n {\n // Handle whitespace timing specially\n if ( token.Whitespace == \" \" && timingIndex + 1 < timingsSpan.Length )\n {\n timingIndex++;\n leftTime = rightTime + timingsSpan[timingIndex];\n rightTime = leftTime + timingsSpan[timingIndex];\n timingIndex++;\n }\n\n continue;\n }\n\n // Calculate end index for this token's phonemes\n var endIndex = timingIndex + (token.Phonemes?.Length ?? 0);\n if ( endIndex >= phonemeTimings.Length )\n {\n continue;\n }\n\n // Start time for this token\n var startTime = (double)leftTime / TIME_DIVISOR;\n\n // Sum durations for all phonemes in this token\n var tokenDuration = 0L;\n for ( var i = timingIndex; i < endIndex && i < timingsSpan.Length; i++ )\n {\n tokenDuration += timingsSpan[i];\n }\n\n // Handle whitespace after token\n var spaceDuration = token.Whitespace == \" \" && endIndex < timingsSpan.Length\n ? timingsSpan[endIndex]\n : 0;\n\n // Calculate end time\n leftTime = rightTime + 2 * tokenDuration + spaceDuration;\n var endTime = (double)leftTime / TIME_DIVISOR;\n rightTime = leftTime + spaceDuration;\n\n // Add token with timing\n token.StartTs = startTime;\n token.EndTs = endTime;\n\n // Move to next token's timing\n timingIndex = endIndex + (token.Whitespace == \" \" ? 1 : 0);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCFilter.cs", "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCFilter : IAudioFilter, IDisposable\n{\n private const int ProcessingSampleRate = 16000;\n\n private const int OutputSampleRate = 32000;\n\n private const int FinalSampleRate = 24000;\n\n private const int MaxInputDuration = 30; // seconds\n\n private readonly SemaphoreSlim _initLock = new(1, 1);\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly IDisposable? _optionsChangeRegistration;\n\n private readonly IOptionsMonitor _optionsMonitor;\n\n private readonly IRVCVoiceProvider _rvcVoiceProvider;\n\n private RVCFilterOptions _currentOptions;\n\n private bool _disposed;\n\n private IF0Predictor? _f0Predictor;\n\n private OnnxRVC? _rvcModel;\n\n public RVCFilter(\n IOptionsMonitor optionsMonitor,\n IModelProvider modelProvider,\n IRVCVoiceProvider rvcVoiceProvider,\n ILogger logger)\n {\n _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));\n _modelProvider = modelProvider;\n _rvcVoiceProvider = rvcVoiceProvider;\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _currentOptions = optionsMonitor.CurrentValue;\n\n _ = InitializeAsync(_currentOptions);\n\n // Register for options changes\n _optionsChangeRegistration = _optionsMonitor.OnChange(OnOptionsChanged);\n }\n\n public void Process(AudioSegment audioSegment)\n {\n if ( _disposed )\n {\n throw new ObjectDisposedException(nameof(RVCFilter));\n }\n\n if ( _rvcModel == null || _f0Predictor == null ||\n audioSegment?.AudioData == null || audioSegment.AudioData.Length == 0 )\n {\n return;\n }\n\n // Get the latest options for processing\n var options = _currentOptions;\n var originalSampleRate = audioSegment.SampleRate;\n\n if ( !options.Enabled )\n {\n return;\n }\n\n // Start timing\n var stopwatch = Stopwatch.StartNew();\n\n // Step 1: Resample input to processing sample rate\n var resampleRatioToProcessing = (int)Math.Ceiling((double)ProcessingSampleRate / originalSampleRate);\n var resampledInputSize = audioSegment.AudioData.Length * resampleRatioToProcessing;\n\n var resampledInput = ArrayPool.Shared.Rent(resampledInputSize);\n try\n {\n var inputSampleCount = AudioConverter.ResampleFloat(\n audioSegment.AudioData,\n resampledInput,\n 1,\n (uint)originalSampleRate,\n ProcessingSampleRate);\n\n // Step 2: Process with RVC model\n var maxInputSamples = OutputSampleRate * MaxInputDuration;\n var outputBufferSize = maxInputSamples + 2 * options.HopSize;\n\n var processingBuffer = ArrayPool.Shared.Rent(outputBufferSize);\n try\n {\n var processedSampleCount = _rvcModel.ProcessAudio(\n resampledInput.AsMemory(0, inputSampleCount),\n processingBuffer,\n _f0Predictor,\n options.SpeakerId,\n options.F0UpKey);\n\n // Step 3: Resample to original sample rate\n var resampleRatioToOutput = (int)Math.Ceiling((double)originalSampleRate / OutputSampleRate);\n var finalOutputSize = processedSampleCount * resampleRatioToOutput;\n\n var resampledOutput = ArrayPool.Shared.Rent(finalOutputSize);\n try\n {\n var finalSampleCount = AudioConverter.ResampleFloat(\n processingBuffer.AsMemory(0, processedSampleCount),\n resampledOutput,\n 1,\n OutputSampleRate,\n (uint)originalSampleRate);\n\n // Need one allocation for the final output buffer since AudioSegment keeps this reference\n var finalBuffer = new float[finalSampleCount];\n Array.Copy(resampledOutput, finalBuffer, finalSampleCount);\n\n audioSegment.AudioData = finalBuffer.AsMemory();\n audioSegment.SampleRate = FinalSampleRate;\n }\n finally\n {\n ArrayPool.Shared.Return(resampledOutput);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(processingBuffer);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(resampledInput);\n }\n\n // Stop timing after processing is complete\n stopwatch.Stop();\n var processingTime = stopwatch.Elapsed.TotalSeconds;\n\n // Calculate final audio duration (based on the processed audio)\n var finalAudioDuration = audioSegment.AudioData.Length / (double)FinalSampleRate;\n\n // Calculate real-time factor\n var realTimeFactor = finalAudioDuration / processingTime;\n\n // Log the results using ILogger\n _logger.LogInformation(\"Generated {AudioDuration:F2}s audio in {ProcessingTime:F2}s (x{RealTimeFactor:F2} real-time)\",\n finalAudioDuration, processingTime, realTimeFactor);\n }\n\n public int Priority => 100;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( disposing )\n {\n _optionsChangeRegistration?.Dispose();\n DisposeResources();\n }\n\n _disposed = true;\n }\n\n private async void OnOptionsChanged(RVCFilterOptions newOptions)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( ShouldReinitialize(newOptions) )\n {\n DisposeResources();\n await InitializeAsync(newOptions);\n }\n\n _currentOptions = newOptions;\n }\n\n private bool ShouldReinitialize(RVCFilterOptions newOptions)\n {\n return _currentOptions.DefaultVoice != newOptions.DefaultVoice ||\n _currentOptions.HopSize != newOptions.HopSize;\n }\n\n private async ValueTask InitializeAsync(RVCFilterOptions options)\n {\n await _initLock.WaitAsync();\n try\n {\n var crepeModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCCrepeTiny);\n var hubertModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCHubert);\n var rvcModel = await _rvcVoiceProvider.GetVoiceAsync(options.DefaultVoice);\n\n // _f0Predictor = new CrepeOnnx(crepeModel.Path);\n _f0Predictor = new CrepeOnnxSimd(crepeModel.Path);\n // _f0Predictor = new ACFMethod(512, 16000);\n\n _rvcModel = new OnnxRVC(\n rvcModel,\n options.HopSize,\n hubertModel.Path);\n }\n finally\n {\n _initLock.Release();\n }\n }\n\n private void DisposeResources()\n {\n _rvcModel?.Dispose();\n _rvcModel = null;\n\n _f0Predictor?.Dispose();\n _f0Predictor = null;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ChatEditor.cs", "using System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nusing OpenAI.Chat;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class ChatEditor : ConfigSectionEditorBase\n{\n private readonly FontProvider _fontProvider;\n\n private readonly IConversationOrchestrator _orchestrator;\n\n private readonly float _participantsPanelWidth = 200f;\n\n private readonly IUiThemeManager _themeManager;\n\n private IConversationContext? _currentContext;\n\n private string _editMessageContent = string.Empty;\n\n private Guid _editMessageId = Guid.Empty;\n\n private Guid _editTurnId = Guid.Empty;\n\n private IReadOnlyList _historySnapshot = Array.Empty();\n\n private bool _needsRedraw = true;\n\n private IReadOnlyDictionary _participantsSnapshot = new Dictionary();\n\n private InteractionTurn? _pendingTurnSnapshot;\n\n private bool _showConfirmClearPopup = false;\n\n private bool _showEditPopup = false;\n\n public ChatEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IUiThemeManager themeManager,\n IConversationOrchestrator orchestrator,\n FontProvider fontProvider)\n : base(configManager, stateManager)\n {\n _orchestrator = orchestrator;\n _themeManager = themeManager;\n _fontProvider = fontProvider;\n\n _orchestrator.SessionsUpdated += OnCurrentContextChanged;\n OnCurrentContextChanged(null, EventArgs.Empty);\n }\n\n public override string SectionKey => \"Chat\";\n\n public override string DisplayName => \"Conversation\";\n\n private void OnCurrentContextChanged(object? sender, EventArgs e)\n {\n var sessionId = _orchestrator.GetActiveSessionIds().FirstOrDefault();\n if ( sessionId == Guid.Empty )\n {\n return;\n }\n\n var context = _orchestrator.GetSession(sessionId).Context;\n SetCurrentContext(context);\n }\n\n private void SetCurrentContext(IConversationContext? newContext)\n {\n if ( _currentContext == newContext )\n {\n return;\n }\n\n if ( _currentContext != null )\n {\n _currentContext.ConversationUpdated -= OnConversationUpdated;\n }\n\n _currentContext = newContext;\n\n if ( _currentContext != null )\n {\n _currentContext.ConversationUpdated += OnConversationUpdated;\n UpdateSnapshots();\n }\n else\n {\n _historySnapshot = Array.Empty();\n _participantsSnapshot = new Dictionary();\n _pendingTurnSnapshot = null;\n }\n\n _needsRedraw = true;\n }\n\n private void OnConversationUpdated(object? sender, EventArgs e)\n {\n UpdateSnapshots();\n _needsRedraw = true;\n }\n\n private void UpdateSnapshots()\n {\n if ( _currentContext == null )\n {\n return;\n }\n\n _participantsSnapshot = new Dictionary(_currentContext.Participants);\n _historySnapshot = _currentContext.History.Select(turn => turn.CreateSnapshot()).ToList();\n _pendingTurnSnapshot = _currentContext.PendingTurn;\n }\n\n public override void Render()\n {\n if ( _needsRedraw )\n {\n _needsRedraw = false;\n }\n\n var availWidth = ImGui.GetContentRegionAvail().X;\n if ( _currentContext == null )\n {\n ImGui.TextWrapped(\"No active conversation selected.\");\n\n return;\n }\n\n // --- Left Panel: Participants and Controls ---\n ImGui.BeginChild(\"ParticipantsPanel\", new Vector2(_participantsPanelWidth, 700), ImGuiChildFlags.Borders);\n {\n RenderParticipantsPanel(_currentContext);\n RenderControlsPanel(_currentContext);\n }\n\n ImGui.EndChild();\n\n ImGui.SameLine();\n\n // --- Right Panel: Chat History ---\n var chatAreaWidth = availWidth - _participantsPanelWidth - ImGui.GetStyle().ItemSpacing.X;\n ImGui.BeginChild(\"ChatHistoryPanel\", new Vector2(chatAreaWidth, 700), ImGuiChildFlags.None);\n {\n RenderChatHistory(_currentContext, chatAreaWidth);\n }\n\n ImGui.EndChild();\n\n // --- Popups ---\n RenderEditPopup(_currentContext);\n RenderConfirmClearPopup(_currentContext);\n }\n\n private void RenderParticipantsPanel(IConversationContext context)\n {\n ImGui.Text(\"Participants\");\n ImGui.Separator();\n\n if ( !_participantsSnapshot.Any() )\n {\n ImGui.TextDisabled(\"No participants.\");\n\n return;\n }\n\n foreach ( var participant in _participantsSnapshot.Values )\n {\n // Simple display: Icon (optional) + Name + Role\n ImGui.BulletText($\"{participant.Name} ({participant.Role})\");\n // Optional: Add context menu to remove participant?\n // if (ImGui.BeginPopupContextItem($\"participant_{participant.Id}\")) { ... }\n }\n }\n\n private void RenderControlsPanel(IConversationContext context)\n {\n ImGui.Separator();\n ImGui.Spacing();\n ImGui.Text(\"Controls\");\n ImGui.Separator();\n\n if ( ImGui.Button(\"Clear Conversation\", new Vector2(-1, 0)) )\n {\n _showConfirmClearPopup = true;\n }\n\n // Optional: Add other controls like Apply Cleanup Strategy\n if ( ImGui.Button(\"Apply Cleanup\", new Vector2(-1, 0)) )\n {\n _currentContext?.ApplyCleanupStrategy();\n }\n }\n\n private void RenderChatHistory(IConversationContext context, float availableWidth)\n {\n var maxBubbleWidth = availableWidth * 0.75f;\n var style = ImGui.GetStyle();\n\n ImGui.Text(\"Conversation: Main\");\n ImGui.Separator();\n\n ImGui.BeginChild(\"ChatScrollRegion\", new Vector2(availableWidth, -1), ImGuiChildFlags.None);\n {\n for ( var turnIndex = 0; turnIndex < _historySnapshot.Count; turnIndex++ )\n {\n var turn = _historySnapshot[turnIndex];\n RenderTurn(context, turn, turnIndex, maxBubbleWidth, availableWidth);\n\n ImGui.Separator();\n ImGui.Spacing();\n }\n\n // if ( _pendingTurnSnapshot != null )\n // {\n // ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.6f, 0.6f, 0.6f, 1.0f));\n // RenderTurn(context, _pendingTurnSnapshot, -1, maxBubbleWidth, availableWidth, true);\n // ImGui.PopStyleColor();\n // }\n\n if ( ImGui.GetScrollY() >= ImGui.GetScrollMaxY() - 10 )\n {\n ImGui.SetScrollHereY(1.0f);\n }\n }\n\n ImGui.EndChild();\n }\n\n private void RenderTurn(IConversationContext context, InteractionTurn turn, int turnIndex, float maxBubbleWidth, float availableWidth, bool isPending = false)\n {\n var style = ImGui.GetStyle();\n\n ImGui.TextDisabled($\"Turn {turnIndex + 1} ({turn.StartTime.ToLocalTime():g})\");\n ImGui.Spacing();\n\n for ( var msgIndex = 0; msgIndex < turn.Messages.Count; msgIndex++ )\n {\n var message = turn.Messages[msgIndex];\n var participant = _participantsSnapshot.GetValueOrDefault(message.ParticipantId);\n var role = participant?.Role ?? message.Role;\n\n var isUserMessage = role == ChatMessageRole.User;\n\n var messageText = message.Text;\n if ( message.IsPartial && isPending )\n {\n messageText += \" ...\";\n }\n\n ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));\n ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, 8.0f);\n\n var textSize = ImGui.CalcTextSize(messageText, false, maxBubbleWidth - style.WindowPadding.X * 2);\n var nameSize = ImGui.CalcTextSize(message.ParticipantName, false, maxBubbleWidth - style.WindowPadding.X * 2);\n var bubbleWidth = Math.Min(textSize.X + style.WindowPadding.X * 2, maxBubbleWidth);\n var bubbleHeight = nameSize.Y + textSize.Y + style.WindowPadding.Y * 2 + (isUserMessage ? ImGui.GetTextLineHeight() : 0);\n\n var startPosX = style.WindowPadding.X;\n if ( isUserMessage )\n {\n startPosX = availableWidth - bubbleWidth - style.WindowPadding.X - style.ScrollbarSize;\n }\n\n ImGui.SetCursorPosX(startPosX);\n\n // --- Styling ---\n Vector4 bgColor,\n textColor;\n\n if ( isUserMessage )\n {\n bgColor = new Vector4(0.15f, 0.48f, 0.88f, 1.0f); // Blueish\n textColor = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); // White text\n }\n else\n {\n bgColor = new Vector4(0.92f, 0.92f, 0.92f, 1.0f); // Light gray\n textColor = new Vector4(0.1f, 0.1f, 0.1f, 1.0f); // Dark text\n }\n\n ImGui.PushStyleColor(ImGuiCol.ChildBg, bgColor);\n ImGui.PushStyleColor(ImGuiCol.Text, textColor);\n\n // --- Render Bubble ---\n var childId = $\"msg_{turn.TurnId}_{message.MessageId}\";\n ImGui.BeginChild(childId, new Vector2(bubbleWidth, bubbleHeight), ImGuiChildFlags.Borders, ImGuiWindowFlags.None);\n {\n if ( isUserMessage )\n {\n ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.52f, 0.92f, 0.89f, 1f));\n ImGui.TextWrapped(message.ParticipantName);\n ImGui.PopStyleColor();\n }\n\n ImGui.TextWrapped(messageText);\n\n ImGui.EndChild();\n }\n\n ImGui.PopStyleColor(2);\n ImGui.PopStyleVar(2);\n\n // --- Context Menu (Edit/Delete) - Only for committed messages ---\n if ( !isPending && ImGui.BeginPopupContextItem($\"ctx_{childId}\") )\n {\n if ( ImGui.MenuItem(\"Edit\") )\n {\n _editTurnId = turn.TurnId;\n _editMessageId = message.MessageId;\n _editMessageContent = message.Text;\n _showEditPopup = true;\n }\n\n ImGui.Separator();\n if ( ImGui.MenuItem(\"Delete\") )\n {\n context.TryDeleteMessage(turn.TurnId, message.MessageId);\n }\n\n ImGui.EndPopup();\n }\n\n ImGui.Dummy(new Vector2(0, style.ItemSpacing.Y));\n }\n }\n\n private void RenderEditPopup(IConversationContext context)\n {\n if ( _showEditPopup )\n {\n ImGui.OpenPopup(\"Edit Message\");\n _showEditPopup = false;\n }\n\n var viewport = ImGui.GetMainViewport();\n ImGui.SetNextWindowPos(viewport.Pos + viewport.Size * 0.5f, ImGuiCond.Appearing, new Vector2(0.5f, 0.5f));\n ImGui.SetNextWindowSize(new Vector2(500, 0), ImGuiCond.Appearing);\n\n if ( ImGui.BeginPopupModal(\"Edit Message\", ImGuiWindowFlags.NoResize) )\n {\n ImGui.InputTextMultiline(\"##edit_content\", ref _editMessageContent, 1024 * 4, new Vector2(0, 150));\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n var buttonWidth = 120f;\n var totalButtonsWidth = buttonWidth * 2 + ImGui.GetStyle().ItemSpacing.X;\n ImGui.SetCursorPosX((ImGui.GetWindowWidth() - totalButtonsWidth) * 0.5f);\n\n if ( ImGui.Button(\"Save\", new Vector2(buttonWidth, 0)) )\n {\n if ( _editMessageId != Guid.Empty && _editTurnId != Guid.Empty )\n {\n context.TryUpdateMessage(_editTurnId, _editMessageId, _editMessageContent);\n\n _editMessageId = Guid.Empty;\n _editTurnId = Guid.Empty;\n _editMessageContent = string.Empty;\n }\n\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"Cancel\", new Vector2(buttonWidth, 0)) )\n {\n _editMessageId = Guid.Empty;\n _editTurnId = Guid.Empty;\n _editMessageContent = string.Empty;\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.EndPopup();\n }\n else\n {\n if ( _editMessageId == Guid.Empty )\n {\n return;\n }\n\n _editMessageId = Guid.Empty;\n _editTurnId = Guid.Empty;\n _editMessageContent = string.Empty;\n }\n }\n\n private void RenderConfirmClearPopup(IConversationContext context)\n {\n if ( _showConfirmClearPopup )\n {\n ImGui.OpenPopup(\"Confirm Clear\");\n _showConfirmClearPopup = false;\n }\n\n var viewport = ImGui.GetMainViewport();\n ImGui.SetNextWindowPos(viewport.Pos + viewport.Size * 0.5f, ImGuiCond.Appearing, new Vector2(0.5f, 0.5f));\n\n if ( ImGui.BeginPopupModal(\"Confirm Clear\", ImGuiWindowFlags.NoResize | ImGuiWindowFlags.AlwaysAutoResize) )\n {\n ImGui.TextWrapped(\"Are you sure you want to clear the entire conversation history?\");\n ImGui.TextWrapped(\"This action cannot be undone.\");\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n var buttonWidth = 120f;\n var totalButtonsWidth = buttonWidth * 2 + ImGui.GetStyle().ItemSpacing.X;\n ImGui.SetCursorPosX((ImGui.GetWindowWidth() - totalButtonsWidth) * 0.5f);\n\n if ( ImGui.Button(\"Yes, Clear\", new Vector2(buttonWidth, 0)) )\n {\n _currentContext?.ClearHistory();\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"No, Cancel\", new Vector2(buttonWidth, 0)) )\n {\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.EndPopup();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemizerG2P.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemizerG2P : IPhonemizer\n{\n private readonly IFallbackPhonemizer? _fallback;\n\n private readonly ILexicon _lexicon;\n\n private readonly Regex _linkRegex;\n\n private readonly IPosTagger _posTagger;\n\n private readonly Regex _subtokenRegex;\n\n private readonly string _unk;\n\n private bool _disposed;\n\n public PhonemizerG2P(IPosTagger posTagger, ILexicon lexicon, IFallbackPhonemizer? fallback = null, string unk = \"❓\")\n {\n _posTagger = posTagger ?? throw new ArgumentNullException(nameof(posTagger));\n _fallback = fallback;\n _unk = unk;\n _lexicon = lexicon;\n\n // Initialize regular expressions once for performance\n _linkRegex = new Regex(@\"\\[([^\\]]+)\\]\\(([^\\)]*)\\)\", RegexOptions.Compiled);\n _subtokenRegex = new Regex(\n @\"^[''']+|\\p{Lu}(?=\\p{Lu}\\p{Ll})|(?:^-)?(?:\\d?[,.]?\\d)+|[-_]+|[''']{2,}|\\p{L}*?(?:[''']\\p{L})*?\\p{Ll}(?=\\p{Lu})|\\p{L}+(?:[''']\\p{L})*|[^-_\\p{L}'''\\d]|[''']+$\",\n RegexOptions.Compiled);\n\n _disposed = false;\n }\n\n public async Task ToPhonemesAsync(string text, CancellationToken cancellationToken = default)\n {\n // 1. Preprocess text\n var (processedText, textTokens, features) = Preprocess(text);\n\n // 2. Tag text with POS tagger\n var posTokens = await _posTagger.TagAsync(processedText, cancellationToken);\n\n // 3. Convert to internal token representation\n var tokens = ConvertToTokens(posTokens);\n\n // 4. Apply features from preprocessing\n ApplyFeatures(tokens, textTokens, features);\n\n // 5. Fold left (merge non-head tokens with previous token)\n tokens = FoldLeft(tokens);\n\n // 6. Retokenize (split complex tokens and handle special cases)\n var retokenizedTokens = Retokenize(tokens);\n\n // 7. Process phonemes using lexicon and fallback\n var ctx = new TokenContext();\n await ProcessTokensAsync(retokenizedTokens, ctx, cancellationToken);\n\n // 8. Merge retokenized tokens\n var mergedTokens = MergeRetokenizedTokens(retokenizedTokens);\n\n // 9. Generate final phoneme string\n var phonemes = string.Concat(mergedTokens.Select(t => (t.Phonemes ?? _unk) + t.Whitespace));\n\n return new PhonemeResult(phonemes, mergedTokens);\n }\n\n public void Dispose() { GC.SuppressFinalize(this); }\n\n private List ConvertToTokens(IReadOnlyList posTokens)\n {\n var tokens = new List(posTokens.Count);\n\n foreach ( var pt in posTokens )\n {\n tokens.Add(new Token { Text = pt.Text, Tag = pt.PartOfSpeech ?? string.Empty, Whitespace = pt.IsWhitespace ? \" \" : string.Empty });\n }\n\n return tokens;\n }\n\n private (string ProcessedText, List Tokens, Dictionary Features) Preprocess(string text)\n {\n text = text.TrimStart();\n var result = new StringBuilder(text.Length);\n var tokens = new List();\n var features = new Dictionary();\n\n var lastEnd = 0;\n\n foreach ( Match m in _linkRegex.Matches(text) )\n {\n if ( m.Index > lastEnd )\n {\n var segment = text.Substring(lastEnd, m.Index - lastEnd);\n result.Append(segment);\n tokens.AddRange(segment.Split(' ', StringSplitOptions.RemoveEmptyEntries));\n }\n\n var linkText = m.Groups[1].Value;\n var featureText = m.Groups[2].Value;\n\n object? featureValue = null;\n if ( featureText.Length >= 1 )\n {\n if ( (featureText[0] == '-' || featureText[0] == '+') &&\n int.TryParse(featureText, out var intVal) )\n {\n featureValue = intVal;\n }\n else if ( int.TryParse(featureText, out intVal) )\n {\n featureValue = intVal;\n }\n else if ( featureText == \"0.5\" || featureText == \"+0.5\" )\n {\n featureValue = 0.5;\n }\n else if ( featureText == \"-0.5\" )\n {\n featureValue = -0.5;\n }\n else if ( featureText.Length > 1 )\n {\n var firstChar = featureText[0];\n var lastChar = featureText[featureText.Length - 1];\n\n if ( firstChar == '/' && lastChar == '/' )\n {\n featureValue = firstChar + featureText.Substring(1, featureText.Length - 2);\n }\n else if ( firstChar == '#' && lastChar == '#' )\n {\n featureValue = firstChar + featureText.Substring(1, featureText.Length - 2);\n }\n }\n }\n\n if ( featureValue != null )\n {\n features[tokens.Count] = featureValue;\n }\n\n result.Append(linkText);\n tokens.Add(linkText);\n lastEnd = m.Index + m.Length;\n }\n\n if ( lastEnd < text.Length )\n {\n var segment = text.Substring(lastEnd);\n result.Append(segment);\n tokens.AddRange(segment.Split(' ', StringSplitOptions.RemoveEmptyEntries));\n }\n\n return (result.ToString(), tokens, features);\n }\n\n private void ApplyFeatures(List tokens, List textTokens, Dictionary features)\n {\n if ( features.Count == 0 )\n {\n return;\n }\n\n var alignment = CreateBidirectionalAlignment(textTokens, tokens.Select(t => t.Text).ToList());\n\n foreach ( var kvp in features )\n {\n var sourceIndex = kvp.Key;\n var value = kvp.Value;\n\n var matchedIndices = new List();\n for ( var i = 0; i < alignment.Length; i++ )\n {\n if ( alignment[i] == sourceIndex )\n {\n matchedIndices.Add(i);\n }\n }\n\n for ( var matchCount = 0; matchCount < matchedIndices.Count; matchCount++ )\n {\n var tokenIndex = matchedIndices[matchCount];\n\n if ( tokenIndex >= tokens.Count )\n {\n continue;\n }\n\n if ( value is int intValue )\n {\n tokens[tokenIndex].Stress = intValue;\n }\n else if ( value is double doubleValue )\n {\n tokens[tokenIndex].Stress = doubleValue;\n }\n else if ( value is string strValue )\n {\n if ( strValue.StartsWith(\"/\") )\n {\n // The \"i == 0\" in Python refers to the first match of this feature\n tokens[tokenIndex].IsHead = matchCount == 0;\n tokens[tokenIndex].Phonemes = matchCount == 0 ? strValue.Substring(1) : string.Empty;\n tokens[tokenIndex].Rating = 5;\n }\n else if ( strValue.StartsWith(\"#\") )\n {\n tokens[tokenIndex].NumFlags = strValue.Substring(1);\n }\n }\n }\n }\n }\n\n private int[] CreateBidirectionalAlignment(List source, List target)\n {\n // This is a simplified version - ideally it would match spaCy's algorithm more closely\n var alignment = new int[target.Count];\n\n // Create a combined string from each list to verify they match overall\n var sourceText = string.Join(\"\", source).ToLowerInvariant();\n var targetText = string.Join(\"\", target).ToLowerInvariant();\n\n // Initialize all alignments to no match\n for ( var i = 0; i < alignment.Length; i++ )\n {\n alignment[i] = -1;\n }\n\n var targetIndex = 0;\n var sourcePos = 0;\n\n // Track position in the joined strings to handle multi-token to single token mappings\n for ( var sourceIndex = 0; sourceIndex < source.Count; sourceIndex++ )\n {\n var sourceToken = source[sourceIndex].ToLowerInvariant();\n sourcePos += sourceToken.Length;\n\n var targetPos = 0;\n for ( var i = 0; i < targetIndex; i++ )\n {\n targetPos += target[i].ToLowerInvariant().Length;\n }\n\n // Map all target tokens that overlap with this source token\n while ( targetIndex < target.Count && targetPos < sourcePos )\n {\n var targetToken = target[targetIndex].ToLowerInvariant();\n alignment[targetIndex] = sourceIndex;\n\n targetPos += targetToken.Length;\n targetIndex++;\n }\n }\n\n return alignment;\n }\n\n private List FoldLeft(List tokens)\n {\n if ( tokens.Count <= 1 )\n {\n return tokens;\n }\n\n var result = new List(tokens.Count);\n result.Add(tokens[0]);\n\n for ( var i = 1; i < tokens.Count; i++ )\n {\n if ( !tokens[i].IsHead )\n {\n var merged = Token.MergeTokens(\n [result[^1], tokens[i]],\n _unk);\n\n result[^1] = merged;\n }\n else\n {\n result.Add(tokens[i]);\n }\n }\n\n return result;\n }\n\n private List Retokenize(List tokens)\n {\n var result = new List(tokens.Count * 2); // Estimate capacity\n string? currentCurrency = null;\n\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var token = tokens[i];\n List subtokens;\n\n // Split token if needed\n if ( token.Alias == null && token.Phonemes == null )\n {\n var subTokenTexts = Subtokenize(token.Text);\n subtokens = new List(subTokenTexts.Count);\n\n for ( var j = 0; j < subTokenTexts.Count; j++ )\n {\n subtokens.Add(new Token {\n Text = subTokenTexts[j],\n Tag = token.Tag,\n Whitespace = j == subTokenTexts.Count - 1 ? token.Whitespace : string.Empty,\n IsHead = token.IsHead && j == 0,\n Stress = token.Stress,\n NumFlags = token.NumFlags\n });\n }\n }\n else\n {\n subtokens = new List { token };\n }\n\n // Process each subtoken\n for ( var j = 0; j < subtokens.Count; j++ )\n {\n var t = subtokens[j];\n\n if ( t.Alias != null || t.Phonemes != null )\n {\n // Skip special handling for already processed tokens\n }\n else if ( t.Tag == \"$\" && PhonemizerConstants.Currencies.ContainsKey(t.Text) )\n {\n currentCurrency = t.Text;\n t.Phonemes = string.Empty;\n t.Rating = 4;\n }\n else if ( t is { Tag: \":\", Text: \"-\" or \"–\" } )\n {\n t.Phonemes = \"—\";\n t.Rating = 3;\n }\n else if ( PhonemizerConstants.PunctTags.Contains(t.Tag) )\n {\n if ( PhonemizerConstants.PunctTagPhonemes.TryGetValue(t.Tag, out var phoneme) )\n {\n t.Phonemes = phoneme;\n }\n else\n {\n var sb = new StringBuilder();\n foreach ( var c in t.Text )\n {\n if ( PhonemizerConstants.Puncts.Contains(c) )\n {\n sb.Append(c);\n }\n }\n\n t.Phonemes = sb.ToString();\n }\n\n t.Rating = 4;\n }\n else if ( currentCurrency != null )\n {\n if ( t.Tag != \"CD\" )\n {\n currentCurrency = null;\n }\n else if ( j + 1 == subtokens.Count && (i + 1 == tokens.Count || tokens[i + 1].Tag != \"CD\") )\n {\n t.Currency = currentCurrency;\n }\n }\n else if ( 0 < j && j < subtokens.Count - 1 &&\n t.Text == \"2\" &&\n char.IsLetter(subtokens[j - 1].Text[subtokens[j - 1].Text.Length - 1]) &&\n char.IsLetter(subtokens[j + 1].Text[0]) )\n {\n t.Alias = \"to\";\n }\n\n // Add to result\n if ( t.Alias != null || t.Phonemes != null )\n {\n result.Add(t);\n }\n else if ( result.Count > 0 &&\n result[result.Count - 1] is List lastList &&\n lastList.Count > 0 &&\n string.IsNullOrEmpty(lastList[lastList.Count - 1].Whitespace) )\n {\n t.IsHead = false;\n ((List)result[^1]).Add(t);\n }\n else\n {\n result.Add(string.IsNullOrEmpty(t.Whitespace) ? new List { t } : t);\n }\n }\n }\n\n // Simplify lists with single elements\n for ( var i = 0; i < result.Count; i++ )\n {\n if ( result[i] is List list && list.Count == 1 )\n {\n result[i] = list[0];\n }\n }\n\n return result;\n }\n\n private List Subtokenize(string word)\n {\n var matches = _subtokenRegex.Matches(word);\n if ( matches.Count == 0 )\n {\n return new List { word };\n }\n\n var result = new List(matches.Count);\n foreach ( Match match in matches )\n {\n result.Add(match.Value);\n }\n\n return result;\n }\n\n private async Task ProcessTokensAsync(List tokens, TokenContext ctx, CancellationToken cancellationToken)\n {\n // Process tokens in reverse order\n for ( var i = tokens.Count - 1; i >= 0; i-- )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n return;\n }\n\n if ( tokens[i] is Token token )\n {\n if ( token.Phonemes == null )\n {\n (token.Phonemes, token.Rating) = await GetPhonemesAsync(token, ctx, cancellationToken);\n }\n\n ctx = TokenContext.UpdateContext(ctx, token.Phonemes, token);\n }\n else if ( tokens[i] is List subtokens )\n {\n await ProcessSubtokensAsync(subtokens, ctx, cancellationToken);\n }\n }\n }\n\n private async Task ProcessSubtokensAsync(List tokens, TokenContext ctx, CancellationToken cancellationToken)\n {\n int left = 0,\n right = tokens.Count;\n\n var shouldFallback = false;\n\n while ( left < right )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n return;\n }\n\n if ( tokens.Skip(left).Take(right - left).Any(t => t.Alias != null || t.Phonemes != null) )\n {\n left++;\n\n continue;\n }\n\n var mergedToken = Token.MergeTokens(tokens.Skip(left).Take(right - left).ToList(), _unk);\n var (phonemes, rating) = await GetPhonemesAsync(mergedToken, ctx, cancellationToken);\n\n if ( phonemes != null )\n {\n tokens[left].Phonemes = phonemes;\n tokens[left].Rating = rating;\n\n for ( var i = left + 1; i < right; i++ )\n {\n tokens[i].Phonemes = string.Empty;\n tokens[i].Rating = rating;\n }\n\n ctx = TokenContext.UpdateContext(ctx, phonemes, mergedToken);\n right = left;\n left = 0;\n }\n else if ( left + 1 < right )\n {\n left++;\n }\n else\n {\n right--;\n var t = tokens[right];\n\n if ( t.Phonemes == null )\n {\n if ( t.Text.All(c => PhonemizerConstants.SubtokenJunks.Contains(c)) )\n {\n t.Phonemes = string.Empty;\n t.Rating = 3;\n }\n else if ( _fallback != null )\n {\n shouldFallback = true;\n\n break;\n }\n }\n\n left = 0;\n }\n }\n\n if ( shouldFallback && _fallback != null )\n {\n var mergedToken = Token.MergeTokens(tokens, _unk);\n var (phonemes, rating) = await _fallback.GetPhonemesAsync(mergedToken.Text, cancellationToken);\n\n if ( phonemes != null )\n {\n tokens[0].Phonemes = phonemes;\n tokens[0].Rating = rating;\n\n for ( var j = 1; j < tokens.Count; j++ )\n {\n tokens[j].Phonemes = string.Empty;\n tokens[j].Rating = rating;\n }\n }\n }\n\n ResolveTokens(tokens);\n }\n\n private async Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(Token token, TokenContext ctx, CancellationToken cancellationToken)\n {\n // Try to get from lexicon\n var (phonemes, rating) = _lexicon.ProcessToken(token, ctx);\n\n // If not found, try fallback\n if ( phonemes == null && _fallback != null )\n {\n return await _fallback.GetPhonemesAsync(token.Alias ?? token.Text, cancellationToken);\n }\n\n return (phonemes, rating);\n }\n\n private void ResolveTokens(List tokens)\n {\n // Calculate if there should be space between phonemes\n var text = string.Concat(tokens.Take(tokens.Count - 1).Select(t => t.Text + t.Whitespace)) +\n tokens[tokens.Count - 1].Text;\n\n var prespace = text.Contains(' ') || text.Contains('/') ||\n text.Where(c => !PhonemizerConstants.SubtokenJunks.Contains(c))\n .Select(c => char.IsLetter(c)\n ? 0\n : char.IsDigit(c)\n ? 1\n : 2)\n .Distinct()\n .Count() > 1;\n\n // Handle specific cases\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var t = tokens[i];\n\n if ( t.Phonemes == null )\n {\n if ( i == tokens.Count - 1 && t.Text.Length > 0 &&\n PhonemizerConstants.NonQuotePuncts.Contains(t.Text[0]) )\n {\n t.Phonemes = t.Text;\n t.Rating = 3;\n }\n else if ( t.Text.All(c => PhonemizerConstants.SubtokenJunks.Contains(c)) )\n {\n t.Phonemes = string.Empty;\n t.Rating = 3;\n }\n }\n else if ( i > 0 )\n {\n t.Prespace = prespace;\n }\n }\n\n if ( prespace )\n {\n return;\n }\n\n // Adjust stress patterns\n var indices = new List<(bool HasPrimaryStress, int Weight, int Index)>();\n for ( var i = 0; i < tokens.Count; i++ )\n {\n if ( !string.IsNullOrEmpty(tokens[i].Phonemes) )\n {\n var hasPrimary = tokens[i].Phonemes.Contains(PhonemizerConstants.PrimaryStress);\n indices.Add((hasPrimary, tokens[i].StressWeight(), i));\n }\n }\n\n if ( indices.Count == 2 && tokens[indices[0].Index].Text.Length == 1 )\n {\n var i = indices[1].Index;\n tokens[i].Phonemes = ApplyStress(tokens[i].Phonemes!, -0.5);\n\n return;\n }\n\n if ( indices.Count < 2 || indices.Count(x => x.HasPrimaryStress) <= (indices.Count + 1) / 2 )\n {\n return;\n }\n\n indices.Sort();\n foreach ( var (_, _, i) in indices.Take(indices.Count / 2) )\n {\n tokens[i].Phonemes = ApplyStress(tokens[i].Phonemes!, -0.5);\n }\n }\n\n private string ApplyStress(string phonemes, double stress)\n {\n if ( stress < -1 )\n {\n return phonemes\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty);\n }\n\n if ( stress == -1 || ((stress == 0 || stress == -0.5) && phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return phonemes\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), PhonemizerConstants.SecondaryStress.ToString());\n }\n\n if ( (stress == 0 || stress == 0.5 || stress == 1) &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.SecondaryStress + phonemes);\n }\n\n if ( stress >= 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n return phonemes.Replace(PhonemizerConstants.SecondaryStress.ToString(), PhonemizerConstants.PrimaryStress.ToString());\n }\n\n if ( stress > 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.PrimaryStress + phonemes);\n }\n\n return phonemes;\n }\n\n private string RestressPhonemes(string phonemes)\n {\n var chars = phonemes.ToCharArray();\n var charPositions = new List<(int Position, char Char)>();\n\n for ( var i = 0; i < chars.Length; i++ )\n {\n charPositions.Add((i, chars[i]));\n }\n\n var stressPositions = new Dictionary();\n for ( var i = 0; i < charPositions.Count; i++ )\n {\n if ( PhonemizerConstants.Stresses.Contains(charPositions[i].Char) )\n {\n // Find the next vowel\n var vowelPos = -1;\n for ( var j = i + 1; j < charPositions.Count; j++ )\n {\n if ( PhonemizerConstants.Vowels.Contains(charPositions[j].Char) )\n {\n vowelPos = j;\n\n break;\n }\n }\n\n if ( vowelPos != -1 )\n {\n stressPositions[charPositions[i].Position] = charPositions[vowelPos].Position;\n charPositions[i] = ((int)(vowelPos - 0.5), charPositions[i].Char);\n }\n }\n }\n\n charPositions.Sort((a, b) => a.Position.CompareTo(b.Position));\n\n return new string(charPositions.Select(cp => cp.Char).ToArray());\n }\n\n private List MergeRetokenizedTokens(List retokenizedTokens)\n {\n var result = new List();\n\n foreach ( var item in retokenizedTokens )\n {\n if ( item is Token token )\n {\n result.Add(token);\n }\n else if ( item is List tokens )\n {\n result.Add(Token.MergeTokens(tokens, _unk));\n }\n }\n\n return result;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/OnnxRVC.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class OnnxRVC : IDisposable\n{\n private readonly ArrayPool _arrayPool;\n\n private readonly int _hopSize;\n\n private readonly InferenceSession _model;\n\n private readonly ArrayPool _shortArrayPool;\n\n // Preallocated buffers and tensors\n private readonly DenseTensor _speakerIdTensor;\n\n private readonly ContentVec _vecModel;\n\n public OnnxRVC(string modelPath, int hopsize, string vecPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR\n };\n\n options.AppendExecutionProvider_CUDA();\n \n _model = new InferenceSession(modelPath, options);\n _hopSize = hopsize;\n _vecModel = new ContentVec(vecPath);\n\n // Preallocate the speaker ID tensor\n _speakerIdTensor = new DenseTensor(new[] { 1 });\n\n // Create array pools for temporary buffers\n _arrayPool = ArrayPool.Shared;\n _shortArrayPool = ArrayPool.Shared;\n }\n\n public void Dispose()\n {\n _model?.Dispose();\n _vecModel?.Dispose();\n }\n\n public int ProcessAudio(ReadOnlyMemory inputAudio, Memory outputAudio,\n IF0Predictor f0Predictor, int speakerId, int f0UpKey)\n {\n // Early exit if input is empty\n if ( inputAudio.Length == 0 )\n {\n return 0;\n }\n\n // Check if output buffer is large enough\n if ( outputAudio.Length < inputAudio.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(outputAudio));\n }\n\n // Set the speaker ID\n _speakerIdTensor[0] = speakerId;\n\n // Process the audio\n return ProcessInPlace(inputAudio, outputAudio, f0Predictor, _speakerIdTensor, f0UpKey);\n }\n\n private int ProcessInPlace(ReadOnlyMemory input, Memory output,\n IF0Predictor f0Predictor,\n DenseTensor speakerIdTensor, int f0UpKey)\n {\n const int f0Min = 50;\n const int f0Max = 1100;\n var f0MelMin = 1127 * Math.Log(1 + f0Min / 700.0);\n var f0MelMax = 1127 * Math.Log(1 + f0Max / 700.0);\n\n if ( input.Length / 16000.0 > 30.0 )\n {\n throw new Exception(\"Audio segment is too long (>30s)\");\n }\n\n // Calculate original scale for normalization (matching original implementation)\n var minValue = float.MaxValue;\n var maxValue = float.MinValue;\n var inputSpan = input.Span;\n for ( var i = 0; i < input.Length; i++ )\n {\n minValue = Math.Min(minValue, inputSpan[i]);\n maxValue = Math.Max(maxValue, inputSpan[i]);\n }\n\n var originalScale = maxValue - minValue;\n\n // Get the hubert features\n var hubert = _vecModel.Forward(input);\n\n // Repeat and transpose the features\n var hubertRepeated = RVCUtils.RepeatTensor(hubert, 2);\n hubertRepeated = RVCUtils.Transpose(hubertRepeated, 0, 2, 1);\n\n hubert = null; // Allow for garbage collection\n\n var hubertLength = hubertRepeated.Dimensions[1];\n var hubertLengthTensor = new DenseTensor(new[] { 1 }) { [0] = hubertLength };\n\n // Allocate buffers for F0 calculations\n var f0Buffer = _arrayPool.Rent(hubertLength);\n var f0Memory = new Memory(f0Buffer, 0, hubertLength);\n\n try\n {\n // Calculate F0 directly into buffer\n f0Predictor.ComputeF0(input, f0Memory, hubertLength);\n\n // Create pitch tensors\n var pitchBuffer = _arrayPool.Rent(hubertLength);\n var pitchTensor = new DenseTensor(new[] { 1, hubertLength });\n var pitchfTensor = new DenseTensor(new[] { 1, hubertLength });\n\n try\n {\n // Apply pitch shift and convert to mel scale\n for ( var i = 0; i < hubertLength; i++ )\n {\n // Apply pitch shift\n var shiftedF0 = f0Buffer[i] * (float)Math.Pow(2, f0UpKey / 12.0);\n pitchfTensor[0, i] = shiftedF0;\n\n // Convert to mel scale for pitch\n var f0Mel = 1127 * Math.Log(1 + shiftedF0 / 700.0);\n if ( f0Mel > 0 )\n {\n f0Mel = (f0Mel - f0MelMin) * 254 / (f0MelMax - f0MelMin) + 1;\n f0Mel = Math.Round(f0Mel);\n }\n\n if ( f0Mel <= 1 )\n {\n f0Mel = 1;\n }\n\n if ( f0Mel > 255 )\n {\n f0Mel = 255;\n }\n\n pitchTensor[0, i] = (long)f0Mel;\n }\n\n // Generate random noise tensor\n var rndTensor = new DenseTensor(new[] { 1, 192, hubertLength });\n var random = new Random();\n for ( var i = 0; i < 192 * hubertLength; i++ )\n {\n rndTensor[0, i / hubertLength, i % hubertLength] = (float)random.NextDouble();\n }\n\n // Run the model\n var outWav = Forward(hubertRepeated, hubertLengthTensor, pitchTensor,\n pitchfTensor, speakerIdTensor, rndTensor);\n\n // Apply padding to match original implementation\n // (adding padding at the end only, like in original Pad method)\n var paddedSize = outWav.Length + 2 * _hopSize;\n var paddedOutput = _shortArrayPool.Rent(paddedSize);\n try\n {\n // Copy original output to the beginning of padded output\n for ( var i = 0; i < outWav.Length; i++ )\n {\n paddedOutput[i] = outWav[i];\n }\n // Rest of array is already zeroed when rented from pool\n\n // Find min and max values for normalization\n var minOutValue = short.MaxValue;\n var maxOutValue = short.MinValue;\n for ( var i = 0; i < outWav.Length; i++ )\n {\n minOutValue = Math.Min(minOutValue, outWav[i]);\n maxOutValue = Math.Max(maxOutValue, outWav[i]);\n }\n\n // Copy the output to the buffer with normalization matching original\n var outputSpan = output.Span;\n if ( outputSpan.Length < paddedSize )\n {\n throw new InvalidOperationException($\"Output buffer too small. Needed {paddedSize}, but only had {outputSpan.Length}\");\n }\n\n var maxLen = Math.Min(paddedSize, outputSpan.Length);\n\n // Apply normalization that matches the original implementation\n float range = maxOutValue - minOutValue;\n if ( range > 0 )\n {\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = paddedOutput[i] * originalScale / range;\n }\n }\n else\n {\n // Handle edge case where all values are the same\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = 0;\n }\n }\n\n return outWav.Length;\n }\n finally\n {\n _shortArrayPool.Return(paddedOutput);\n }\n }\n finally\n {\n _arrayPool.Return(pitchBuffer);\n }\n }\n finally\n {\n _arrayPool.Return(f0Buffer);\n }\n }\n\n private short[] Forward(DenseTensor hubert, DenseTensor hubertLength,\n DenseTensor pitch, DenseTensor pitchf,\n DenseTensor speakerId, DenseTensor noise)\n {\n var inputs = new List {\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(0), hubert),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(1), hubertLength),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(2), pitch),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(3), pitchf),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(4), speakerId),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(5), noise)\n };\n\n var results = _model.Run(inputs);\n var output = results.First().AsTensor();\n\n return output.Select(x => (short)(x * 32767)).ToArray();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadDetector.cs", "using System.Buffers;\nusing System.Runtime.CompilerServices;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroVadDetector : IVadDetector\n{\n private readonly int _minSilenceSamples;\n\n private readonly int _minSpeechSamples;\n\n private readonly SileroVadOnnxModel _model;\n\n private readonly float _negThreshold;\n\n private readonly float _threshold;\n\n public SileroVadDetector(VadDetectorOptions vadDetectorOptions, SileroVadOptions sileroVadOptions)\n {\n _model = new SileroVadOnnxModel(sileroVadOptions.ModelPath);\n _threshold = sileroVadOptions.Threshold;\n _negThreshold = _threshold - sileroVadOptions.ThresholdGap;\n _minSpeechSamples = (int)(16d * vadDetectorOptions.MinSpeechDuration.TotalMilliseconds);\n _minSilenceSamples = (int)(16d * vadDetectorOptions.MinSilenceDuration.TotalMilliseconds);\n }\n\n public async IAsyncEnumerable DetectSegmentsAsync(IAudioSource source, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n ValidateSource(source);\n\n foreach ( var segment in DetectSegments(await source.GetSamplesAsync(0, cancellationToken: cancellationToken)) )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n yield return segment;\n }\n }\n\n private IEnumerable DetectSegments(Memory samples)\n {\n var state = _model.CreateInferenceState();\n int? startingIndex = null;\n int? startingSilenceIndex = null;\n\n for ( var i = 0; i < samples.Length - SileroConstants.BatchSize; i += SileroConstants.BatchSize )\n {\n Memory slice;\n float[]? rentedMemory = null;\n try\n {\n if ( i == 0 )\n {\n // the first batch will have the empty context (which we need to copy at the beggining of the slice)\n rentedMemory = ArrayPool.Shared.Rent(SileroConstants.ContextSize + SileroConstants.BatchSize);\n Array.Clear(rentedMemory, 0, SileroConstants.ContextSize);\n samples.Span.Slice(0, SileroConstants.BatchSize).CopyTo(rentedMemory.AsSpan(SileroConstants.ContextSize));\n slice = rentedMemory.AsMemory(0, SileroConstants.BatchSize + SileroConstants.ContextSize);\n }\n else\n {\n slice = samples.Slice(i - SileroConstants.ContextSize, SileroConstants.BatchSize + SileroConstants.ContextSize);\n }\n\n var prob = _model.Call(slice, state);\n if ( !startingIndex.HasValue )\n {\n if ( prob > _threshold )\n {\n startingIndex = i;\n }\n\n continue;\n }\n\n // We are in speech\n if ( prob > _threshold )\n {\n startingSilenceIndex = null;\n\n continue;\n }\n\n if ( prob > _negThreshold )\n {\n // We are still in speech and the current batch is between the threshold and the negative threshold\n // We continue to the next batch\n continue;\n }\n\n if ( startingSilenceIndex == null )\n {\n startingSilenceIndex = i;\n\n continue;\n }\n\n var silenceLength = i - startingSilenceIndex.Value;\n\n if ( silenceLength > _minSilenceSamples )\n {\n // We have silence after speech exceeding the minimum silence duration\n var length = i - startingIndex.Value;\n if ( length >= _minSpeechSamples )\n {\n yield return new VadSegment { StartTime = TimeSpan.FromMilliseconds(startingIndex.Value * 1000d / SileroConstants.SampleRate), Duration = TimeSpan.FromMilliseconds(length * 1000d / SileroConstants.SampleRate) };\n }\n\n startingIndex = null;\n startingSilenceIndex = null;\n }\n }\n finally\n {\n if ( rentedMemory != null )\n {\n ArrayPool.Shared.Return(rentedMemory, ArrayPoolConfig.ClearOnReturn);\n }\n }\n }\n\n // The last segment if it was already started (might be incomplete for sources that are not yet finished)\n if ( startingIndex.HasValue )\n {\n var length = samples.Length - startingIndex.Value;\n if ( length >= _minSpeechSamples )\n {\n yield return new VadSegment { StartTime = TimeSpan.FromMilliseconds(startingIndex.Value * 1000d / SileroConstants.SampleRate), Duration = TimeSpan.FromMilliseconds(length * 1000d / SileroConstants.SampleRate), IsIncomplete = true };\n }\n }\n }\n\n private static void ValidateSource(IAudioSource source)\n {\n if ( source.ChannelCount != 1 )\n {\n throw new NotSupportedException(\"Only mono-channel audio is supported. Consider one channel aggregation on the audio source.\");\n }\n\n if ( source.SampleRate != 16000 )\n {\n throw new NotSupportedException(\"Only 16 kHz audio is supported. Consider resampling before calling this transcriptor.\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OpenNlpPosTagger.cs", "using System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nusing OpenNLP.Tools.PosTagger;\nusing OpenNLP.Tools.Tokenize;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of OpenNLP-based POS tagger with spaCy-like currency handling\n/// \npublic partial class OpenNlpPosTagger : IPosTagger\n{\n private readonly Regex _currencySymbolRegex = CurrencyRegex();\n\n private readonly ILogger _logger;\n\n private readonly EnglishMaximumEntropyPosTagger _posTagger;\n\n private readonly EnglishRuleBasedTokenizer _tokenizer;\n\n private bool _disposed;\n\n public OpenNlpPosTagger(string modelPath, ILogger logger)\n {\n if ( string.IsNullOrEmpty(modelPath) )\n {\n throw new ArgumentException(\"Model path cannot be null or empty\", nameof(modelPath));\n }\n\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n try\n {\n _tokenizer = new EnglishRuleBasedTokenizer(false);\n _posTagger = new EnglishMaximumEntropyPosTagger(modelPath);\n _logger.LogInformation(\"Initialized OpenNLP POS tagger from {ModelPath}\", modelPath);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to initialize OpenNLP POS tagger\");\n\n throw;\n }\n }\n\n /// \n /// Tags parts of speech in text using OpenNLP with spaCy-like currency handling\n /// \n public Task> TagAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Task.FromResult>(Array.Empty());\n }\n\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Pre-process text to insert spaces between currency symbols and digits\n // This makes the tokenizer split currency symbols from amounts, similar to spaCy\n var currencyRegex = CurrencyWithNumRegex();\n var processedText = currencyRegex.Replace(text, \"$1 $2\");\n\n // Tokenize pre-processed text\n var tokens = _tokenizer.Tokenize(processedText);\n\n // Get POS tags\n var tags = _posTagger.Tag(tokens);\n\n // Post-process to assign \"$\" tag to currency symbols\n for ( var i = 0; i < tokens.Length; i++ )\n {\n if ( _currencySymbolRegex.IsMatch(tokens[i]) )\n {\n tags[i] = \"$\"; // Assign \"$\" tag to currency symbols (spaCy-like behavior)\n }\n }\n\n // Build result tokens with whitespace\n var result = new List();\n var currentPosition = 0;\n\n for ( var i = 0; i < tokens.Length; i++ )\n {\n var token = tokens[i];\n var tag = tags[i];\n\n // Find token position in processed text\n var tokenPosition = processedText.IndexOf(token, currentPosition, StringComparison.Ordinal);\n\n // Extract whitespace between tokens\n var whitespace = \"\";\n if ( i < tokens.Length - 1 )\n {\n var nextTokenStart = processedText.IndexOf(tokens[i + 1], tokenPosition + token.Length, StringComparison.Ordinal);\n if ( nextTokenStart >= 0 )\n {\n whitespace = processedText.Substring(\n tokenPosition + token.Length,\n nextTokenStart - (tokenPosition + token.Length));\n }\n }\n else\n {\n // Last token - get any remaining whitespace\n whitespace = tokenPosition + token.Length < processedText.Length\n ? processedText[(tokenPosition + token.Length)..]\n : \"\";\n }\n\n result.Add(new PosToken { Text = token, PartOfSpeech = tag, IsWhitespace = whitespace.Contains(\" \") });\n\n currentPosition = tokenPosition + token.Length;\n }\n\n return Task.FromResult>(result);\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"POS tagging was canceled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during POS tagging\");\n\n throw;\n }\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n }\n\n [GeneratedRegex(@\"([\\$\\€\\£\\¥\\₹])(\\d)\")]\n private static partial Regex CurrencyWithNumRegex();\n\n [GeneratedRegex(@\"^[\\$\\€\\£\\¥\\₹]$\")] private static partial Regex CurrencyRegex();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Context/ConversationContext.cs", "using System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Text.Json;\n\nusing Microsoft.Extensions.Options;\nusing Microsoft.SemanticKernel.ChatCompletion;\n\nusing OpenAI.Chat;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\nusing ChatMessage = PersonaEngine.Lib.Core.Conversation.Abstractions.Context.ChatMessage;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Context;\n\npublic class ConversationContext : IConversationContext\n{\n private readonly IConversationCleanupStrategy? _cleanupStrategy;\n\n private readonly Dictionary _currentMessageBuffers = new();\n\n private readonly List _history = new();\n\n private readonly Lock _lock = new();\n\n private readonly IDisposable? _optionsMonitorRegistration;\n\n private readonly Dictionary _participants;\n\n private readonly HashSet _participantsReadyToCommit = new();\n\n private Guid _currentTurnId = Guid.Empty;\n\n private HashSet _currentTurnParticipantIds = new();\n\n private string? _currentVisualContext;\n\n private ConversationContextOptions _options;\n\n private bool _turnInterrupted = false;\n\n private DateTimeOffset _turnStartTime;\n\n public ConversationContext(\n IEnumerable initialParticipants,\n IOptionsMonitor optionsMonitor,\n IConversationCleanupStrategy? cleanupStrategy = null)\n {\n _participants = initialParticipants.ToDictionary(p => p.Id);\n _options = optionsMonitor.CurrentValue;\n _cleanupStrategy = cleanupStrategy ?? new MaxTurnsCleanupStrategy(100);\n _optionsMonitorRegistration = optionsMonitor.OnChange(newOptions =>\n {\n lock (_lock)\n {\n if ( newOptions.SystemPromptFile != _options.SystemPromptFile )\n {\n PromptUtils.ClearCache();\n }\n\n _options = newOptions;\n }\n });\n }\n\n public event EventHandler? ConversationUpdated;\n\n public IReadOnlyDictionary Participants\n {\n get\n {\n lock (_lock)\n {\n return new ReadOnlyDictionary(_participants);\n }\n }\n }\n\n public IReadOnlyList History\n {\n get\n {\n lock (_lock)\n {\n return _history.AsReadOnly();\n }\n }\n }\n\n public string? CurrentVisualContext\n {\n get\n {\n lock (_lock)\n {\n return _currentVisualContext;\n }\n }\n set\n {\n lock (_lock)\n {\n _currentVisualContext = value;\n OnConversationUpdated();\n }\n }\n }\n\n public bool TryAddParticipant(ParticipantInfo participant)\n {\n lock (_lock)\n {\n var added = _participants.TryAdd(participant.Id, participant);\n if ( added )\n {\n OnConversationUpdated();\n }\n\n return added;\n }\n }\n\n public bool TryRemoveParticipant(string participantId)\n {\n lock (_lock)\n {\n var removed = _participants.Remove(participantId);\n if ( removed )\n {\n // Optional: Decide if removing a participant should affect ongoing turns\n // e.g., remove them from _currentTurnParticipantIds if turn is active?\n // Current implementation doesn't automatically remove from active turn.\n OnConversationUpdated();\n }\n\n return removed;\n }\n }\n\n #region Cleanup\n\n public void ApplyCleanupStrategy()\n {\n if ( _cleanupStrategy == null )\n {\n return;\n }\n\n lock (_lock)\n {\n if ( _cleanupStrategy.Cleanup(_history, _options, _participants) )\n {\n OnConversationUpdated();\n }\n }\n }\n\n public void ClearHistory()\n {\n lock (_lock)\n {\n if ( _history.Count <= 0 )\n {\n return;\n }\n\n _history.Clear();\n OnConversationUpdated();\n }\n }\n\n public void Dispose() { Dispose(true); }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( disposing )\n {\n _optionsMonitorRegistration?.Dispose();\n }\n }\n\n #endregion\n\n #region Private Helpers\n\n protected virtual void OnConversationUpdated()\n {\n var handler = ConversationUpdated;\n handler?.Invoke(this, EventArgs.Empty);\n }\n\n private void InternalAbortTurn(bool raiseEvent = true)\n {\n var wasActive = _currentTurnId != Guid.Empty;\n\n _currentTurnId = Guid.Empty;\n _currentMessageBuffers.Clear();\n _participantsReadyToCommit.Clear();\n _currentTurnParticipantIds.Clear();\n _turnInterrupted = false;\n\n if ( wasActive && raiseEvent )\n {\n OnConversationUpdated();\n }\n }\n\n private void FinalizeCurrentTurn()\n {\n if ( _currentTurnId == Guid.Empty )\n {\n return;\n }\n\n var turn = _history.FirstOrDefault(t => t.TurnId == _currentTurnId);\n\n if ( turn != null )\n {\n turn.EndTime = DateTimeOffset.UtcNow;\n turn.WasInterrupted = _turnInterrupted;\n }\n\n _currentTurnId = Guid.Empty;\n _currentMessageBuffers.Clear();\n _participantsReadyToCommit.Clear();\n _currentTurnParticipantIds.Clear();\n _turnInterrupted = false;\n }\n\n private InteractionTurn? CreatePendingTurnSnapshot()\n {\n if ( _currentTurnId == Guid.Empty || _currentMessageBuffers.Count == 0 )\n {\n return null;\n }\n\n var pendingMessages = new List();\n foreach ( var (participantId, buffer) in _currentMessageBuffers )\n {\n var text = buffer.ToString();\n\n if ( string.IsNullOrWhiteSpace(text) || !_participants.TryGetValue(participantId, out var participantInfo) )\n {\n continue;\n }\n\n var snapshotMessage = new ChatMessage(\n Guid.NewGuid(),\n participantId,\n participantInfo.Name,\n text,\n _turnStartTime,\n true,\n participantInfo.Role\n );\n\n pendingMessages.Add(snapshotMessage);\n }\n\n if ( pendingMessages.Count == 0 )\n {\n return null;\n }\n\n return new InteractionTurn(\n _currentTurnId,\n _currentTurnParticipantIds,\n _turnStartTime,\n null,\n pendingMessages,\n _turnInterrupted\n );\n }\n\n private void AddMessageToSkHistory(ChatHistory skChatHistory, ChatMessage message)\n {\n var role = message.Role;\n var content = message.Text;\n\n if ( role != ChatMessageRole.Assistant && role != ChatMessageRole.System )\n {\n content = $\"[{message.ParticipantName}]{message.Text}\";\n\n role = ChatMessageRole.User;\n }\n\n skChatHistory.AddMessage(GetAuthorRole(role), content);\n }\n\n private AuthorRole GetAuthorRole(ChatMessageRole role)\n {\n return role switch {\n ChatMessageRole.System => AuthorRole.System,\n ChatMessageRole.Assistant => AuthorRole.Assistant,\n ChatMessageRole.User => AuthorRole.User,\n ChatMessageRole.Developer => AuthorRole.Developer,\n ChatMessageRole.Tool => AuthorRole.Tool,\n ChatMessageRole.Function => AuthorRole.Tool,\n _ => throw new ArgumentOutOfRangeException(nameof(role), role, null)\n };\n }\n\n #endregion\n\n #region Message Management\n\n public bool TryUpdateMessage(Guid turnId, Guid messageId, string newText)\n {\n lock (_lock)\n {\n var turn = _history.FirstOrDefault(t => t.TurnId == turnId);\n var message = turn?.Messages.FirstOrDefault(m => m.MessageId == messageId);\n if ( message != null && message.Text != newText )\n {\n message.Text = newText;\n OnConversationUpdated();\n\n return true;\n }\n\n return false;\n }\n }\n\n public bool TryDeleteMessage(Guid turnId, Guid messageId)\n {\n lock (_lock)\n {\n var turn = _history.FirstOrDefault(t => t.TurnId == turnId);\n if ( turn != null )\n {\n var messageToRemove = turn.Messages.FirstOrDefault(m => m.MessageId == messageId);\n if ( messageToRemove == null )\n {\n return false;\n }\n\n var messageRemoved = turn.Messages.Remove(messageToRemove);\n var turnRemoved = false;\n if ( turn.Messages.Count == 0 )\n {\n turnRemoved = _history.Remove(turn);\n }\n\n if ( messageRemoved || turnRemoved )\n {\n OnConversationUpdated();\n\n return true;\n }\n\n return true;\n }\n\n return false;\n }\n }\n\n #endregion\n\n #region Turn Management\n\n public void StartTurn(Guid turnId, IEnumerable participantIds)\n {\n lock (_lock)\n {\n if ( _currentTurnId != Guid.Empty && _currentMessageBuffers.Count > 0 )\n {\n Debug.WriteLine($\"Warning: Starting new turn {turnId} while previous turn {_currentTurnId} was pending. Aborting previous turn.\");\n InternalAbortTurn();\n }\n\n _currentTurnId = turnId;\n _currentTurnParticipantIds = new HashSet(participantIds.Distinct());\n\n foreach ( var id in _currentTurnParticipantIds )\n {\n if ( !_participants.ContainsKey(id) )\n {\n InternalAbortTurn(false);\n\n throw new ArgumentException($\"Participant with ID '{id}' not found in the conversation context.\", nameof(participantIds));\n }\n }\n\n _currentMessageBuffers.Clear();\n _participantsReadyToCommit.Clear();\n _turnStartTime = DateTimeOffset.UtcNow;\n _turnInterrupted = false;\n\n foreach ( var id in _currentTurnParticipantIds )\n {\n _currentMessageBuffers[id] = new StringBuilder();\n }\n }\n }\n\n public void AppendToTurn(string participantId, string chunk)\n {\n lock (_lock)\n {\n if ( _currentTurnId == Guid.Empty )\n {\n throw new InvalidOperationException(\"Cannot append to turn: No turn is currently active.\");\n }\n\n if ( !_currentTurnParticipantIds.Contains(participantId) )\n {\n throw new InvalidOperationException($\"Participant '{participantId}' is not designated as part of the current turn (ID: {_currentTurnId}).\");\n }\n\n if ( !_currentMessageBuffers.TryGetValue(participantId, out var buffer) )\n {\n buffer = new StringBuilder();\n _currentMessageBuffers[participantId] = buffer;\n Debug.WriteLine($\"Warning: Buffer for participant {participantId} was missing in AppendToTurn.\");\n }\n\n buffer.Append(chunk);\n OnConversationUpdated();\n }\n }\n\n public string GetPendingMessageText(string participantId)\n {\n lock (_lock)\n {\n if ( _currentTurnId == Guid.Empty )\n {\n return string.Empty;\n }\n\n if ( _currentMessageBuffers.TryGetValue(participantId, out var buffer) )\n {\n return buffer.ToString();\n }\n\n return string.Empty;\n }\n }\n\n public void CompleteTurnPart(string participantId, bool interrupted = false)\n {\n lock (_lock)\n {\n if ( _currentTurnId == Guid.Empty )\n {\n return;\n }\n\n if ( !_currentTurnParticipantIds.Contains(participantId) )\n {\n return;\n }\n\n if ( _participantsReadyToCommit.Contains(participantId) )\n {\n return;\n }\n\n if ( !_currentMessageBuffers.TryGetValue(participantId, out var buffer) || buffer.Length == 0 )\n {\n Debug.WriteLine($\"Debug: CompleteTurnPart called for participant {participantId} in turn {_currentTurnId} with no message content.\");\n }\n\n if ( _participants.TryGetValue(participantId, out var participantInfo) )\n {\n var text = buffer!.ToString();\n var message = new ChatMessage(\n Guid.NewGuid(),\n participantId,\n participantInfo.Name,\n text,\n DateTimeOffset.UtcNow,\n false,\n participantInfo.Role\n );\n\n var turn = _history.FirstOrDefault(t => t.TurnId == _currentTurnId);\n if ( turn == null )\n {\n turn = new InteractionTurn(\n _currentTurnId,\n _currentTurnParticipantIds,\n _turnStartTime,\n null,\n new List { message },\n interrupted\n );\n\n _history.Add(turn);\n ApplyCleanupStrategy();\n }\n else\n {\n turn.Messages.Add(message);\n turn.WasInterrupted = turn.WasInterrupted || interrupted;\n }\n\n _currentMessageBuffers.Remove(participantId);\n }\n else\n {\n return;\n }\n\n _participantsReadyToCommit.Add(participantId);\n _turnInterrupted = _turnInterrupted || interrupted;\n\n if ( _participantsReadyToCommit.IsSupersetOf(_currentTurnParticipantIds) )\n {\n FinalizeCurrentTurn();\n }\n\n OnConversationUpdated();\n }\n }\n\n public void AbortTurn()\n {\n lock (_lock)\n {\n InternalAbortTurn();\n }\n }\n\n #endregion\n\n #region History & Projection\n\n public InteractionTurn? PendingTurn\n {\n get\n {\n lock (_lock)\n {\n return CreatePendingTurnSnapshot();\n }\n }\n }\n\n public IReadOnlyList GetProjectedHistory()\n {\n lock (_lock)\n {\n var projectedHistory = new List(_history);\n var pendingTurn = CreatePendingTurnSnapshot();\n if ( pendingTurn != null )\n {\n projectedHistory.Add(pendingTurn);\n }\n\n return projectedHistory.AsReadOnly();\n }\n }\n\n public ChatHistory GetSemanticKernelChatHistory(bool includePendingTurn = true)\n {\n lock (_lock)\n {\n var skChatHistory = new ChatHistory();\n\n // 1. Add System Prompt (from options)\n if ( !string.IsNullOrWhiteSpace(_options.SystemPrompt) )\n {\n skChatHistory.AddSystemMessage(_options.SystemPrompt);\n }\n else if ( !string.IsNullOrWhiteSpace(_options.SystemPromptFile) && PromptUtils.TryGetPrompt(_options.SystemPromptFile, out var systemPrompt) )\n {\n skChatHistory.AddSystemMessage(systemPrompt!);\n }\n\n // 2. Add Metadata Message\n var metadata = new { topics = _options.Topics, context = _options.CurrentContext ?? string.Empty, visual_context = _currentVisualContext ?? string.Empty };\n var serializedMetadata = JsonSerializer.Serialize(metadata, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });\n skChatHistory.AddUserMessage(serializedMetadata);\n\n // 3. Add Committed History Messages\n foreach ( var message in _history.SelectMany(turn => turn.Messages) )\n {\n AddMessageToSkHistory(skChatHistory, message);\n }\n\n // 4. Optionally Add Pending Turn Messages\n if ( includePendingTurn )\n {\n var pendingTurn = CreatePendingTurnSnapshot();\n if ( pendingTurn == null )\n {\n return skChatHistory;\n }\n\n foreach ( var message in pendingTurn.Messages )\n {\n AddMessageToSkHistory(skChatHistory, message);\n }\n }\n\n return skChatHistory;\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismRenderer_OpenGLES2.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic class CubismRenderer_OpenGLES2 : CubismRenderer\n{\n public const int ColorChannelCount = 4; // 実験時に1チャンネルの場合は1、RGBだけの場合は3、アルファも含める場合は4\n\n public const int ClippingMaskMaxCountOnDefault = 36; // 通常のフレームバッファ1枚あたりのマスク最大数\n\n public const int ClippingMaskMaxCountOnMultiRenderTexture = 32; // フレームバッファが2枚以上ある場合のフレームバッファ1枚あたりのマスク最大数\n\n /// \n /// マスク描画用のフレームバッファ\n /// \n private readonly List _offscreenFrameBuffers = [];\n\n /// \n /// OpenGLのステートを保持するオブジェクト\n /// \n private readonly CubismRendererProfile_OpenGLES2 _rendererProfile;\n\n /// \n /// 描画オブジェクトのインデックスを描画順に並べたリスト\n /// \n private readonly int[] _sortedDrawableIndexList;\n\n /// \n /// モデルが参照するテクスチャとレンダラでバインドしているテクスチャとのマップ\n /// \n private readonly Dictionary _textures;\n\n private readonly OpenGLApi GL;\n\n /// \n /// クリッピングマスク管理オブジェクト\n /// \n private CubismClippingManager_OpenGLES2? _clippingManager;\n\n internal CubismShader_OpenGLES2 Shader;\n\n internal VBO[] vbo = new VBO[512];\n\n public CubismRenderer_OpenGLES2(OpenGLApi gl, CubismModel model, int maskBufferCount = 1) : base(model)\n {\n GL = gl;\n Shader = new CubismShader_OpenGLES2(gl);\n _rendererProfile = new CubismRendererProfile_OpenGLES2(gl);\n _textures = new Dictionary(32);\n\n VertexArray = GL.GenVertexArray();\n VertexBuffer = GL.GenBuffer();\n IndexBuffer = GL.GenBuffer();\n\n // 1未満は1に補正する\n if ( maskBufferCount < 1 )\n {\n maskBufferCount = 1;\n CubismLog.Warning(\"[Live2D SDK]The number of render textures must be an integer greater than or equal to 1. Set the number of render textures to 1.\");\n }\n\n if ( model.IsUsingMasking() )\n {\n _clippingManager = new CubismClippingManager_OpenGLES2(GL); //クリッピングマスク・バッファ前処理方式を初期化\n _clippingManager.Initialize(model, maskBufferCount);\n\n _offscreenFrameBuffers.Clear();\n for ( var i = 0; i < maskBufferCount; ++i )\n {\n var offscreenSurface = new CubismOffscreenSurface_OpenGLES2(GL);\n offscreenSurface.CreateOffscreenSurface((int)_clippingManager.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n _offscreenFrameBuffers.Add(offscreenSurface);\n }\n }\n\n _sortedDrawableIndexList = new int[model.GetDrawableCount()];\n }\n\n /// \n /// マスクテクスチャに描画するためのクリッピングコンテキスト\n /// \n internal CubismClippingContext? ClippingContextBufferForMask { get; set; }\n\n /// \n /// 画面上描画するためのクリッピングコンテキスト\n /// \n internal CubismClippingContext? ClippingContextBufferForDraw { get; set; }\n\n internal int VertexArray { get; private set; }\n\n internal int VertexBuffer { get; private set; }\n\n internal int IndexBuffer { get; private set; }\n\n /// \n /// Tegraプロセッサ対応。拡張方式による描画の有効・無効\n /// \n /// trueなら拡張方式で描画する\n /// trueなら拡張方式のPA設定を有効にする\n public void SetExtShaderMode(bool extMode, bool extPAMode = false)\n {\n Shader.SetExtShaderMode(extMode, extPAMode);\n Shader.ReleaseShaderProgram();\n }\n\n /// \n /// OpenGLテクスチャのバインド処理\n /// CubismRendererにテクスチャを設定し、CubismRenderer中でその画像を参照するためのIndex値を戻り値とする\n /// \n /// セットするモデルテクスチャの番号\n /// OpenGLテクスチャの番号\n public void BindTexture(int modelTextureNo, int glTextureNo) { _textures[modelTextureNo] = glTextureNo; }\n\n /// \n /// OpenGLにバインドされたテクスチャのリストを取得する\n /// \n /// テクスチャのアドレスのリスト\n public Dictionary GetBindedTextures() { return _textures; }\n\n /// \n /// クリッピングマスクバッファのサイズを設定する\n /// マスク用のFrameBufferを破棄・再作成するため処理コストは高い。\n /// \n /// クリッピングマスクバッファのサイズ\n /// クリッピングマスクバッファのサイズ\n public void SetClippingMaskBufferSize(float width, float height)\n {\n if ( _clippingManager == null )\n {\n return;\n }\n\n // インスタンス破棄前にレンダーテクスチャの数を保存\n var renderTextureCount = _clippingManager.RenderTextureCount;\n\n _clippingManager = new CubismClippingManager_OpenGLES2(GL);\n\n _clippingManager.SetClippingMaskBufferSize(width, height);\n\n _clippingManager.Initialize(Model, renderTextureCount);\n }\n\n /// \n /// クリッピングマスクのバッファを取得する\n /// \n /// クリッピングマスクのバッファへのポインタ\n public CubismOffscreenSurface_OpenGLES2 GetMaskBuffer(int index) { return _offscreenFrameBuffers[index]; }\n\n internal override unsafe void DrawMesh(int textureNo, int indexCount, int vertexCount\n , ushort* indexArray, float* vertexArray, float* uvArray\n , float opacity, CubismBlendMode colorBlendMode, bool invertedMask)\n {\n throw new Exception(\"[Live2D Core]Use 'DrawMeshOpenGL' function\");\n }\n\n public bool IsGeneratingMask() { return ClippingContextBufferForMask != null; }\n\n /// \n /// [オーバーライド]\n /// 描画オブジェクト(アートメッシュ)を描画する。\n /// ポリゴンメッシュとテクスチャ番号をセットで渡す。\n /// \n /// 描画するテクスチャ番号\n /// 描画オブジェクトのインデックス値\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュのインデックス配列\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 乗算色\n /// スクリーン色\n /// 不透明度\n /// カラー合成タイプ\n /// マスク使用時のマスクの反転使用\n internal unsafe void DrawMeshOpenGL(CubismModel model, int index)\n {\n if ( _textures[model.GetDrawableTextureIndex(index)] == 0 )\n {\n return; // モデルが参照するテクスチャがバインドされていない場合は描画をスキップする\n }\n\n // 裏面描画の有効・無効\n if ( IsCulling )\n {\n GL.Enable(GL.GL_CULL_FACE);\n }\n else\n {\n GL.Disable(GL.GL_CULL_FACE);\n }\n\n GL.FrontFace(GL.GL_CCW); // Cubism SDK OpenGLはマスク・アートメッシュ共にCCWが表面\n\n var vertexCount = model.GetDrawableVertexCount(index);\n var vertexArray = model.GetDrawableVertices(index);\n var uvArray = (float*)model.GetDrawableVertexUvs(index);\n\n GL.BindVertexArray(VertexArray);\n\n if ( vbo == null || vbo.Length < vertexCount )\n {\n vbo = new VBO[vertexCount];\n }\n\n for ( var a = 0; a < vertexCount; a++ )\n {\n vbo[a].ver0 = vertexArray[a * 2];\n vbo[a].ver1 = vertexArray[a * 2 + 1];\n vbo[a].uv0 = uvArray[a * 2];\n vbo[a].uv1 = uvArray[a * 2 + 1];\n }\n\n var indexCount = model.GetDrawableVertexIndexCount(index);\n var indexArray = model.GetDrawableVertexIndices(index);\n\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, VertexBuffer);\n fixed (void* p = vbo)\n {\n GL.BufferData(GL.GL_ARRAY_BUFFER, vertexCount * sizeof(VBO), new IntPtr(p), GL.GL_STATIC_DRAW);\n }\n\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n GL.BufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(ushort), new IntPtr(indexArray), GL.GL_STATIC_DRAW);\n\n if ( IsGeneratingMask() ) // マスク生成時\n {\n Shader.SetupShaderProgramForMask(this, model, index);\n }\n else\n {\n Shader.SetupShaderProgramForDraw(this, model, index);\n }\n\n // ポリゴンメッシュを描画する\n GL.DrawElements(GL.GL_TRIANGLES, indexCount, GL.GL_UNSIGNED_SHORT, 0);\n\n // 後処理\n GL.UseProgram(0);\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, 0);\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);\n GL.BindVertexArray(0);\n ClippingContextBufferForDraw = null;\n ClippingContextBufferForMask = null;\n }\n\n /// \n /// 描画開始時の追加処理。\n /// モデルを描画する前にクリッピングマスクに必要な処理を実装している。\n /// \n internal void PreDraw()\n {\n GL.Disable(GL.GL_SCISSOR_TEST);\n GL.Disable(GL.GL_STENCIL_TEST);\n GL.Disable(GL.GL_DEPTH_TEST);\n\n GL.Enable(GL.GL_BLEND);\n GL.ColorMask(true, true, true, true);\n\n if ( GL.IsPhoneES2 )\n {\n GL.BindVertexArrayOES(0);\n }\n\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, 0); //前にバッファがバインドされていたら破棄する必要がある\n\n //異方性フィルタリング。プラットフォームのOpenGLによっては未対応の場合があるので、未設定のときは設定しない\n if ( Anisotropy > 0.0f )\n {\n for ( var i = 0; i < _textures.Count; i++ )\n {\n GL.BindTexture(GL.GL_TEXTURE_2D, _textures[i]);\n GL.TexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, Anisotropy);\n }\n }\n }\n\n /// \n /// モデル描画直前のOpenGLES2のステートを保持する\n /// \n protected override void SaveProfile() { _rendererProfile.Save(); }\n\n /// \n /// モデル描画直前のOpenGLES2のステートを保持する\n /// \n protected override void RestoreProfile() { _rendererProfile.Restore(); }\n\n protected override unsafe void DoDrawModel()\n {\n //------------ クリッピングマスク・バッファ前処理方式の場合 ------------\n if ( _clippingManager != null )\n {\n PreDraw();\n\n // サイズが違う場合はここで作成しなおし\n for ( var i = 0; i < _clippingManager.RenderTextureCount; ++i )\n {\n if ( _offscreenFrameBuffers[i].BufferWidth != (uint)_clippingManager.ClippingMaskBufferSize.X ||\n _offscreenFrameBuffers[i].BufferHeight != (uint)_clippingManager.ClippingMaskBufferSize.Y )\n {\n _offscreenFrameBuffers[i].CreateOffscreenSurface(\n (int)_clippingManager.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n }\n }\n\n if ( UseHighPrecisionMask )\n {\n _clippingManager.SetupMatrixForHighPrecision(Model, false);\n }\n else\n {\n _clippingManager.SetupClippingContext(Model, this, _rendererProfile.LastFBO, _rendererProfile.LastViewport);\n }\n }\n\n // 上記クリッピング処理内でも一度PreDrawを呼ぶので注意!!\n PreDraw();\n\n var drawableCount = Model.GetDrawableCount();\n var renderOrder = Model.GetDrawableRenderOrders();\n\n // インデックスを描画順でソート\n for ( var i = 0; i < drawableCount; ++i )\n {\n var order = renderOrder[i];\n _sortedDrawableIndexList[order] = i;\n }\n\n if ( GL.AlwaysClear )\n {\n GL.ClearColor(ClearColor.R,\n ClearColor.G,\n ClearColor.B,\n ClearColor.A);\n\n GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n }\n\n // 描画\n for ( var i = 0; i < drawableCount; ++i )\n {\n var drawableIndex = _sortedDrawableIndexList[i];\n\n // Drawableが表示状態でなければ処理をパスする\n if ( !Model.GetDrawableDynamicFlagIsVisible(drawableIndex) )\n {\n continue;\n }\n\n // クリッピングマスク\n var clipContext = _clippingManager?.ClippingContextListForDraw[drawableIndex];\n\n if ( clipContext != null && UseHighPrecisionMask ) // マスクを書く必要がある\n {\n if ( clipContext.IsUsing ) // 書くことになっていた\n {\n // 生成したFrameBufferと同じサイズでビューポートを設定\n GL.Viewport(0, 0, (int)_clippingManager!.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n\n PreDraw(); // バッファをクリアする\n\n // ---------- マスク描画処理 ----------\n // マスク用RenderTextureをactiveにセット\n GetMaskBuffer(clipContext.BufferIndex).BeginDraw(_rendererProfile.LastFBO);\n\n // マスクをクリアする\n // 1が無効(描かれない)領域、0が有効(描かれる)領域。(シェーダで Cd*Csで0に近い値をかけてマスクを作る。1をかけると何も起こらない)\n GL.ClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n GL.Clear(GL.GL_COLOR_BUFFER_BIT);\n }\n\n {\n var clipDrawCount = clipContext.ClippingIdCount;\n for ( var index = 0; index < clipDrawCount; index++ )\n {\n var clipDrawIndex = clipContext.ClippingIdList[index];\n\n // 頂点情報が更新されておらず、信頼性がない場合は描画をパスする\n if ( !Model.GetDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex) )\n {\n continue;\n }\n\n IsCulling = Model.GetDrawableCulling(clipDrawIndex);\n\n // 今回専用の変換を適用して描く\n // チャンネルも切り替える必要がある(A,R,G,B)\n ClippingContextBufferForMask = clipContext;\n\n DrawMeshOpenGL(Model, clipDrawIndex);\n }\n }\n\n {\n // --- 後処理 ---\n GetMaskBuffer(clipContext.BufferIndex).EndDraw();\n ClippingContextBufferForMask = null;\n GL.Viewport(_rendererProfile.LastViewport[0], _rendererProfile.LastViewport[1], _rendererProfile.LastViewport[2], _rendererProfile.LastViewport[3]);\n\n PreDraw(); // バッファをクリアする\n }\n }\n\n // クリッピングマスクをセットする\n ClippingContextBufferForDraw = clipContext;\n\n IsCulling = Model.GetDrawableCulling(drawableIndex);\n\n DrawMeshOpenGL(Model, drawableIndex);\n }\n }\n\n public override void Dispose() { Shader.ReleaseShaderProgram(); }\n\n public int GetBindedTextureId(int textureId) { return _textures[textureId] != 0 ? _textures[textureId] : -1; }\n\n [StructLayout(LayoutKind.Sequential, Pack = 4)]\n internal struct VBO\n {\n public float ver0;\n\n public float ver1;\n\n public float uv0;\n\n public float uv1;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/RealtimeTranscriptor.cs", "using System.Diagnostics;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.ASR.VAD;\nusing PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\ninternal class RealtimeTranscriptor : IRealtimeSpeechTranscriptor, IAsyncDisposable\n{\n private readonly object cacheLock = new();\n\n private readonly ILogger logger;\n\n private readonly RealtimeSpeechTranscriptorOptions options;\n\n private readonly RealtimeOptions realtimeOptions;\n\n private readonly ISpeechTranscriptorFactory? recognizingSpeechTranscriptorFactory;\n\n private readonly ISpeechTranscriptorFactory speechTranscriptorFactory;\n\n private readonly Dictionary transcriptorCache;\n\n private readonly IVadDetector vadDetector;\n\n private TimeSpan _lastDuration = TimeSpan.Zero;\n\n private TimeSpan _processedDuration = TimeSpan.Zero;\n\n private bool isDisposed;\n\n public RealtimeTranscriptor(\n ISpeechTranscriptorFactory speechTranscriptorFactory,\n IVadDetector vadDetector,\n ISpeechTranscriptorFactory? recognizingSpeechTranscriptorFactory,\n RealtimeSpeechTranscriptorOptions options,\n RealtimeOptions realtimeOptions,\n ILogger logger)\n {\n this.speechTranscriptorFactory = speechTranscriptorFactory;\n this.vadDetector = vadDetector;\n this.recognizingSpeechTranscriptorFactory = recognizingSpeechTranscriptorFactory;\n this.options = options;\n this.realtimeOptions = realtimeOptions;\n this.logger = logger;\n transcriptorCache = new Dictionary();\n\n logger.LogDebug(\"RealtimeTranscriptor initialized with options: {@Options}, realtime options: {@RealtimeOptions}\",\n options, realtimeOptions);\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( isDisposed )\n {\n return;\n }\n\n // lock (cacheLock)\n // {\n logger.LogInformation(\"Disposing {Count} cached transcriptors\", transcriptorCache.Count);\n foreach ( var transcriptor in transcriptorCache.Values )\n {\n await transcriptor.DisposeAsync();\n }\n\n transcriptorCache.Clear();\n // }\n\n isDisposed = true;\n GC.SuppressFinalize(this);\n }\n\n public async IAsyncEnumerable TranscribeAsync(\n IAwaitableAudioSource source,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n if ( isDisposed )\n {\n throw new ObjectDisposedException(nameof(RealtimeTranscriptor));\n }\n\n var stopwatch = Stopwatch.StartNew();\n var promptBuilder = new StringBuilder(options.Prompt);\n CultureInfo? detectedLanguage = null;\n\n await source.WaitForInitializationAsync(cancellationToken);\n var sessionId = Guid.NewGuid().ToString();\n\n logger.LogInformation(\"Starting transcription session {SessionId}\", sessionId);\n\n yield return new RealtimeSessionStarted(sessionId);\n\n try\n {\n while ( !source.IsFlushed )\n {\n var currentDuration = source.Duration;\n\n if ( currentDuration == _lastDuration )\n {\n await source.WaitForNewSamplesAsync(_lastDuration + realtimeOptions.ProcessingInterval, cancellationToken);\n\n continue;\n }\n\n logger.LogTrace(\"Processing new audio segment: Current={Current}ms, Last={Last}ms, Delta={Delta}ms\",\n currentDuration.TotalMilliseconds,\n _lastDuration.TotalMilliseconds,\n (currentDuration - _lastDuration).TotalMilliseconds);\n\n _lastDuration = currentDuration;\n var segmentStopwatch = Stopwatch.StartNew();\n var slicedSource = new SliceAudioSource(source, _processedDuration, currentDuration - _processedDuration);\n\n VadSegment? lastNonFinalSegment = null;\n VadSegment? recognizingSegment = null;\n\n await foreach ( var segment in vadDetector.DetectSegmentsAsync(slicedSource, cancellationToken) )\n {\n if ( segment.IsIncomplete )\n {\n recognizingSegment = segment;\n\n continue;\n }\n\n var segmentEnd = segment.StartTime + segment.Duration;\n lastNonFinalSegment = segment;\n\n logger.LogDebug(\"Processing VAD segment: Start={Start}ms, Duration={Duration}ms\",\n segment.StartTime.TotalMilliseconds,\n segment.Duration.TotalMilliseconds);\n\n var transcribeStopwatch = Stopwatch.StartNew();\n var transcribingEvents = TranscribeSegments(\n speechTranscriptorFactory,\n source,\n _processedDuration,\n segment.StartTime,\n segment.Duration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segmentData in transcribingEvents )\n {\n if ( options.AutodetectLanguageOnce )\n {\n detectedLanguage = segmentData.Language;\n }\n\n if ( realtimeOptions.ConcatenateSegmentsToPrompt )\n {\n promptBuilder.Append(segmentData.Text);\n }\n\n logger.LogDebug(\n \"Segment recognized: SessionId={SessionId}, Duration={Duration}ms, ProcessingTime={ProcessingTime}ms\",\n sessionId,\n segmentData.Duration.TotalMilliseconds,\n transcribeStopwatch.ElapsedMilliseconds);\n\n yield return new RealtimeSegmentRecognized(segmentData, sessionId);\n }\n }\n\n if ( options.IncludeSpeechRecogizingEvents && recognizingSegment != null )\n {\n logger.LogDebug(\"Processing recognizing segment: Duration={Duration}ms\",\n recognizingSegment.Duration.TotalMilliseconds);\n\n var transcribingEvents = TranscribeSegments(\n recognizingSpeechTranscriptorFactory ?? speechTranscriptorFactory,\n source,\n _processedDuration,\n recognizingSegment.StartTime,\n recognizingSegment.Duration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segment in transcribingEvents )\n {\n yield return new RealtimeSegmentRecognizing(segment, sessionId);\n }\n }\n\n HandleSegmentProcessing(source, ref _processedDuration, lastNonFinalSegment, recognizingSegment, _lastDuration);\n\n logger.LogTrace(\"Segment processing completed in {ElapsedTime}ms\",\n segmentStopwatch.ElapsedMilliseconds);\n }\n\n var finalStopwatch = Stopwatch.StartNew();\n var lastEvents = TranscribeSegments(\n speechTranscriptorFactory,\n source,\n _processedDuration,\n TimeSpan.Zero,\n source.Duration - _processedDuration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segmentData in lastEvents )\n {\n if ( realtimeOptions.ConcatenateSegmentsToPrompt )\n {\n promptBuilder.Append(segmentData.Text);\n }\n\n yield return new RealtimeSegmentRecognized(segmentData, sessionId);\n }\n\n logger.LogInformation(\n \"Transcription session completed: SessionId={SessionId}, TotalDuration={TotalDuration}ms, TotalProcessingTime={TotalTime}ms\",\n sessionId,\n source.Duration.TotalMilliseconds,\n stopwatch.ElapsedMilliseconds);\n\n yield return new RealtimeSessionStopped(sessionId);\n }\n finally\n {\n await CleanupSessionAsync(sessionId);\n }\n }\n\n private void HandleSegmentProcessing(\n IAudioSource source,\n ref TimeSpan processedDuration,\n VadSegment? lastNonFinalSegment,\n VadSegment? recognizingSegment,\n TimeSpan lastDuration)\n {\n if ( lastNonFinalSegment != null )\n {\n var skippingDuration = lastNonFinalSegment.StartTime + lastNonFinalSegment.Duration;\n processedDuration += skippingDuration;\n\n if ( source is IDiscardableAudioSource discardableSource )\n {\n var lastSegmentEndFrameIndex = (int)(skippingDuration.TotalMilliseconds * source.SampleRate / 1000d) - 1;\n discardableSource.DiscardFrames(lastSegmentEndFrameIndex);\n logger.LogTrace(\"Discarded frames up to index {FrameIndex}\", lastSegmentEndFrameIndex);\n }\n }\n else if ( recognizingSegment == null )\n {\n if ( lastDuration - processedDuration > realtimeOptions.SilenceDiscardInterval )\n {\n var silenceDurationToDiscard = TimeSpan.FromTicks(realtimeOptions.SilenceDiscardInterval.Ticks / 2);\n processedDuration += silenceDurationToDiscard;\n\n if ( source is IDiscardableAudioSource discardableSource )\n {\n var halfSilenceIndex = (int)(silenceDurationToDiscard.TotalMilliseconds * source.SampleRate / 1000d) - 1;\n discardableSource.DiscardFrames(halfSilenceIndex);\n logger.LogTrace(\"Discarded silence frames up to index {FrameIndex}\", halfSilenceIndex);\n }\n }\n }\n }\n\n private async IAsyncEnumerable TranscribeSegments(\n ISpeechTranscriptorFactory transcriptorFactory,\n IAudioSource source,\n TimeSpan processedDuration,\n TimeSpan startTime,\n TimeSpan duration,\n StringBuilder promptBuilder,\n CultureInfo? detectedLanguage,\n string sessionId,\n [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n if ( duration < realtimeOptions.MinTranscriptDuration )\n {\n yield break;\n }\n\n startTime += processedDuration;\n var paddedStart = startTime - realtimeOptions.PaddingDuration;\n\n if ( paddedStart < processedDuration )\n {\n paddedStart = processedDuration;\n }\n\n var paddedDuration = duration + realtimeOptions.PaddingDuration;\n\n using IAudioSource paddedSource = paddedDuration < realtimeOptions.MinDurationWithPadding\n ? GetSilenceAddedSource(source, paddedStart, paddedDuration)\n : new SliceAudioSource(source, paddedStart, paddedDuration);\n\n var languageAutodetect = options.LanguageAutoDetect;\n var language = options.Language;\n\n if ( languageAutodetect && options.AutodetectLanguageOnce && detectedLanguage != null )\n {\n languageAutodetect = false;\n language = detectedLanguage;\n }\n\n var currentOptions = options with { Prompt = realtimeOptions.ConcatenateSegmentsToPrompt ? promptBuilder.ToString() : options.Prompt, LanguageAutoDetect = languageAutodetect, Language = language };\n\n var transcriptor = GetOrCreateTranscriptor(transcriptorFactory, currentOptions, sessionId);\n\n await foreach ( var segment in transcriptor.TranscribeAsync(paddedSource, cancellationToken) )\n {\n segment.StartTime += processedDuration;\n\n yield return segment;\n }\n }\n\n private ISpeechTranscriptor GetOrCreateTranscriptor(\n ISpeechTranscriptorFactory factory,\n RealtimeSpeechTranscriptorOptions currentOptions,\n string sessionId)\n {\n var cacheKey = $\"{sessionId}_{factory.GetHashCode()}\";\n\n lock (cacheLock)\n {\n if ( !transcriptorCache.TryGetValue(cacheKey, out var transcriptor) )\n {\n transcriptor = factory.Create(currentOptions);\n transcriptorCache.Add(cacheKey, transcriptor);\n }\n\n return transcriptor;\n }\n }\n\n private async ValueTask CleanupSessionAsync(string sessionId)\n {\n // lock (cacheLock)\n // {\n var keysToRemove = transcriptorCache.Keys\n .Where(k => k.StartsWith($\"{sessionId}_\"))\n .ToList();\n\n foreach ( var key in keysToRemove )\n {\n if ( !transcriptorCache.TryGetValue(key, out var transcriptor) )\n {\n continue;\n }\n\n await transcriptor.DisposeAsync();\n transcriptorCache.Remove(key);\n }\n // }\n }\n\n private ConcatAudioSource GetSilenceAddedSource(IAudioSource source, TimeSpan paddedStart, TimeSpan paddedDuration)\n {\n var silenceDuration = new TimeSpan((realtimeOptions.MinDurationWithPadding.Ticks - paddedDuration.Ticks) / 2);\n var preSilence = new SilenceAudioSource(silenceDuration, source.SampleRate, source.Metadata, source.ChannelCount, source.BitsPerSample);\n var postSilence = new SilenceAudioSource(silenceDuration, source.SampleRate, source.Metadata, source.ChannelCount, source.BitsPerSample);\n\n return new ConcatAudioSource([preSilence, new SliceAudioSource(source, paddedStart, paddedDuration), postSilence], source.Metadata);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionQueueManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーション再生の管理用クラス。CubismMotionモーションなどACubismMotionのサブクラスを再生するために使用する。\n/// 再生中に別のモーションが StartMotion()された場合は、新しいモーションに滑らかに変化し旧モーションは中断する。\n/// 表情用モーション、体用モーションなどを分けてモーション化した場合など、\n/// 複数のモーションを同時に再生させる場合は、複数のCubismMotionQueueManagerインスタンスを使用する。\n/// \npublic class CubismMotionQueueManager\n{\n private readonly List _remove = [];\n\n /// \n /// モーション\n /// \n protected readonly List Motions = [];\n\n /// \n /// コールバック関数ポインタ\n /// \n private CubismMotionEventFunction? _eventCallback;\n\n /// \n /// コールバックに戻されるデータ\n /// \n private CubismUserModel? _eventCustomData;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n protected float UserTimeSeconds;\n\n /// \n /// 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。\n /// \n /// 開始するモーション\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotion(ACubismMotion motion)\n {\n CubismMotionQueueEntry motionQueueEntry;\n\n // 既にモーションがあれば終了フラグを立てる\n for ( var i = 0; i < Motions.Count; ++i )\n {\n motionQueueEntry = Motions[0];\n if ( motionQueueEntry == null )\n {\n continue;\n }\n\n motionQueueEntry.SetFadeout(motionQueueEntry.Motion.FadeOutSeconds);\n }\n\n motionQueueEntry = new CubismMotionQueueEntry { Motion = motion };\n\n Motions.Add(motionQueueEntry);\n\n return motionQueueEntry;\n }\n\n /// \n /// 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。\n /// \n /// 開始するモーション\n /// 再生が終了したモーションのインスタンスを削除するなら true\n /// デルタ時間の積算値[秒]\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n [Obsolete(\"Please use StartMotion(ACubismMotion motion\")]\n public CubismMotionQueueEntry StartMotion(ACubismMotion motion, float userTimeSeconds)\n {\n CubismLog.Warning(\"StartMotion(ACubismMotion motion, float userTimeSeconds) is a deprecated function. Please use StartMotion(ACubismMotion motion).\");\n\n CubismMotionQueueEntry motionQueueEntry;\n\n // 既にモーションがあれば終了フラグを立てる\n for ( var i = 0; i < Motions.Count; ++i )\n {\n motionQueueEntry = Motions[i];\n if ( motionQueueEntry == null )\n {\n continue;\n }\n\n motionQueueEntry.SetFadeout(motionQueueEntry.Motion.FadeOutSeconds);\n }\n\n motionQueueEntry = new CubismMotionQueueEntry { Motion = motion }; // 終了時に破棄する\n\n Motions.Add(motionQueueEntry);\n\n return motionQueueEntry;\n }\n\n /// \n /// すべてのモーションが終了しているかどうか。\n /// \n /// \n /// true すべて終了している\n /// false 終了していない\n /// \n public bool IsFinished()\n {\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n foreach ( var item in Motions )\n {\n // ----- 終了済みの処理があれば削除する ------\n if ( !item.Finished )\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// 指定したモーションが終了しているかどうか。\n /// \n /// モーションの識別番号\n /// \n /// true 指定したモーションは終了している\n /// false 終了していない\n /// \n public bool IsFinished(object motionQueueEntryNumber)\n {\n // 既にモーションがあれば終了フラグを立てる\n\n foreach ( var item in Motions )\n {\n if ( item == null )\n {\n continue;\n }\n\n if ( item == motionQueueEntryNumber && !item.Finished )\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// すべてのモーションを停止する。\n /// \n public void StopAllMotions()\n {\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n\n Motions.Clear();\n }\n\n /// \n /// 指定したCubismMotionQueueEntryを取得する。\n /// \n /// モーションの識別番号\n /// \n /// 指定したCubismMotionQueueEntryへのポインタ\n /// NULL 見つからなかった\n /// \n public CubismMotionQueueEntry? GetCubismMotionQueueEntry(object motionQueueEntryNumber)\n {\n //------- 処理を行う --------\n //既にモーションがあれば終了フラグを立てる\n\n foreach ( var item in Motions )\n {\n if ( item == motionQueueEntryNumber )\n {\n return item;\n }\n }\n\n return null;\n }\n\n /// \n /// イベントを受け取るCallbackの登録をする。\n /// \n /// コールバック関数\n /// コールバックに返されるデータ\n public void SetEventCallback(CubismMotionEventFunction callback, CubismUserModel customData)\n {\n _eventCallback = callback;\n _eventCustomData = customData;\n }\n\n /// \n /// モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間の積算値[秒]\n /// \n /// true モデルへパラメータ値の反映あり\n /// false モデルへパラメータ値の反映なし(モーションの変化なし)\n /// \n public virtual bool DoUpdateMotion(CubismModel model, float userTimeSeconds)\n {\n var updated = false;\n\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n\n _remove.Clear();\n\n for ( var motionIndex = Motions.Count - 1; motionIndex >= 0; motionIndex-- )\n {\n var item = Motions[motionIndex];\n var motion = item.Motion;\n\n // ------ 値を反映する ------\n motion.UpdateParameters(model, item, userTimeSeconds);\n updated = true;\n\n // ------ ユーザトリガーイベントを検査する ----\n var firedList = motion.GetFiredEvent(\n item.LastEventCheckSeconds - item.StartTime,\n userTimeSeconds - item.StartTime);\n\n for ( var i = 0; i < firedList.Count; ++i )\n {\n _eventCallback?.Invoke(_eventCustomData, firedList[i]);\n }\n\n item.LastEventCheckSeconds = userTimeSeconds;\n\n // ----- 終了済みの処理があれば削除する ------\n if ( item.Finished )\n {\n _remove.Add(item); // 削除\n }\n else\n {\n if ( item.IsTriggeredFadeOut )\n {\n item.StartFadeout(item.FadeOutSeconds, userTimeSeconds);\n }\n }\n }\n\n foreach ( var item in _remove )\n {\n Motions.Remove(item);\n }\n\n return updated;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Adapters/Audio/Input/MicrophoneInputAdapter.cs", "using System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\n\nusing OpenAI.Chat;\n\nusing PersonaEngine.Lib.ASR.Transcriber;\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Input;\n\nusing Polly;\nusing Polly.Contrib.WaitAndRetry;\nusing Polly.Retry;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Input;\n\npublic sealed class MicrophoneInputAdapter(\n IMicrophone microphone,\n IRealtimeSpeechTranscriptor speechTranscriptor,\n ILogger logger)\n : IAudioInputAdapter\n{\n private readonly AsyncRetryPolicy _transcriptionRetyPolicy = Policy\n .Handle()\n .Or(ex => ex is not OperationCanceledException)\n .WaitAndRetryAsync(Backoff.ExponentialBackoff(TimeSpan.FromMilliseconds(1000), 3),\n async (exception, timespan, retryAttempt, context) =>\n {\n var sessionId = context.TryGetValue(\"sessionId\", out var value) ? (Guid)value : Guid.Empty;\n logger.LogWarning(\"Transcription failed/stopped for session {SessionId}. Retrying in {Timespan}. Attempt {RetryAttempt}...\",\n sessionId, timespan, retryAttempt);\n\n await Task.CompletedTask;\n });\n\n private ChannelWriter? _inputWriter;\n\n private bool _isDisposed;\n\n private Guid? _sessionId;\n\n private CancellationTokenSource? _transcriptionCts;\n\n private Task? _transcriptionTask;\n\n public Guid AdapterId { get; } = Guid.NewGuid();\n\n public ParticipantInfo Participant { get; } = new(Guid.NewGuid().ToString(), \"User\", ChatMessageRole.User);\n\n public IAwaitableAudioSource GetAudioSource() { return microphone; }\n\n public ValueTask InitializeAsync(Guid sessionId, ChannelWriter inputWriter, CancellationToken cancellationToken)\n {\n ObjectDisposedException.ThrowIf(_isDisposed, this);\n\n if ( _transcriptionTask is not null && !_transcriptionTask.IsCompleted )\n {\n logger.LogWarning(\"Adapter is already running. Initialization skipped.\");\n\n return ValueTask.CompletedTask;\n }\n\n _sessionId = sessionId;\n _inputWriter = inputWriter ?? throw new ArgumentNullException(nameof(inputWriter));\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StartAsync(CancellationToken cancellationToken)\n {\n ObjectDisposedException.ThrowIf(_isDisposed, this);\n\n if ( _inputWriter is null || _sessionId is null )\n {\n throw new InvalidOperationException(\"Adapter must be initialized before starting.\");\n }\n\n if ( _transcriptionTask is not null && !_transcriptionTask.IsCompleted )\n {\n logger.LogInformation(\"Transcription task is already running.\");\n\n return ValueTask.CompletedTask;\n }\n\n _transcriptionCts?.Dispose();\n _transcriptionCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n var localCt = _transcriptionCts.Token;\n var localWriter = _inputWriter;\n var localSessionId = _sessionId.Value;\n\n microphone.StartRecording();\n\n _transcriptionTask = Task.Run(async () => await TranscriptionJobWithRetry(localSessionId, localWriter, localCt), localCt);\n\n return ValueTask.CompletedTask;\n }\n\n public async ValueTask StopAsync(CancellationToken cancellationToken)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n logger.LogDebug(\"Stopping microphone recording and transcription task.\");\n microphone.StopRecording();\n\n if ( _transcriptionCts is { IsCancellationRequested: false } )\n {\n await _transcriptionCts.CancelAsync();\n }\n\n if ( _transcriptionTask != null )\n {\n try\n {\n await _transcriptionTask.WaitAsync(cancellationToken);\n }\n catch (OperationCanceledException)\n {\n logger.LogInformation(\"Transcription task cancellation confirmed during stop.\");\n }\n catch (Exception ex)\n {\n logger.LogError(ex, \"Exception waiting for transcription task to complete during stop: {Message}\", ex.Message);\n }\n finally\n {\n _transcriptionTask = null;\n }\n }\n\n _transcriptionCts?.Dispose();\n _transcriptionCts = null;\n _inputWriter = null;\n _sessionId = null;\n\n logger.LogDebug(\"Adapter stopped.\");\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _isDisposed )\n {\n return;\n }\n\n await StopAsync(CancellationToken.None);\n\n _transcriptionCts?.Dispose();\n\n _isDisposed = true;\n }\n\n private async ValueTask TranscriptionJobWithRetry(Guid sessionId, ChannelWriter writer, CancellationToken ct)\n {\n logger.LogDebug(\"Transcription job starting for session {SessionId}.\", sessionId);\n var pollyContext = new Polly.Context($\"TranscriptionJob_{sessionId}\") { [\"sessionId\"] = sessionId };\n\n try\n {\n await _transcriptionRetyPolicy.ExecuteAsync(\n async (_, token) => await RunTranscriptionLoop(sessionId, writer, token),\n pollyContext,\n ct);\n }\n catch (OperationCanceledException)\n {\n logger.LogDebug(\"Transcription job cancelled for session {SessionId}.\", sessionId);\n }\n catch (Exception ex) when (ex is not OperationCanceledException)\n {\n logger.LogError(ex, \"Unhandled error during transcription job for session {SessionId} after retries (if any): {Message}\", sessionId, ex.Message);\n }\n finally\n {\n logger.LogInformation(\"Transcription job execution flow completed for session {SessionId}.\", sessionId);\n }\n }\n\n private async ValueTask RunTranscriptionLoop(Guid sessionId, ChannelWriter writer, CancellationToken ct)\n {\n logger.LogDebug(\"Transcription job starting for session {SessionId}.\", sessionId);\n\n var eventsLoop = speechTranscriptor.TranscribeAsync(microphone, ct);\n\n await foreach ( var transcriptionEvent in eventsLoop )\n {\n if ( transcriptionEvent is RealtimeSessionStopped )\n {\n throw new RestartTranscriptionException();\n }\n\n if ( transcriptionEvent is not IRealtimeTranscriptionSegment transcriptionEventSeg )\n {\n continue;\n }\n\n var inputEvent = MapToInputEvent(transcriptionEventSeg, sessionId);\n\n if ( inputEvent != null )\n {\n await writer.WriteAsync(inputEvent, ct);\n }\n }\n }\n\n private IInputEvent? MapToInputEvent(IRealtimeTranscriptionSegment transcriptionEvent, Guid sessionId)\n {\n return transcriptionEvent switch {\n RealtimeSegmentRecognized recognized => new SttSegmentRecognized(\n sessionId,\n DateTimeOffset.UtcNow,\n Participant.Id,\n recognized.Segment.Text,\n recognized.Segment.Duration,\n recognized.Segment.ConfidenceLevel),\n\n RealtimeSegmentRecognizing recognizing => new SttSegmentRecognizing(\n sessionId,\n DateTimeOffset.UtcNow,\n Participant.Id,\n recognizing.Segment.Text,\n recognizing.Segment.Duration),\n\n _ => null\n };\n }\n\n private class RestartTranscriptionException() : Exception(\"Transcription session stopped and needs restart.\");\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppWavFileHandler.cs", "using System.Text;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\npublic class WavFileInfo\n{\n public int _bitsPerSample;\n\n public string _fileName;\n\n public int _numberOfChannels;\n\n public int _samplePerChannel;\n\n public int _samplingRate;\n}\n\npublic class LAppWavFileHandler\n{\n private readonly ByteReader _byteReader;\n\n private readonly WavFileInfo _wavFileInfo;\n\n private double _lastRms;\n\n private float[] _pcmData;\n\n private double _sampleOffset;\n\n private double _userTimeSeconds;\n\n public LAppWavFileHandler()\n {\n _pcmData = Array.Empty();\n _userTimeSeconds = 0.0;\n _lastRms = 0.0;\n _sampleOffset = 0.0;\n _wavFileInfo = new WavFileInfo();\n _byteReader = new ByteReader();\n }\n\n public bool Update(float deltaTimeSeconds)\n {\n double goalOffset;\n float rms;\n\n // データロード前/ファイル末尾に達した場合は更新しない\n if ( _pcmData == null || _sampleOffset >= _wavFileInfo._samplePerChannel )\n {\n _lastRms = 0.0f;\n\n return false;\n }\n\n // 経過時間後の状態を保持\n _userTimeSeconds += deltaTimeSeconds;\n goalOffset = Math.Floor(_userTimeSeconds * _wavFileInfo._samplingRate);\n if ( goalOffset > _wavFileInfo._samplePerChannel )\n {\n goalOffset = _wavFileInfo._samplePerChannel;\n }\n\n // RMS計測\n rms = 0.0f;\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n for ( var sampleCount = (int)_sampleOffset; sampleCount < goalOffset; sampleCount++ )\n {\n var index = sampleCount * _wavFileInfo._numberOfChannels + channelCount;\n if ( index >= _pcmData.Length )\n {\n // Ensure we do not go out of bounds\n break;\n }\n\n var pcm = _pcmData[index];\n rms += pcm * pcm;\n }\n }\n\n rms = (float)Math.Sqrt(rms / (_wavFileInfo._numberOfChannels * (goalOffset - _sampleOffset)));\n\n _lastRms = rms;\n _sampleOffset = goalOffset;\n\n return true;\n }\n\n public void Start(string filePath)\n {\n // サンプル位参照位置を初期化\n _sampleOffset = 0;\n _userTimeSeconds = 0.0f;\n\n // RMS値をリセット\n _lastRms = 0.0f;\n }\n\n public double GetRms() { return _lastRms; }\n\n public async Task LoadWavFile(string filePath)\n {\n if ( _pcmData != null )\n {\n ReleasePcmData();\n }\n\n // ファイルロード\n var response = await FetchAsync(filePath);\n if ( response != null )\n {\n // Process the response to load PCM data\n return await AsyncWavFileManager(filePath);\n }\n\n return false;\n }\n\n private async Task FetchAsync(string filePath) { return await Task.Run(() => File.ReadAllBytes(filePath)); }\n\n public async Task AsyncWavFileManager(string filePath)\n {\n var ret = false;\n _byteReader._fileByte = await FetchAsync(filePath);\n _byteReader._fileDataView = new MemoryStream(_byteReader._fileByte);\n _byteReader._fileSize = _byteReader._fileByte.Length;\n _byteReader._readOffset = 0;\n\n // Check if file load failed or if there is not enough size for the signature \"RIFF\"\n if ( _byteReader._fileByte == null || _byteReader._fileSize < 4 )\n {\n return false;\n }\n\n // File name\n _wavFileInfo._fileName = filePath;\n\n try\n {\n // Signature \"RIFF\"\n if ( !_byteReader.GetCheckSignature(\"RIFF\") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'RIFF'.\");\n }\n\n // File size - 8 (skip)\n _byteReader.Get32LittleEndian();\n // Signature \"WAVE\"\n if ( !_byteReader.GetCheckSignature(\"WAVE\") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'WAVE'.\");\n }\n\n // Signature \"fmt \"\n if ( !_byteReader.GetCheckSignature(\"fmt \") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'fmt'.\");\n }\n\n // fmt chunk size\n var fmtChunkSize = (int)_byteReader.Get32LittleEndian();\n // Format ID must be 1 (linear PCM)\n if ( _byteReader.Get16LittleEndian() != 1 )\n {\n ret = false;\n\n throw new Exception(\"File is not linear PCM.\");\n }\n\n // Number of channels\n _wavFileInfo._numberOfChannels = (int)_byteReader.Get16LittleEndian();\n // Sampling rate\n _wavFileInfo._samplingRate = (int)_byteReader.Get32LittleEndian();\n // Data rate [byte/sec] (skip)\n _byteReader.Get32LittleEndian();\n // Block size (skip)\n _byteReader.Get16LittleEndian();\n // Bits per sample\n _wavFileInfo._bitsPerSample = (int)_byteReader.Get16LittleEndian();\n // Skip the extended part of the fmt chunk\n if ( fmtChunkSize > 16 )\n {\n _byteReader._readOffset += fmtChunkSize - 16;\n }\n\n // Skip until \"data\" chunk appears\n while ( !_byteReader.GetCheckSignature(\"data\") && _byteReader._readOffset < _byteReader._fileSize )\n {\n _byteReader._readOffset += (int)_byteReader.Get32LittleEndian() + 4;\n }\n\n // \"data\" chunk not found in the file\n if ( _byteReader._readOffset >= _byteReader._fileSize )\n {\n ret = false;\n\n throw new Exception(\"Cannot find 'data' Chunk.\");\n }\n\n // Number of samples\n {\n var dataChunkSize = (int)_byteReader.Get32LittleEndian();\n _wavFileInfo._samplePerChannel = dataChunkSize * 8 / (_wavFileInfo._bitsPerSample * _wavFileInfo._numberOfChannels);\n }\n\n // Allocate memory\n _pcmData = new float[_wavFileInfo._numberOfChannels * _wavFileInfo._samplePerChannel];\n // Retrieve waveform data\n for ( var sampleCount = 0; sampleCount < _wavFileInfo._samplePerChannel; sampleCount++ )\n {\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n _pcmData[sampleCount * _wavFileInfo._numberOfChannels + channelCount] = GetPcmSample();\n }\n }\n\n ret = true;\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n\n return ret;\n }\n\n public float GetPcmSample()\n {\n int pcm32;\n\n // Expand to 32-bit width and round to the range -1 to 1\n switch ( _wavFileInfo._bitsPerSample )\n {\n case 8:\n pcm32 = _byteReader.Get8() - 128;\n pcm32 <<= 24;\n\n break;\n case 16:\n pcm32 = (int)_byteReader.Get16LittleEndian() << 16;\n\n break;\n case 24:\n pcm32 = (int)_byteReader.Get24LittleEndian() << 8;\n\n break;\n default:\n // Unsupported bit width\n pcm32 = 0;\n\n break;\n }\n\n return pcm32 / 2147483647f; // float.MaxValue;\n }\n\n private void ReleasePcmData()\n {\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n for ( var sampleCount = 0; sampleCount < _wavFileInfo._samplePerChannel; sampleCount++ )\n {\n _pcmData[sampleCount * _wavFileInfo._numberOfChannels + channelCount] = 0.0f;\n }\n }\n\n _pcmData = Array.Empty();\n }\n}\n\npublic class ByteReader\n{\n public byte[] _fileByte;\n\n public MemoryStream _fileDataView;\n\n public int _fileSize;\n\n public int _readOffset;\n\n public int Get8()\n {\n var returnValue = _fileDataView.ReadByte();\n _readOffset++;\n\n return returnValue;\n }\n\n /**\n * @brief 16ビット読み込み(リトルエンディアン)\n * @return Csm::csmUint16 読み取った16ビット値\n */\n public uint Get16LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8);\n\n return ret;\n }\n\n /// \n /// 24ビット読み込み(リトルエンディアン)\n /// \n /// 読み取った24ビット値(下位24ビットに設定)\n public uint Get24LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8) |\n (uint)(Get8() << 16);\n\n return ret;\n }\n\n /// \n /// 32ビット読み込み(リトルエンディアン)\n /// \n /// 読み取った32ビット値\n public uint Get32LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8) |\n (uint)(Get8() << 16) |\n (uint)(Get8() << 24);\n\n return ret;\n }\n\n /// \n /// シグネチャの取得と参照文字列との一致チェック\n /// \n /// 検査対象のシグネチャ文字列\n /// true 一致している, false 一致していない\n public bool GetCheckSignature(string reference)\n {\n if ( reference.Length != 4 )\n {\n return false;\n }\n\n var getSignature = new byte[4];\n var referenceString = Encoding.UTF8.GetBytes(reference);\n\n for ( var signatureOffset = 0; signatureOffset < 4; signatureOffset++ )\n {\n getSignature[signatureOffset] = (byte)Get8();\n }\n\n return getSignature[0] == referenceString[0] &&\n getSignature[1] == referenceString[1] &&\n getSignature[2] == referenceString[2] &&\n getSignature[3] == referenceString[3];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/SemanticKernelLlmEngine.cs", "using System.Diagnostics;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.SemanticKernel;\nusing Microsoft.SemanticKernel.ChatCompletion;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.Logging;\n\nusing Polly;\nusing Polly.Registry;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic class SemanticKernelChatEngine : IChatEngine\n{\n private readonly IChatCompletionService _chatCompletionService;\n\n private readonly ILogger _logger;\n\n private readonly ResiliencePipeline _resiliencePipeline;\n\n private readonly SemaphoreSlim _semaphore = new(1, 1);\n\n public SemanticKernelChatEngine(\n Kernel kernel,\n ILogger logger, ResiliencePipelineProvider resiliencePipelineProvider)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _resiliencePipeline = resiliencePipelineProvider.GetPipeline(\"semantickernel-chat\");\n _chatCompletionService = kernel.GetRequiredService(\"text\");\n\n _logger.LogInformation(\"SemanticKernelChatEngine initialized successfully\");\n }\n\n public void Dispose()\n {\n try\n {\n _logger.LogInformation(\"Disposing SemanticKernelChatEngine\");\n _semaphore.Dispose();\n GC.SuppressFinalize(this);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error occurred while disposing SemanticKernelChatEngine\");\n }\n }\n\n public async Task GetStreamingChatResponseAsync(\n IConversationContext context,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n PromptExecutionSettings? executionSettings = null,\n CancellationToken cancellationToken = default)\n {\n await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n var stopwatch = Stopwatch.StartNew();\n long chunkCount = 0;\n\n try\n {\n var history = context.GetSemanticKernelChatHistory();\n\n var rc = ResilienceContextPool.Shared.Get(cancellationToken);\n rc.Properties.Set(ResilienceKeys.SessionId, sessionId);\n rc.Properties.Set(ResilienceKeys.Logger, _logger);\n\n await _resiliencePipeline.ExecuteAsync(async (x, token) =>\n {\n firstChunk = true;\n chunkCount = 0;\n x.stopwatch.Restart();\n\n var streamingResponse = _chatCompletionService.GetStreamingChatMessageContentsAsync(\n x.history,\n x.executionSettings,\n null,\n token);\n\n await foreach ( var chunk in streamingResponse.ConfigureAwait(false) )\n {\n chunkCount++;\n var content = chunk.Content ?? string.Empty;\n\n if ( firstChunk )\n {\n var firstChunkEvent = new LlmStreamStartEvent(x.sessionId, x.turnId, DateTimeOffset.UtcNow);\n await x.outputWriter.WriteAsync(firstChunkEvent, token).ConfigureAwait(false);\n firstChunk = false;\n }\n\n var chunkEvent = new LlmChunkEvent(x.sessionId, x.turnId, DateTimeOffset.UtcNow, content);\n await x.outputWriter.WriteAsync(chunkEvent, token).ConfigureAwait(false);\n\n _logger.LogTrace(\"Received chunk {ChunkNumber}: {ChunkLength} characters for TurnId: {TurnId}\", chunkCount, content.Length, x.turnId);\n }\n\n _logger.LogInformation(\"Chat response streaming completed. Total chunks: {ChunkCount}, Total time: {ElapsedMs}ms\", chunkCount, stopwatch.ElapsedMilliseconds);\n }, (stopwatch, outputWriter, history, executionSettings, sessionId, turnId), cancellationToken).ConfigureAwait(false);\n\n ResilienceContextPool.Shared.Return(rc);\n\n stopwatch.Stop();\n\n if ( !firstChunk )\n {\n _logger.LogInformation(\n \"Chat response streaming completed successfully for TurnId: {TurnId}. Total chunks: {ChunkCount}, Total time: {ElapsedMs}ms\",\n turnId, chunkCount, stopwatch.ElapsedMilliseconds);\n }\n else\n {\n _logger.LogWarning(\"Chat response streaming finished for TurnId: {TurnId}, but no chunks were received (potentially empty response or immediate failure). Time: {ElapsedMs}ms\", turnId, stopwatch.ElapsedMilliseconds);\n }\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n stopwatch.Stop();\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n stopwatch.Stop();\n await outputWriter.WriteAsync(new ErrorOutputEvent(sessionId, turnId, DateTimeOffset.UtcNow, ex), cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n if ( !firstChunk )\n {\n var endEvent = new LlmStreamEndEvent(sessionId, turnId, DateTimeOffset.UtcNow, completedReason);\n try\n {\n using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));\n await outputWriter.WriteAsync(endEvent, cts.Token).ConfigureAwait(false);\n }\n catch (Exception finalEx)\n {\n _logger.LogError(finalEx, \"Failed to write LlmStreamEndEvent for TurnId: {TurnId}\", turnId);\n }\n }\n\n _semaphore.Release();\n }\n\n return completedReason;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/FontProvider.cs", "using System.Drawing;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.OpenGL;\n\nusing StbImageSharp;\n\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI;\n\n/// \n/// Manages caching and loading of fonts and textures.\n/// \npublic class FontProvider : IStartupTask\n{\n private const string FONTS_DIR = @\"Resources\\Fonts\";\n\n private const string IMAGES_PATH = @\"Resources\\Imgs\";\n\n private readonly Dictionary _fontCache = new();\n\n private readonly ILogger _logger;\n\n private readonly Dictionary _textureCache = new();\n\n private Texture2DManager _texture2DManager = null!;\n\n // static FontProvider()\n // {\n // FontSystemDefaults.FontLoader = new SixLaborsFontLoader();\n // }\n\n public FontProvider(ILogger logger) { _logger = logger; }\n\n public void Execute(GL gl) { _texture2DManager = new Texture2DManager(gl); }\n\n public Task> GetAvailableFontsAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n if ( !Directory.Exists(FONTS_DIR) )\n {\n _logger.LogWarning(\"Fonts directory not found: {Path}\", FONTS_DIR);\n\n return Task.FromResult>(Array.Empty());\n }\n\n var fontFiles = Directory.GetFiles(FONTS_DIR, \"*.ttf\");\n var fontNames = new List(fontFiles.Length);\n foreach ( var file in fontFiles )\n {\n var voiceId = Path.GetFileName(file);\n fontNames.Add(voiceId);\n }\n\n _logger.LogInformation(\"Found {Count} available fonts\", fontNames.Count);\n\n return Task.FromResult>(fontNames);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available fonts\");\n\n throw;\n }\n }\n\n public FontSystem GetFontSystem(string fontName)\n {\n if ( !_fontCache.TryGetValue(fontName, out var fontSystem) )\n {\n fontSystem = new FontSystem();\n var fontData = File.ReadAllBytes(Path.Combine(FONTS_DIR, fontName));\n fontSystem.AddFont(fontData);\n _fontCache[fontName] = fontSystem;\n }\n\n return fontSystem;\n }\n\n public Texture GetTexture(string imageName)\n {\n if ( !_textureCache.TryGetValue(imageName, out var texture) )\n {\n using var stream = File.OpenRead(Path.Combine(IMAGES_PATH, imageName));\n var imageResult = ImageResult.FromStream(stream, ColorComponents.RedGreenBlueAlpha);\n\n // Premultiply alpha\n unsafe\n {\n fixed (byte* b = imageResult.Data)\n {\n var ptr = b;\n for ( var i = 0; i < imageResult.Data.Length; i += 4, ptr += 4 )\n {\n var falpha = ptr[3] / 255.0f;\n ptr[0] = (byte)(ptr[0] * falpha);\n ptr[1] = (byte)(ptr[1] * falpha);\n ptr[2] = (byte)(ptr[2] * falpha);\n }\n }\n }\n\n texture = (Texture)_texture2DManager.CreateTexture(imageResult.Width, imageResult.Height);\n _texture2DManager.SetTextureData(texture, new Rectangle(0, 0, (int)texture.Width, (int)texture.Height), imageResult.Data);\n _textureCache[imageName] = texture;\n }\n\n return texture;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioConverter.cs", "using System.Buffers.Binary;\nusing System.Runtime.CompilerServices;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Provides functionality for converting audio between different formats.\n/// \npublic static class AudioConverter\n{\n /// \n /// Calculates the required size for a buffer to hold the converted audio.\n /// \n /// The source audio buffer.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The size in bytes needed for the target buffer.\n public static int CalculateTargetBufferSize(\n ReadOnlyMemory sourceBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var framesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // If resampling is needed, adjust the frame count\n if ( sourceFormat.SampleRate != targetFormat.SampleRate )\n {\n framesCount = CalculateResampledFrameCount(framesCount, sourceFormat.SampleRate, targetFormat.SampleRate);\n }\n\n // Calculate the expected size of the target buffer\n return framesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Calculates the number of frames after resampling.\n /// \n /// Number of frames in the source buffer.\n /// Sample rate of the source audio.\n /// Target sample rate.\n /// The number of frames after resampling.\n public static int CalculateResampledFrameCount(\n int sourceFrameCount,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n return (int)Math.Ceiling(sourceFrameCount * ((double)targetSampleRate / sourceSampleRate));\n }\n\n /// \n /// Converts audio data between different formats.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the converted data to.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The number of bytes written to the target buffer.\n /// Thrown if the target buffer is too small.\n public static int Convert(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var sourceFramesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // Check if resampling is needed\n var needsResampling = sourceFormat.SampleRate != targetFormat.SampleRate;\n\n // Calculate the expected number of frames in the target buffer\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceFormat.SampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate the expected size of the target buffer\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Fast path for same format conversion with no resampling\n if ( !needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n sourceBuffer.CopyTo(targetBuffer);\n\n return sourceBuffer.Length;\n }\n\n // If only resampling is needed (same format otherwise)\n if ( needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n return ResampleDirect(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // For mono-to-stereo int16 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 32 && targetFormat.BitsPerSample == 16 )\n {\n ConvertMonoFloat32ToStereoInt16Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For stereo-to-mono conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 2 && targetFormat.Channels == 1 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertStereoInt16ToMonoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For mono-int16 to stereo-float32 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertMonoInt16ToStereoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // General case: convert through intermediate float format\n return ConvertGeneral(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount,\n needsResampling);\n }\n\n /// \n /// Specialized fast path to convert 48kHz stereo float32 audio to 16kHz mono int16 audio.\n /// This optimized method combines resampling, channel conversion, and bit depth conversion in one pass.\n /// \n /// The 48kHz stereo float32 audio buffer.\n /// The target buffer to receive the 16kHz mono int16 data.\n /// The number of bytes written to the target buffer.\n public static int ConvertStereoFloat32_48kTo_MonoInt16_16k(\n ReadOnlyMemory stereoFloat32Buffer,\n Memory targetBuffer)\n {\n var sourceFormat = new AudioFormat(2, 32, 48000);\n var targetFormat = new AudioFormat(1, 16, 16000);\n\n // Calculate number of source and target frames\n var sourceFramesCount = stereoFloat32Buffer.Length / sourceFormat.BytesPerFrame;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, 48000, 16000);\n\n // Calculate expected target size and verify buffer is large enough\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Process the conversion directly\n ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n stereoFloat32Buffer.Span,\n targetBuffer.Span,\n sourceFramesCount,\n targetFramesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Direct conversion implementation for 48kHz stereo float32 to 16kHz mono int16.\n /// Combines downsampling (48kHz to 16kHz - 3:1 ratio), stereo to mono mixing, and float32 to int16 conversion.\n /// \n private static void ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n ReadOnlySpan source,\n Span target,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // The resampling ratio is exactly 3:1 (48000/16000)\n const int resampleRatio = 3;\n\n // For optimal quality, we'll use a simple low-pass filter when downsampling\n // by averaging 3 consecutive frames before picking every 3rd one\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source frame index (center of 3-frame window)\n var sourceFrameBase = targetFrame * resampleRatio;\n\n // Initialize accumulator for filtered sample\n var monoSampleAccumulator = 0f;\n var sampleCount = 0;\n\n // Apply a simple averaging filter over a window of frames\n for ( var offset = -1; offset <= 1; offset++ )\n {\n var sourceFrameIndex = sourceFrameBase + offset;\n\n // Skip samples outside buffer boundary\n if ( sourceFrameIndex < 0 || sourceFrameIndex >= sourceFramesCount )\n {\n continue;\n }\n\n // Read left and right float32 samples and average them to mono\n var sourceByteIndex = sourceFrameIndex * 8; // 8 bytes per stereo float32 frame\n var leftSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex, 4));\n var rightSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex + 4, 4));\n\n // Average stereo to mono\n var monoSample = (leftSample + rightSample) * 0.5f;\n\n // Accumulate filtered sample\n monoSampleAccumulator += monoSample;\n sampleCount++;\n }\n\n // Average samples if we have any\n var filteredSample = sampleCount > 0 ? monoSampleAccumulator / sampleCount : 0f;\n\n // Convert float32 to int16 (with scaling and clamping)\n var int16Sample = ClampToInt16(filteredSample * 32767f);\n\n // Write to target buffer\n var targetByteIndex = targetFrame * 2; // 2 bytes per mono int16 frame\n BinaryPrimitives.WriteInt16LittleEndian(target.Slice(targetByteIndex, 2), int16Sample);\n }\n }\n\n /// \n /// Resamples audio using a higher quality filter.\n /// Uses a sinc filter for better frequency response.\n /// \n private static void ResampleWithFilter(float[] source, float[] target, uint sourceRate, uint targetRate)\n {\n // For 48kHz to 16kHz, we have a 3:1 ratio\n var ratio = (double)sourceRate / targetRate;\n\n // Use a simple windowed-sinc filter with 8 taps for anti-aliasing\n var filterSize = 8;\n\n for ( var targetIndex = 0; targetIndex < target.Length; targetIndex++ )\n {\n // Calculate the corresponding position in the source\n var sourcePos = targetIndex * ratio;\n var sourceCenterIndex = (int)sourcePos;\n\n // Apply the filter\n var sum = 0f;\n var totalWeight = 0f;\n\n for ( var tap = -filterSize / 2; tap < filterSize / 2; tap++ )\n {\n var sourceIndex = sourceCenterIndex + tap;\n\n // Skip samples outside buffer boundary\n if ( sourceIndex < 0 || sourceIndex >= source.Length )\n {\n continue;\n }\n\n // Calculate the sinc weight\n var x = sourcePos - sourceIndex;\n var weight = x == 0 ? 1.0f : (float)(Math.Sin(Math.PI * x) / (Math.PI * x));\n\n // Apply a Hann window to reduce ringing\n weight *= 0.5f * (1 + (float)Math.Cos(2 * Math.PI * (tap + filterSize / 2) / filterSize));\n\n sum += source[sourceIndex] * weight;\n totalWeight += weight;\n }\n\n // Normalize the output\n target[targetIndex] = totalWeight > 0 ? sum / totalWeight : 0f;\n }\n }\n\n /// \n /// Resamples audio data to a different sample rate.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the resampled data to.\n /// The format of the source audio.\n /// The target sample rate.\n /// The number of bytes written to the target buffer.\n public static int Resample(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n uint targetSampleRate)\n {\n // Create target format with the new sample rate but same other parameters\n var targetFormat = new AudioFormat(\n sourceFormat.Channels,\n sourceFormat.BitsPerSample,\n targetSampleRate);\n\n return Convert(sourceBuffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Resamples floating-point audio samples directly.\n /// \n /// The source float samples.\n /// The target buffer to write the resampled samples to.\n /// Number of channels in the audio.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ResampleFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort channels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n // Fast path for same sample rate\n if ( sourceSampleRate == targetSampleRate )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceSamples.Length / channels;\n }\n\n var sourceFramesCount = sourceSamples.Length / channels;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate);\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * channels )\n {\n throw new ArgumentException(\"Target buffer is too small for the resampled audio.\");\n }\n\n // Perform the resampling\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n channels,\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Converts float samples to a different format (channels, sample rate) and outputs as byte array.\n /// \n /// The source float samples.\n /// The target buffer to write the converted data to.\n /// Number of channels in the source.\n /// Source sample rate.\n /// The desired output format.\n /// The number of bytes written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetBuffer,\n ushort sourceChannels,\n uint sourceSampleRate,\n AudioFormat targetFormat)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetFormat.SampleRate;\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate expected target buffer size\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Handle resampling if needed\n ReadOnlyMemory resampledSamples;\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceChannels];\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n }\n else\n {\n resampledSamples = sourceSamples;\n }\n\n // Handle channel conversion if needed\n ReadOnlyMemory convertedSamples;\n if ( sourceChannels != targetFormat.Channels )\n {\n var convertedBuffer = new float[targetFramesCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceChannels,\n targetFormat.Channels,\n targetFramesCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return expectedTargetSize;\n }\n\n /// \n /// Converts audio format with direct access to float samples.\n /// \n /// The source float samples.\n /// The target buffer to write the converted samples to.\n /// Number of channels in the source.\n /// Number of channels for the output.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort sourceChannels,\n ushort targetChannels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetSampleRate;\n var needsChannelConversion = sourceChannels != targetChannels;\n\n // If no conversion needed, just copy\n if ( !needsResampling && !needsChannelConversion )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceFramesCount;\n }\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate)\n : sourceFramesCount;\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * targetChannels )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Optimize the common path where only channel conversion or only resampling is needed\n if ( needsResampling && !needsChannelConversion )\n {\n // Only resample\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels, // same as targetChannels in this case\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n if ( !needsResampling && needsChannelConversion )\n {\n // Only convert channels\n ConvertChannels(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n sourceFramesCount);\n\n return sourceFramesCount;\n }\n\n // If we need both resampling and channel conversion\n // First resample, then convert channels\n var resampledBuffer = needsResampling ? new float[targetFramesCount * sourceChannels] : null;\n\n if ( needsResampling )\n {\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // Then convert channels\n ConvertChannels(\n needsResampling ? resampledBuffer.AsSpan() : sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Direct resampling of audio data without format conversion.\n /// \n private static int ResampleDirect(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Convert to float for processing\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Resample the float samples\n var resampledBuffer = new float[targetFramesCount * targetFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n // Serialize back to the target format\n SampleSerializer.Serialize(resampledBuffer, targetBuffer, targetFormat.BitsPerSample);\n\n return targetFramesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Resamples floating-point audio samples.\n /// \n private static void ResampleFloatBuffer(\n ReadOnlySpan sourceBuffer,\n Span targetBuffer,\n ushort channels,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Calculate the step size for linear interpolation\n var step = (double)(sourceFramesCount - 1) / (targetFramesCount - 1);\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source position (as a floating point value)\n var sourcePos = targetFrame * step;\n\n // Get indices of the two source frames to interpolate between\n var sourceFrameLow = (int)sourcePos;\n var sourceFrameHigh = Math.Min(sourceFrameLow + 1, sourceFramesCount - 1);\n\n // Calculate interpolation factor\n var fraction = (float)(sourcePos - sourceFrameLow);\n\n // Interpolate each channel\n for ( var channel = 0; channel < channels; channel++ )\n {\n var sourceLowIndex = sourceFrameLow * channels + channel;\n var sourceHighIndex = sourceFrameHigh * channels + channel;\n var targetIndex = targetFrame * channels + channel;\n\n // Linear interpolation\n targetBuffer[targetIndex] = Lerp(\n sourceBuffer[sourceLowIndex],\n sourceBuffer[sourceHighIndex],\n fraction);\n }\n }\n }\n\n /// \n /// Linear interpolation between two values.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static float Lerp(float a, float b, float t) { return a + (b - a) * t; }\n\n /// \n /// Converts mono float32 audio to stereo int16 PCM format.\n /// \n /// The mono float32 audio buffer.\n /// The target buffer to receive the stereo int16 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoFloat32ToStereoInt16(\n ReadOnlyMemory monoFloat32Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(32, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(16, sampleRate);\n\n return Convert(monoFloat32Buffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Converts mono int16 audio to stereo float32 PCM format.\n /// \n /// The mono int16 audio buffer.\n /// The target buffer to receive the stereo float32 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoInt16ToStereoFloat32(\n ReadOnlyMemory monoInt16Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(16, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(32, sampleRate);\n\n // Use fast path for this specific conversion\n var framesCount = monoInt16Buffer.Length / sourceFormat.BytesPerFrame;\n var expectedTargetSize = framesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n ConvertMonoInt16ToStereoFloat32Direct(monoInt16Buffer, targetBuffer, framesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Optimized direct conversion from mono float32 to stereo int16.\n /// \n private static void ConvertMonoFloat32ToStereoInt16Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 4 bytes per float32\n var targetIndex = frame * 4; // 2 bytes per int16 * 2 channels\n\n // Read float32 value\n var floatValue = BinaryPrimitives.ReadSingleLittleEndian(sourceSpan.Slice(sourceIndex, 4));\n\n // Convert to int16 (with clamping)\n var int16Value = ClampToInt16(floatValue * 32767f);\n\n // Write the same value to both left and right channels\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex, 2), int16Value);\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex + 2, 2), int16Value);\n }\n }\n\n /// \n /// Optimized direct conversion from stereo int16 to mono float32.\n /// \n private static void ConvertStereoInt16ToMonoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 2 bytes per int16 * 2 channels\n var targetIndex = frame * 4; // 4 bytes per float32\n\n // Read int16 values for left and right channels\n var leftValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n var rightValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex + 2, 2));\n\n // Convert to float32 and average the channels\n var floatValue = (leftValue + rightValue) * 0.5f / 32768f;\n\n // Write to target buffer\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n }\n }\n\n /// \n /// Optimized direct conversion from mono int16 to stereo float32.\n /// \n private static void ConvertMonoInt16ToStereoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2; // 2 bytes per int16\n var targetIndex = frame * 8; // 4 bytes per float32 * 2 channels\n\n // Read int16 value\n var int16Value = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n\n // Convert to float32\n var floatValue = int16Value / 32768f;\n\n // Write the same float value to both left and right channels\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex + 4, 4), floatValue);\n }\n }\n\n /// \n /// General case conversion using intermediate float format.\n /// \n private static int ConvertGeneral(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount,\n bool needsResampling)\n {\n // Deserialize to float samples - this will give us interleaved float samples\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Perform resampling if needed\n Memory resampledSamples;\n int actualFrameCount;\n\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n actualFrameCount = targetFramesCount;\n }\n else\n {\n resampledSamples = floatSamples;\n actualFrameCount = sourceFramesCount;\n }\n\n // Convert channel configuration if needed\n Memory convertedSamples;\n\n if ( sourceFormat.Channels != targetFormat.Channels )\n {\n var convertedBuffer = new float[actualFrameCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceFormat.Channels,\n targetFormat.Channels,\n actualFrameCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n // No channel conversion needed\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return actualFrameCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Converts between different channel configurations.\n /// \n private static void ConvertChannels(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n // If source and target have the same number of channels, just copy\n if ( sourceChannels == targetChannels )\n {\n source.CopyTo(target);\n\n return;\n }\n\n // Handle specific conversions with optimized implementations\n if ( sourceChannels == 1 && targetChannels == 2 )\n {\n // Mono to stereo conversion\n ConvertMonoToStereo(source, target, framesCount);\n }\n else if ( sourceChannels == 2 && targetChannels == 1 )\n {\n // Stereo to mono conversion\n ConvertStereoToMono(source, target, framesCount);\n }\n else\n {\n // More general conversion implementation\n ConvertChannelsGeneral(source, target, sourceChannels, targetChannels, framesCount);\n }\n }\n\n /// \n /// Converts mono audio to stereo by duplicating each sample.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertMonoToStereo(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceSample = source[frame];\n var targetIndex = frame * 2;\n\n target[targetIndex] = sourceSample; // Left channel\n target[targetIndex + 1] = sourceSample; // Right channel\n }\n }\n\n /// \n /// Converts stereo audio to mono by averaging the channels.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertStereoToMono(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2;\n var leftSample = source[sourceIndex];\n var rightSample = source[sourceIndex + 1];\n\n target[frame] = (leftSample + rightSample) * 0.5f; // Average the channels\n }\n }\n\n /// \n /// General method for converting between different channel configurations.\n /// \n private static void ConvertChannelsGeneral(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n ConvertChannelsChunk(source, target, sourceChannels, targetChannels, 0, framesCount);\n }\n\n /// \n /// Converts a chunk of frames between different channel configurations.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertChannelsChunk(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int startFrame,\n int endFrame)\n {\n for ( var frame = startFrame; frame < endFrame; frame++ )\n {\n var sourceFrameOffset = frame * sourceChannels;\n var targetFrameOffset = frame * targetChannels;\n\n // Find the minimum of source and target channels\n var minChannels = Math.Min(sourceChannels, targetChannels);\n\n // Copy the available channels\n for ( var channel = 0; channel < minChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + channel];\n }\n\n // If target has more channels than source, duplicate the last channel\n for ( var channel = minChannels; channel < targetChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + (minChannels - 1)];\n }\n }\n }\n\n /// \n /// Clamps a float value to the range of a 16-bit integer.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static short ClampToInt16(float value)\n {\n if ( value > 32767f )\n {\n return 32767;\n }\n\n if ( value < -32768f )\n {\n return -32768;\n }\n\n return (short)value;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Spout/SpoutManager.cs", "using PersonaEngine.Lib.Configuration;\n\nusing Silk.NET.OpenGL;\n\nusing Spout.Interop;\n\nnamespace PersonaEngine.Lib.UI.Spout;\n\n/// \n/// Provides real-time frame sharing via Spout with custom framebuffer support.\n/// \npublic class SpoutManager : IDisposable\n{\n private readonly SpoutConfiguration _config;\n\n private readonly GL _gl;\n\n private readonly SpoutSender _spoutSender;\n\n private uint _colorAttachment;\n\n private uint _customFbo;\n\n private bool _customFboInitialized = false;\n\n private uint _depthAttachment;\n\n public SpoutManager(GL gl, SpoutConfiguration config)\n {\n _gl = gl;\n _config = config;\n _spoutSender = new SpoutSender();\n\n InitializeCustomFramebuffer();\n\n if ( !_spoutSender.CreateSender(config.OutputName, (uint)_config.Width, (uint)_config.Height, 0) )\n {\n _spoutSender.Dispose();\n Console.WriteLine($\"Failed to create Spout Sender '{config.OutputName}'.\");\n }\n }\n\n public void Dispose()\n {\n if ( _customFboInitialized )\n {\n _gl.DeleteTexture(_colorAttachment);\n _gl.DeleteTexture(_depthAttachment);\n _gl.DeleteFramebuffer(_customFbo);\n }\n\n _spoutSender?.Dispose();\n }\n\n private unsafe void InitializeCustomFramebuffer()\n {\n _customFbo = _gl.GenFramebuffer();\n _gl.BindFramebuffer(GLEnum.Framebuffer, _customFbo);\n\n _colorAttachment = _gl.GenTexture();\n _gl.BindTexture(GLEnum.Texture2D, _colorAttachment);\n _gl.TexImage2D(GLEnum.Texture2D, 0, (int)GLEnum.Rgba8,\n (uint)_config.Width, (uint)_config.Height, 0, GLEnum.Rgba, GLEnum.UnsignedByte, null);\n\n _gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureMinFilter, (int)GLEnum.Linear);\n _gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureMagFilter, (int)GLEnum.Linear);\n _gl.FramebufferTexture2D(GLEnum.Framebuffer, GLEnum.ColorAttachment0,\n GLEnum.Texture2D, _colorAttachment, 0);\n\n _depthAttachment = _gl.GenTexture();\n _gl.BindTexture(GLEnum.Texture2D, _depthAttachment);\n _gl.TexImage2D(GLEnum.Texture2D, 0, (int)GLEnum.DepthComponent,\n (uint)_config.Width, (uint)_config.Height, 0, GLEnum.DepthComponent, GLEnum.Float, null);\n\n _gl.FramebufferTexture2D(GLEnum.Framebuffer, GLEnum.DepthAttachment,\n GLEnum.Texture2D, _depthAttachment, 0);\n\n if ( _gl.CheckFramebufferStatus(GLEnum.Framebuffer) != GLEnum.FramebufferComplete )\n {\n Console.WriteLine(\"Custom framebuffer is not complete!\");\n\n return;\n }\n\n _gl.BindFramebuffer(GLEnum.Framebuffer, 0);\n\n _customFboInitialized = true;\n }\n\n /// \n /// Begins rendering to the custom framebuffer\n /// \n public void BeginFrame()\n {\n if ( _customFboInitialized )\n {\n _gl.BindFramebuffer(GLEnum.Framebuffer, _customFbo);\n\n _gl.Viewport(0, 0, (uint)_config.Width, (uint)_config.Height);\n\n var blendEnabled = _gl.IsEnabled(EnableCap.Blend);\n\n // Enable blending for transparency\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n\n // Clear with transparency (RGBA: 0,0,0,0)\n _gl.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n _gl.Clear((uint)(GLEnum.ColorBufferBit | GLEnum.DepthBufferBit));\n\n if ( !blendEnabled )\n {\n _gl.Disable(EnableCap.Blend);\n }\n }\n }\n\n /// \n /// Sends the current frame to Spout and returns to the default framebuffer\n /// \n /// Whether to copy the framebuffer to the screen\n /// Window width if blitting to screen\n /// Window height if blitting to screen\n public void SendFrame(bool blitToScreen = true, int windowWidth = 0, int windowHeight = 0)\n {\n if ( _customFboInitialized )\n {\n _gl.GetInteger(GetPName.UnpackAlignment, out var previousUnpackAlignment);\n _gl.PixelStore(PixelStoreParameter.UnpackAlignment, 1);\n\n _spoutSender.SendFbo(_customFbo, (uint)_config.Width, (uint)_config.Height, true);\n\n _gl.PixelStore(PixelStoreParameter.UnpackAlignment, previousUnpackAlignment);\n\n if ( blitToScreen && windowWidth > 0 && windowHeight > 0 )\n {\n _gl.BindFramebuffer(GLEnum.ReadFramebuffer, _customFbo);\n _gl.BindFramebuffer(GLEnum.DrawFramebuffer, 0); // Default framebuffer\n\n var blendEnabled = _gl.IsEnabled(EnableCap.Blend);\n if ( !blendEnabled )\n {\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n }\n\n _gl.BlitFramebuffer(\n 0, 0, _config.Width, _config.Height,\n 0, 0, windowWidth, windowHeight,\n (uint)GLEnum.ColorBufferBit,\n GLEnum.Linear);\n\n if ( !blendEnabled )\n {\n _gl.Disable(EnableCap.Blend);\n }\n }\n\n _gl.BindFramebuffer(GLEnum.Framebuffer, 0);\n }\n else\n {\n _gl.GetInteger(GetPName.ReadFramebufferBinding, out var fboId);\n _spoutSender.SendFbo((uint)fboId, (uint)_config.Width, (uint)_config.Height, true);\n }\n }\n\n /// \n /// Updates the custom framebuffer dimensions if needed\n /// \n public void ResizeFramebuffer(int width, int height)\n {\n // if ( _config.Width == width && _config.Height == height )\n // {\n // return;\n // }\n\n // _config.Width = width;\n // _config.Height = height;\n\n // if ( _customFboInitialized )\n // {\n // _gl.DeleteTexture(_colorAttachment);\n // _gl.DeleteTexture(_depthAttachment);\n // _gl.DeleteFramebuffer(_customFbo);\n // _customFboInitialized = false;\n // }\n //\n // InitializeCustomFramebuffer();\n //\n // _spoutSender.UpdateSender(_config.OutputName, (uint)width, (uint)height);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/SentenceSegmenter.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// High-performance sentence segmentation using both rule-based and ML approaches with\n/// advanced handling of edge cases and text structures\n/// \npublic partial class SentenceSegmenter(IMlSentenceDetector mlDetector, ILogger logger) : ISentenceSegmenter\n{\n private const int MinimumSentences = 2;\n\n private static readonly Regex SpecialTokenPattern = new(@\"\\[[A-Z]+:[^\\]]+\\]\", RegexOptions.Compiled);\n\n private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n private readonly IMlSentenceDetector _mlDetector = mlDetector ?? throw new ArgumentNullException(nameof(mlDetector));\n\n /// \n /// Segments text into sentences with optimized handling and pre-processing for boundary detection\n /// \n public IReadOnlyList Segment(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Array.Empty();\n }\n\n try\n {\n // First attempt with original text\n var sentences = _mlDetector.Detect(text);\n\n // If we have fewer than minimum required sentences, try pre-processing\n if ( sentences.Count < MinimumSentences )\n {\n _logger.LogTrace(\"Initial segmentation yielded only {count} sentence(s), attempting pre-processing\", sentences.Count);\n\n // Apply pre-processing to create potential sentence boundaries\n var preprocessedText = AddPotentialSentenceBoundaries(text);\n\n // Re-detect sentences with the pre-processed text\n sentences = _mlDetector.Detect(preprocessedText);\n\n _logger.LogTrace(\"After pre-processing, segmentation yielded {count} sentence(s)\", sentences.Count);\n }\n\n return sentences;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error in sentence segmentation.\");\n\n return Array.Empty();\n }\n }\n\n /// \n /// Adds potential sentence boundaries by replacing certain punctuation with periods\n /// to help generate at least 2 sentences when possible\n /// \n private string AddPotentialSentenceBoundaries(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return text;\n }\n\n try\n {\n if ( !SpecialTokenPattern.IsMatch(text) )\n {\n // No special tokens - apply normal processing\n return ApplyBasicPreprocessing(text);\n }\n\n var result = new StringBuilder(text.Length + 20);\n var currentPosition = 0;\n\n foreach ( Match match in SpecialTokenPattern.Matches(text) )\n {\n // Process the text between the last token and this one\n if ( match.Index > currentPosition )\n {\n var segment = text.Substring(currentPosition, match.Index - currentPosition);\n result.Append(ApplyBasicPreprocessing(segment));\n }\n\n // Append the token unchanged\n result.Append(match.Value);\n currentPosition = match.Index + match.Length;\n }\n\n if ( currentPosition < text.Length )\n {\n var segment = text[currentPosition..];\n result.Append(ApplyBasicPreprocessing(segment));\n }\n\n return result.ToString();\n }\n catch (Exception ex)\n {\n _logger.LogWarning(ex, \"Error during preprocessing for sentence boundaries. Using original text.\");\n\n return text;\n }\n }\n\n /// \n /// Applies basic preprocessing rules to a text segment without special tokens\n /// \n private string ApplyBasicPreprocessing(string text)\n {\n // Replace semicolons with periods\n text = text.Replace(\";\", \".\");\n\n // Replace colons with periods\n text = text.Replace(\":\", \".\");\n\n // Replace dashes with periods (when surrounded by spaces)\n text = text.Replace(\" - \", \". \");\n text = text.Replace(\" – \", \". \");\n text = text.Replace(\" — \", \". \");\n\n // Ensure proper spacing after periods for the ML detector\n text = TextAfterSpaceRegex().Replace(text, \". $1\");\n\n return text;\n }\n\n [GeneratedRegex(@\"\\.([A-Za-z0-9])\")] private static partial Regex TextAfterSpaceRegex();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/RouletteWheel.Transform.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic partial class RouletteWheel\n{\n /// \n /// Defines how the wheel position is tracked and updated during window resizing.\n /// \n public enum PositionMode\n {\n /// \n /// Position is fixed in absolute pixels and won't change during resizing.\n /// \n Absolute,\n\n /// \n /// Position is based on viewport percentages and will scale with resizing.\n /// \n Percentage,\n\n /// \n /// Position is based on viewport anchors and will adapt during resizing.\n /// \n Anchored\n }\n\n /// \n /// Represents anchor points within the viewport for positioning the wheel.\n /// \n public enum ViewportAnchor\n {\n Center,\n\n TopLeft,\n\n TopCenter,\n\n TopRight,\n\n MiddleLeft,\n\n MiddleRight,\n\n BottomLeft,\n\n BottomCenter,\n\n BottomRight\n }\n\n private Vector2 _anchorOffset = Vector2.Zero;\n\n private ViewportAnchor _currentAnchor = ViewportAnchor.Center;\n\n private PositionMode _positionMode = PositionMode.Absolute;\n\n private Vector2 _positionPercentage = new(0.5f, 0.5f);\n\n /// \n /// Gets the current radius of the wheel in pixels.\n /// \n public float Radius => Diameter / 2;\n\n /// \n /// Gets the current diameter of the wheel in pixels.\n /// \n public float Diameter => Math.Min(_viewportWidth, _viewportHeight) * _wheelSize * OUTER_RADIUS_FACTOR;\n\n /// \n /// Gets or sets the rotation of the wheel in radians.\n /// \n public float Rotation { get; private set; } = 0f;\n\n /// \n /// Gets or sets the rotation of the wheel in degrees.\n /// \n public float RotationDegrees => Rotation * 180 / MathF.PI;\n\n public void Resize()\n {\n _viewportWidth = _config.CurrentValue.Width;\n _viewportHeight = _config.CurrentValue.Height;\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n\n switch ( _positionMode )\n {\n case PositionMode.Anchored:\n UpdatePositionFromAnchor();\n\n break;\n case PositionMode.Percentage:\n UpdatePositionFromPercentage();\n\n break;\n case PositionMode.Absolute:\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n /// \n /// Rotates the wheel by the specified angle in radians.\n /// \n public void RotateBy(float angleRadians) { Rotation += angleRadians; }\n\n /// \n /// Rotates the wheel by the specified angle in radians.\n /// \n public void RotateByDegrees(float angleDegrees) { Rotation += angleDegrees * MathF.PI / 180; }\n\n /// \n /// Sets the diameter of the wheel in pixels.\n /// \n public void SetDiameter(float diameter)\n {\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n _wheelSize = Math.Clamp(diameter / minDimension, 0.1f, 1.0f);\n }\n\n /// \n /// Sets the radius of the wheel in pixels.\n /// \n public void SetRadius(float radius) { SetDiameter(radius * 2); }\n\n /// \n /// Sets the wheel size as a percentage of the viewport (0.0 to 1.0).\n /// \n /// Value between 0.0 and 1.0\n public void SetSizePercentage(float percentage) { _wheelSize = Math.Clamp(percentage, 0.1f, 1.0f); }\n\n /// \n /// Scales the wheel size by the specified factor relative to its current size.\n /// \n public void Scale(float factor) { _wheelSize = Math.Clamp(_wheelSize * factor, 0.1f, 1.0f); }\n\n /// \n /// Translates the wheel by the specified amount.\n /// \n public void Translate(float deltaX, float deltaY)\n {\n _positionMode = PositionMode.Absolute;\n _position = new Vector2(_position.X + deltaX, _position.Y + deltaY);\n }\n\n /// \n /// Translates the wheel by the specified vector.\n /// \n public void Translate(Vector2 delta)\n {\n _positionMode = PositionMode.Absolute;\n _position += delta;\n }\n\n /// \n /// Sets the position using viewport percentages (0.0 to 1.0 for each axis)\n /// \n public void PositionByPercentage(float xPercent, float yPercent)\n {\n _positionMode = PositionMode.Percentage;\n _positionPercentage = new Vector2(\n Math.Clamp(xPercent, 0, 1),\n Math.Clamp(yPercent, 0, 1)\n );\n\n UpdatePositionFromPercentage();\n }\n\n /// \n /// Updates position based on viewport percentages\n /// \n private void UpdatePositionFromPercentage()\n {\n _position = new Vector2(\n _viewportWidth * _positionPercentage.X,\n _viewportHeight * _positionPercentage.Y\n );\n }\n\n /// \n /// Sets the position in absolute pixels. This will not adjust with window resizing.\n /// \n public void SetAbsolutePosition(float x, float y)\n {\n _positionMode = PositionMode.Absolute;\n _position = new Vector2(x, y);\n }\n\n /// \n /// Positions the wheel at the specified viewport anchor with an optional offset.\n /// \n public void PositionAt(ViewportAnchor anchor, Vector2 offset = default)\n {\n _positionMode = PositionMode.Anchored;\n _currentAnchor = anchor;\n _anchorOffset = offset;\n\n UpdatePositionFromAnchor();\n }\n\n /// \n /// Updates position based on the current anchor and offset\n /// \n private void UpdatePositionFromAnchor()\n {\n float x = 0,\n y = 0;\n\n switch ( _currentAnchor )\n {\n case ViewportAnchor.Center:\n x = _viewportWidth / 2.0f;\n y = _viewportHeight / 2.0f;\n\n break;\n case ViewportAnchor.TopLeft:\n x = Radius;\n y = Radius;\n\n break;\n case ViewportAnchor.TopCenter:\n x = _viewportWidth / 2.0f;\n y = Radius;\n\n break;\n case ViewportAnchor.TopRight:\n x = _viewportWidth - Radius;\n y = Radius;\n\n break;\n case ViewportAnchor.MiddleLeft:\n x = Radius;\n y = _viewportHeight / 2.0f;\n\n break;\n case ViewportAnchor.MiddleRight:\n x = _viewportWidth - Radius;\n y = _viewportHeight / 2.0f;\n\n break;\n case ViewportAnchor.BottomLeft:\n x = Radius;\n y = _viewportHeight - Radius;\n\n break;\n case ViewportAnchor.BottomCenter:\n x = _viewportWidth / 2.0f;\n y = _viewportHeight - Radius;\n\n break;\n case ViewportAnchor.BottomRight:\n x = _viewportWidth - Radius;\n y = _viewportHeight - Radius;\n\n break;\n }\n\n _position = new Vector2(x + _anchorOffset.X, y + _anchorOffset.Y);\n }\n\n /// \n /// Centers the wheel in the viewport.\n /// \n public void CenterInViewport() { _position = new Vector2(_viewportWidth / 2.0f, _viewportHeight / 2.0f); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Session/ConversationOrchestrator.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Context;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Session;\n\npublic class ConversationOrchestrator : IConversationOrchestrator\n{\n private readonly ConcurrentDictionary _activeSessions = new();\n\n private readonly IOptionsMonitor _conversationContextOptions;\n\n private readonly IOptions _conversationOptions;\n\n private readonly ILogger _logger;\n\n private readonly CancellationTokenSource _orchestratorCts = new();\n\n private readonly IConversationSessionFactory _sessionFactory;\n\n public ConversationOrchestrator(ILogger logger, IConversationSessionFactory sessionFactory, IOptions conversationOptions, IOptionsMonitor conversationContextOptions)\n {\n _logger = logger;\n _sessionFactory = sessionFactory;\n _conversationOptions = conversationOptions;\n _conversationContextOptions = conversationContextOptions;\n }\n\n public async ValueTask DisposeAsync()\n {\n await StopAllSessionsAsync();\n\n _orchestratorCts.Dispose();\n\n var remainingIds = _activeSessions.Keys.ToList();\n if ( remainingIds.Count > 0 )\n {\n _logger.LogWarning(\"Found {Count} sessions remaining after StopAll. Force cleaning up.\", remainingIds.Count);\n foreach ( var id in remainingIds )\n {\n if ( !_activeSessions.TryRemove(id, out var sessionInfo) )\n {\n continue;\n }\n\n try\n {\n await sessionInfo.Session.DisposeAsync();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during final forced disposal of session {SessionId}.\", id);\n }\n }\n }\n\n _activeSessions.Clear();\n\n GC.SuppressFinalize(this);\n }\n\n public IConversationSession GetSession(Guid sessionId)\n {\n if ( _activeSessions.TryGetValue(sessionId, out var sessionInfo) )\n {\n return sessionInfo.Session;\n }\n\n throw new KeyNotFoundException($\"Session {sessionId} not found in active sessions.\");\n }\n\n public async Task StartNewSessionAsync(CancellationToken cancellationToken = default)\n {\n var sessionId = Guid.NewGuid();\n var context = new ConversationContext([], _conversationContextOptions);\n var session = _sessionFactory.CreateSession(context, _conversationOptions.Value, sessionId);\n\n try\n {\n var runTask = session.RunAsync(_orchestratorCts.Token);\n\n if ( _activeSessions.TryAdd(session.SessionId, (null!, ValueTask.CompletedTask)) )\n {\n _logger.LogInformation(\"Session {SessionId} started.\", session.SessionId);\n\n var sessionJob = HandleSessionCompletionAsync(session, runTask);\n _activeSessions[session.SessionId] = (session, sessionJob);\n\n OnSessionsUpdated();\n\n return session.SessionId;\n }\n\n await session.StopAsync();\n await session.DisposeAsync();\n\n throw new InvalidOperationException($\"Failed to add session {session.SessionId} to the active pool.\");\n }\n catch (OperationCanceledException)\n {\n _logger.LogWarning(\"Starting session {SessionId} was cancelled before RunAsync could start.\", session.SessionId);\n await session.DisposeAsync();\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to create or start session {SessionId}.\", session.SessionId);\n await session.DisposeAsync();\n\n throw;\n }\n }\n\n public async ValueTask StopSessionAsync(Guid sessionId)\n {\n if ( _activeSessions.TryGetValue(sessionId, out var sessionInfo) )\n {\n try\n {\n await sessionInfo.Session.StopAsync();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error requesting stop for session {SessionId}.\", sessionId);\n }\n }\n else\n {\n _logger.LogWarning(\"Session {SessionId} not found in active sessions for stopping.\", sessionId);\n }\n }\n\n public IEnumerable GetActiveSessionIds() { return _activeSessions.Keys.ToList(); }\n\n public async ValueTask StopAllSessionsAsync()\n {\n if ( !_orchestratorCts.IsCancellationRequested )\n {\n await _orchestratorCts.CancelAsync();\n }\n\n var activeSessionIds = _activeSessions.Keys.ToList(); // Get a snapshot of IDs\n\n foreach ( var sessionId in activeSessionIds )\n {\n if ( !_activeSessions.TryGetValue(sessionId, out var sessionInfo) )\n {\n continue;\n }\n\n try\n {\n await StopSessionAsync(sessionId);\n await sessionInfo.RunTask;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Exception occurred while waiting for sessions to stop during StopAllSessionsAsync.\");\n }\n }\n }\n\n public event EventHandler? SessionsUpdated;\n\n private async ValueTask HandleSessionCompletionAsync(IConversationSession session, ValueTask runTask)\n {\n try\n {\n await runTask;\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"Session {SessionId} RunAsync task was cancelled.\", session.SessionId);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Session {SessionId} RunAsync task completed with an unhandled exception.\", session.SessionId);\n }\n finally\n {\n if ( _activeSessions.TryRemove(session.SessionId, out _) )\n {\n _logger.LogInformation(\"Session {SessionId} removed from active sessions.\", session.SessionId);\n OnSessionsUpdated();\n }\n else\n {\n _logger.LogWarning(\"Session {SessionId} was already removed or not found during cleanup.\", session.SessionId);\n }\n\n try\n {\n await session.DisposeAsync();\n _logger.LogDebug(\"Session {SessionId} disposed successfully.\", session.SessionId);\n }\n catch (Exception disposeEx)\n {\n _logger.LogError(disposeEx, \"Error disposing session {SessionId}.\", session.SessionId);\n }\n }\n }\n\n protected virtual void OnSessionsUpdated() { SessionsUpdated?.Invoke(this, EventArgs.Empty); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MicrophoneInputPortAudioSource.cs", "using System.Runtime.InteropServices;\nusing System.Text;\n\nusing Microsoft.Extensions.Logging;\n\nusing PortAudioSharp;\n\nusing Stream = PortAudioSharp.Stream;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents a source that captures audio from a microphone.\n/// \npublic sealed class MicrophoneInputPortAudioSource : AwaitableWaveFileSource, IMicrophone\n{\n private readonly int _bitsPerSample;\n\n private readonly int _channels;\n\n private readonly CancellationTokenSource _cts;\n\n private readonly int _deviceNumber;\n\n private readonly uint _framesPerBuffer;\n\n private readonly ILogger _logger;\n\n private readonly int _sampleRate;\n\n private Stream? _audioStream;\n\n private bool _isRecording;\n\n private Dictionary _metadata;\n\n public MicrophoneInputPortAudioSource(\n ILogger logger,\n int deviceNumber = -1,\n int sampleRate = 16000,\n int bitsPerSample = 16,\n int channels = 1,\n uint framesPerBuffer = 0,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : this(new Dictionary(), logger, deviceNumber, sampleRate, bitsPerSample,\n channels, framesPerBuffer, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy) { }\n\n private MicrophoneInputPortAudioSource(\n Dictionary metadata,\n ILogger logger,\n int deviceNumber = -1,\n int sampleRate = 16000,\n int bitsPerSample = 16,\n int channels = 1,\n uint framesPerBuffer = 0,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : base(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy)\n {\n PortAudio.Initialize();\n\n _logger = logger;\n _deviceNumber = deviceNumber == -1 ? PortAudio.DefaultInputDevice : deviceNumber;\n _sampleRate = sampleRate;\n _bitsPerSample = bitsPerSample;\n _channels = channels;\n _framesPerBuffer = framesPerBuffer;\n _cts = new CancellationTokenSource();\n _metadata = metadata;\n\n if ( _deviceNumber == PortAudio.NoDevice )\n {\n var sb = new StringBuilder();\n\n for ( var i = 0; i != PortAudio.DeviceCount; ++i )\n {\n var deviceInfo = PortAudio.GetDeviceInfo(i);\n\n sb.AppendLine($\"[*] Device {i}\");\n sb.AppendLine($\" Name: {deviceInfo.name}\");\n sb.AppendLine($\" Max input channels: {deviceInfo.maxInputChannels}\");\n sb.AppendLine($\" Default sample rate: {deviceInfo.defaultSampleRate}\");\n }\n\n logger.LogWarning(\"Devices available: {Devices}\", sb);\n\n throw new InvalidOperationException(\"No default input device available\");\n }\n\n Initialize(new AudioSourceHeader { BitsPerSample = (ushort)bitsPerSample, Channels = (ushort)channels, SampleRate = (uint)sampleRate });\n\n try\n {\n InitializeAudioStream();\n }\n catch\n {\n PortAudio.Terminate();\n\n throw;\n }\n }\n\n public void StartRecording()\n {\n if ( _isRecording )\n {\n return;\n }\n\n _isRecording = true;\n _audioStream?.Start();\n }\n\n public void StopRecording()\n {\n if ( !_isRecording )\n {\n return;\n }\n\n _isRecording = false;\n _audioStream?.Stop();\n Flush();\n }\n\n public IEnumerable GetAvailableDevices()\n {\n throw new NotImplementedException();\n }\n\n private void InitializeAudioStream()\n {\n var deviceInfo = PortAudio.GetDeviceInfo(_deviceNumber);\n _logger.LogInformation(\"Using input device: {DeviceName}\", deviceInfo.name);\n\n var inputParams = new StreamParameters {\n device = _deviceNumber,\n channelCount = _channels,\n sampleFormat = SampleFormat.Float32,\n suggestedLatency = deviceInfo.defaultLowInputLatency,\n hostApiSpecificStreamInfo = IntPtr.Zero\n };\n\n _audioStream = new Stream(\n inputParams,\n null,\n _sampleRate,\n _framesPerBuffer,\n StreamFlags.ClipOff,\n ProcessAudioCallback,\n IntPtr.Zero);\n }\n\n private StreamCallbackResult ProcessAudioCallback(\n IntPtr input,\n IntPtr output,\n uint frameCount,\n ref StreamCallbackTimeInfo timeInfo,\n StreamCallbackFlags statusFlags,\n IntPtr userData)\n {\n if ( _cts.Token.IsCancellationRequested )\n {\n return StreamCallbackResult.Complete;\n }\n\n try\n {\n var samples = new float[frameCount];\n Marshal.Copy(input, samples, 0, (int)frameCount);\n\n var byteArray = SampleSerializer.Serialize(samples, Header.BitsPerSample);\n\n WriteData(byteArray);\n\n return StreamCallbackResult.Continue;\n }\n catch\n {\n return StreamCallbackResult.Abort;\n }\n }\n\n protected override void Dispose(bool disposing)\n {\n if ( disposing )\n {\n _cts.Cancel();\n StopRecording();\n _audioStream?.Dispose();\n _audioStream = null;\n PortAudio.Terminate();\n }\n\n base.Dispose(disposing);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleRenderer.cs", "// SubtitleRenderer.cs\n\nusing System.Collections.Concurrent;\nusing System.Drawing;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.Synthesis;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Main class responsible for rendering subtitles using the revised system.\n/// Integrates with audio events, processes segments, manages the timeline, and draws text.\n/// \npublic class SubtitleRenderer : IRenderComponent\n{\n private readonly IAudioProgressNotifier _audioNotifier;\n\n private readonly SubtitleOptions _config;\n\n private readonly FontProvider _fontProvider;\n\n private readonly FSColor _highlightColor;\n\n private readonly FSColor _normalColor;\n\n private readonly ConcurrentQueue _pendingSegments = new();\n\n private TimeSpan _currentPlaybackTime = TimeSpan.Zero;\n\n private GL? _gl;\n\n private bool _isDisposed = false;\n\n private List _linesToRender = new();\n\n private Task _processingTask = Task.CompletedTask;\n\n private SubtitleProcessor _subtitleProcessor;\n\n private SubtitleTimeline _subtitleTimeline;\n\n private TextMeasurer _textMeasurer;\n\n private TextRenderer _textRenderer;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n private IWordAnimator _wordAnimator;\n\n public SubtitleRenderer(\n IOptions configOptions,\n IAudioProgressNotifier audioNotifier,\n FontProvider fontProvider)\n {\n _config = configOptions.Value;\n _audioNotifier = audioNotifier;\n _fontProvider = fontProvider;\n\n var normalColorSys = ColorTranslator.FromHtml(_config.Color);\n _normalColor = new FSColor(normalColorSys.R, normalColorSys.G, normalColorSys.B, normalColorSys.A);\n var hColorSys = ColorTranslator.FromHtml(_config.HighlightColor);\n _highlightColor = new FSColor(hColorSys.R, hColorSys.G, hColorSys.B, hColorSys.A);\n\n SubscribeToAudioNotifier();\n }\n\n public void Dispose()\n {\n if ( _isDisposed )\n {\n return;\n }\n\n _isDisposed = true;\n\n UnsubscribeFromAudioNotifier();\n \n _pendingSegments.Clear();\n\n _linesToRender.Clear();\n\n GC.SuppressFinalize(this);\n }\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _viewportWidth = view.Size.X;\n _viewportHeight = view.Size.Y;\n\n var fontSystem = _fontProvider.GetFontSystem(_config.Font);\n var font = fontSystem.GetFont(_config.FontSize);\n\n _textMeasurer = new TextMeasurer(font, _config.SideMargin, _viewportWidth, _viewportHeight);\n _subtitleProcessor = new SubtitleProcessor(_textMeasurer, _config.AnimationDuration);\n _wordAnimator = new PopAnimator();\n\n _subtitleTimeline = new SubtitleTimeline(\n _config.MaxVisibleLines,\n _config.BottomMargin,\n _textMeasurer.LineHeight + 0.5f,\n _config.InterSegmentSpacing,\n _textMeasurer,\n _wordAnimator,\n _highlightColor,\n _normalColor\n );\n\n _textRenderer = new TextRenderer(_gl);\n\n Resize();\n }\n \n public bool UseSpout { get; } = true;\n\n public string SpoutTarget { get; } = \"Live2D\";\n\n public int Priority { get; } = -100;\n\n public void Update(float deltaTime)\n {\n if ( _isDisposed )\n {\n return;\n }\n\n var currentTime = (float)_currentPlaybackTime.TotalSeconds;\n\n _subtitleTimeline.Update(currentTime);\n\n _linesToRender = _subtitleTimeline.GetVisibleLinesAndPosition(currentTime, _viewportWidth, _viewportHeight);\n }\n\n public void Render(float deltaTime)\n {\n if ( _isDisposed || _gl == null )\n {\n return;\n }\n\n _textRenderer.Begin();\n\n foreach ( var line in _linesToRender )\n {\n foreach ( var word in line.Words )\n {\n if ( word.AnimationProgress > 0 || word.IsActive((float)_currentPlaybackTime.TotalSeconds) )\n {\n _textMeasurer.Font.DrawText(\n _textRenderer,\n word.Text,\n word.Position,\n word.CurrentColor,\n scale: word.CurrentScale,\n origin: word.Size / 2.0f,\n effect: FontSystemEffect.Stroked,\n effectAmount: _config.StrokeThickness\n );\n }\n }\n }\n\n _textRenderer.End();\n }\n\n public void Resize()\n {\n _viewportWidth = _config.Width;\n _viewportHeight = _config.Height;\n\n _textMeasurer.UpdateViewport(_viewportWidth, _viewportHeight);\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n }\n\n private void SubscribeToAudioNotifier()\n {\n _audioNotifier.ChunkPlaybackStarted += OnChunkPlaybackStarted;\n _audioNotifier.ChunkPlaybackEnded += OnChunkPlaybackEnded;\n _audioNotifier.PlaybackProgress += OnPlaybackProgress;\n }\n\n private void UnsubscribeFromAudioNotifier()\n {\n _audioNotifier.ChunkPlaybackStarted -= OnChunkPlaybackStarted;\n _audioNotifier.ChunkPlaybackEnded -= OnChunkPlaybackEnded;\n _audioNotifier.PlaybackProgress -= OnPlaybackProgress;\n }\n \n private void OnChunkPlaybackStarted(object? sender, AudioChunkPlaybackStartedEvent e)\n {\n _pendingSegments.Enqueue(e.Chunk);\n\n if ( _processingTask.IsCompleted )\n {\n _processingTask = Task.Run(ProcessPendingSegmentsAsync);\n }\n }\n\n private void OnChunkPlaybackEnded(object? sender, AudioChunkPlaybackEndedEvent e) { _subtitleTimeline.RemoveSegment(e.Chunk); }\n\n private void OnPlaybackProgress(object? sender, AudioPlaybackProgressEvent e) { _currentPlaybackTime = e.CurrentPlaybackTime; }\n\n private void ProcessPendingSegmentsAsync()\n {\n while ( _pendingSegments.TryDequeue(out var audioSegment) )\n {\n try\n {\n var segmentStartTime = (float)0f;\n\n var processedSegment = _subtitleProcessor.ProcessSegment(audioSegment, segmentStartTime);\n\n _subtitleTimeline.AddSegment(processedSegment);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error processing subtitle segment: {ex.Message}\");\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCVoiceProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCVoiceProvider : IRVCVoiceProvider\n{\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly ConcurrentDictionary _voicePaths = new();\n\n private bool _disposed;\n\n public RVCVoiceProvider(\n IModelProvider ittsModelProvider,\n ILogger logger)\n {\n _modelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n /// \n public async Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(voiceId) )\n {\n throw new ArgumentException(\"Voice ID cannot be null or empty\", nameof(voiceId));\n }\n\n return await GetVoicePathAsync(voiceId, cancellationToken);\n }\n\n /// \n public async Task> GetAvailableVoicesAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n // Get voice directory\n var model = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCVoices, cancellationToken);\n var voicesDir = model.Path;\n\n if ( !Directory.Exists(voicesDir) )\n {\n _logger.LogWarning(\"Voices directory not found: {Path}\", voicesDir);\n\n return Array.Empty();\n }\n\n // Get all .bin files\n var voiceFiles = Directory.GetFiles(voicesDir, \"*.onnx\");\n\n // Extract voice IDs from filenames\n var voiceIds = new List(voiceFiles.Length);\n\n foreach ( var file in voiceFiles )\n {\n var voiceId = Path.GetFileNameWithoutExtension(file);\n voiceIds.Add(voiceId);\n\n // Cache the path for faster lookup\n _voicePaths[voiceId] = file;\n }\n\n _logger.LogInformation(\"Found {Count} available RVC voices\", voiceIds.Count);\n\n return voiceIds;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available voices\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _voicePaths.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n private async Task GetVoicePathAsync(string voiceId, CancellationToken cancellationToken)\n {\n if ( _voicePaths.TryGetValue(voiceId, out var cachedPath) )\n {\n return cachedPath;\n }\n\n var model = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCVoices, cancellationToken);\n var voicesDir = model.Path;\n\n var voicePath = Path.Combine(voicesDir, $\"{voiceId}.onnx\");\n\n if ( !File.Exists(voicePath) )\n {\n _logger.LogWarning(\"Voice file not found: {Path}\", voicePath);\n\n throw new FileNotFoundException($\"Voice file not found for {voiceId}\", voicePath);\n }\n\n _voicePaths[voiceId] = voicePath;\n\n return voicePath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleProcessor.cs", "using System.Text;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Processes raw AudioSegments into structured SubtitleSegments containing lines and words\n/// with calculated timing and layout information.\n/// \npublic class SubtitleProcessor(TextMeasurer textMeasurer, float defaultWordDuration = 0.3f)\n{\n private readonly float _defaultWordDuration = Math.Max(0.01f, defaultWordDuration);\n\n public SubtitleSegment ProcessSegment(AudioSegment audioSegment, float segmentAbsoluteStartTime)\n {\n if ( audioSegment?.Tokens == null || audioSegment.Tokens.Count == 0 )\n {\n return new SubtitleSegment(audioSegment!, segmentAbsoluteStartTime, string.Empty);\n }\n\n // --- 1. Build Full Text ---\n\n var textBuilder = new StringBuilder();\n foreach ( var token in audioSegment.Tokens )\n {\n textBuilder.Append(token.Text);\n textBuilder.Append(token.Whitespace);\n }\n\n var fullText = textBuilder.ToString();\n\n var processedSegment = new SubtitleSegment(audioSegment, segmentAbsoluteStartTime, fullText);\n var currentLine = new SubtitleLine(0, 0);\n var currentLineWidth = 0f;\n var cumulativeTimeOffset = 0f;\n\n // --- 2. Iterate Tokens, Calculate Timing & Layout ---\n for ( var i = 0; i < audioSegment.Tokens.Count; i++ )\n {\n var token = audioSegment.Tokens[i];\n var wordText = token.Text + token.Whitespace;\n var wordSize = textMeasurer.MeasureText(wordText);\n\n // --- 3. Line Breaking ---\n if ( currentLineWidth > 0 && currentLineWidth + wordSize.X > textMeasurer.AvailableWidth )\n {\n processedSegment.AddLine(currentLine);\n currentLine = new SubtitleLine(processedSegment.Lines.Count, 0); // TODO: Get segment index properly if needed\n currentLineWidth = 0f;\n }\n\n // --- 4. Word Timing Calculation ---\n float wordStartTimeOffset;\n float wordDuration;\n\n if ( token.StartTs.HasValue )\n {\n wordStartTimeOffset = (float)token.StartTs.Value;\n if ( token.EndTs.HasValue )\n {\n // Case 1: Start and End provided\n wordDuration = (float)(token.EndTs.Value - token.StartTs.Value);\n }\n else\n {\n // Case 2: Only Start provided - Estimate duration until next token or use default\n var nextTokenStartOffset = FindNextTokenStartOffset(audioSegment, i);\n if ( nextTokenStartOffset > wordStartTimeOffset )\n {\n wordDuration = nextTokenStartOffset - wordStartTimeOffset;\n }\n else\n {\n wordDuration = _defaultWordDuration;\n }\n }\n }\n else\n {\n // Case 3: No Start provided - Estimate start based on previous word's end or cumulative time\n wordStartTimeOffset = cumulativeTimeOffset;\n var nextTokenStartOffset = FindNextTokenStartOffset(audioSegment, i);\n if ( nextTokenStartOffset > wordStartTimeOffset )\n {\n wordDuration = nextTokenStartOffset - wordStartTimeOffset;\n }\n else\n {\n wordDuration = _defaultWordDuration;\n }\n }\n\n wordDuration = Math.Max(0.01f, wordDuration);\n\n cumulativeTimeOffset = wordStartTimeOffset + wordDuration;\n\n // --- 5. Create Word Info ---\n var wordInfo = new SubtitleWordInfo { Text = wordText, Size = wordSize, AbsoluteStartTime = segmentAbsoluteStartTime + wordStartTimeOffset, Duration = wordDuration };\n\n currentLine.AddWord(wordInfo);\n currentLineWidth += wordSize.X;\n }\n\n if ( currentLine.Words.Count > 0 )\n {\n processedSegment.AddLine(currentLine);\n }\n\n return processedSegment;\n }\n\n private float FindNextTokenStartOffset(AudioSegment segment, int currentTokenIndex)\n {\n for ( var j = currentTokenIndex + 1; j < segment.Tokens.Count; j++ )\n {\n if ( segment.Tokens[j].StartTs.HasValue )\n {\n return (float)segment.Tokens[j].StartTs!.Value;\n }\n }\n\n // Indicate not found or end of segment\n // Return a value that ensures the calling logic uses the default duration.\n // Returning -1 or float.MaxValue could work, depending on how it's used.\n // Let's return a value <= the current offset to trigger default duration.\n return segment.Tokens[currentTokenIndex].StartTs.HasValue ? (float)segment.Tokens[currentTokenIndex].StartTs!.Value : 0f;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/DefaultAudioBufferManager.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Default implementation of IAudioBufferManager.\n/// \npublic class DefaultAudioBufferManager : IAudioBufferManager\n{\n private readonly BlockingCollection<(Memory Data, AudioSegment Segment)> _audioQueue;\n\n private readonly ILogger _logger;\n\n private readonly int _maxBufferCount;\n\n private bool _disposed;\n\n public DefaultAudioBufferManager(int maxBufferCount = 32, ILogger? logger = null)\n {\n _maxBufferCount = maxBufferCount > 0\n ? maxBufferCount\n : throw new ArgumentException(\"Max buffer count must be positive\", nameof(maxBufferCount));\n\n _logger = logger ?? NullLogger.Instance;\n _audioQueue = new BlockingCollection<(Memory, AudioSegment)>(_maxBufferCount);\n }\n\n public int BufferCount => _audioQueue.Count;\n\n public bool ProducerCompleted { get; private set; }\n\n public async Task EnqueueSegmentsAsync(\n IAsyncEnumerable audioSegments,\n CancellationToken cancellationToken)\n {\n try\n {\n ProducerCompleted = false;\n\n await foreach ( var segment in audioSegments.WithCancellation(cancellationToken) )\n {\n if ( segment.AudioData.Length <= 0 || cancellationToken.IsCancellationRequested )\n {\n continue;\n }\n\n try\n {\n // Add to bounded collection - will block if queue is full (applying backpressure)\n _audioQueue.Add((segment.AudioData, segment), cancellationToken);\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n // Expected when cancellation is requested\n break;\n }\n catch (InvalidOperationException) when (_audioQueue.IsAddingCompleted)\n {\n // Queue was completed during processing\n break;\n }\n }\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n _logger.LogInformation(\"Audio enqueuing cancelled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error while enqueuing audio segments\");\n\n throw;\n }\n finally\n {\n ProducerCompleted = true;\n }\n }\n\n public bool TryGetNextBuffer(\n out (Memory Data, AudioSegment Segment) buffer,\n int timeoutMs,\n CancellationToken cancellationToken)\n {\n return _audioQueue.TryTake(out buffer, timeoutMs, cancellationToken);\n }\n\n public void Clear()\n {\n while ( _audioQueue.TryTake(out _) ) { }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n\n try\n {\n _audioQueue.Dispose();\n await Task.CompletedTask; // For async consistency\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error disposing audio buffer manager\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModel.cs", "using System.Numerics;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\npublic class CubismModel : IDisposable\n{\n /// \n /// 存在していないパラメータIDのリスト\n /// \n private readonly Dictionary _notExistParameterId = [];\n\n /// \n /// 存在していないパラメータの値のリスト\n /// \n private readonly Dictionary _notExistParameterValues = [];\n\n /// \n /// 存在していないパーツIDのリスト\n /// \n private readonly Dictionary _notExistPartId = [];\n\n /// \n /// 存在していないパーツの不透明度のリスト\n /// \n private readonly Dictionary _notExistPartOpacities = [];\n\n /// \n /// パラメータの最大値のリスト\n /// \n private readonly unsafe float* _parameterMaximumValues;\n\n /// \n /// パラメータの最小値のリスト\n /// \n private readonly unsafe float* _parameterMinimumValues;\n\n /// \n /// パラメータの値のリスト\n /// \n private readonly unsafe float* _parameterValues;\n\n /// \n /// Partの子DrawableIndexの配列\n /// \n private readonly List[] _partChildDrawables;\n\n /// \n /// パーツの不透明度のリスト\n /// \n private readonly unsafe float* _partOpacities;\n\n /// \n /// 保存されたパラメータ\n /// \n private readonly List _savedParameters = [];\n\n /// \n /// カリング設定の配列\n /// \n private readonly List _userCullings = [];\n\n /// \n /// Drawable スクリーン色の配列\n /// \n private readonly List _userMultiplyColors = [];\n\n /// \n /// Part スクリーン色の配列\n /// \n private readonly List _userPartMultiplyColors = [];\n\n /// \n /// Part 乗算色の配列\n /// \n private readonly List _userPartScreenColors = [];\n\n /// \n /// Drawable 乗算色の配列\n /// \n private readonly List _userScreenColors = [];\n\n public readonly List DrawableIds = [];\n\n public readonly List ParameterIds = [];\n\n public readonly List PartIds = [];\n\n /// \n /// モデルのカリング設定をすべて上書きするか?\n /// \n private bool _isOverwrittenCullings;\n\n /// \n /// 乗算色を全て上書きするか?\n /// \n private bool _isOverwrittenModelMultiplyColors;\n\n /// \n /// スクリーン色を全て上書きするか?\n /// \n private bool _isOverwrittenModelScreenColors;\n\n /// \n /// モデルの不透明度\n /// \n private float _modelOpacity;\n\n public unsafe CubismModel(IntPtr model)\n {\n Model = model;\n _modelOpacity = 1.0f;\n\n _parameterValues = CubismCore.GetParameterValues(Model);\n _partOpacities = CubismCore.GetPartOpacities(Model);\n _parameterMaximumValues = CubismCore.GetParameterMaximumValues(Model);\n _parameterMinimumValues = CubismCore.GetParameterMinimumValues(Model);\n\n {\n var parameterIds = CubismCore.GetParameterIds(Model);\n var parameterCount = CubismCore.GetParameterCount(Model);\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n var str = new string(parameterIds[i]);\n ParameterIds.Add(CubismFramework.CubismIdManager.GetId(str));\n }\n }\n\n var partCount = CubismCore.GetPartCount(Model);\n var partIds = CubismCore.GetPartIds(Model);\n\n _partChildDrawables = new List[partCount];\n for ( var i = 0; i < partCount; ++i )\n {\n var str = new string(partIds[i]);\n PartIds.Add(CubismFramework.CubismIdManager.GetId(str));\n _partChildDrawables[i] = [];\n }\n\n var drawableIds = CubismCore.GetDrawableIds(Model);\n var drawableCount = CubismCore.GetDrawableCount(Model);\n\n // カリング設定\n var userCulling = new DrawableCullingData { IsOverwritten = false, IsCulling = false };\n\n // 乗算色\n var multiplyColor = new CubismTextureColor();\n\n // スクリーン色\n var screenColor = new CubismTextureColor(0, 0, 0, 1.0f);\n\n // Parts\n for ( var i = 0; i < partCount; ++i )\n {\n _userPartMultiplyColors.Add(new PartColorData {\n IsOverwritten = false, Color = multiplyColor // 乗算色\n });\n\n _userPartScreenColors.Add(new PartColorData {\n IsOverwritten = false, Color = screenColor // スクリーン色\n });\n }\n\n // Drawables\n for ( var i = 0; i < drawableCount; ++i )\n {\n var str = new string(drawableIds[i]);\n DrawableIds.Add(CubismFramework.CubismIdManager.GetId(str));\n _userMultiplyColors.Add(new DrawableColorData {\n IsOverwritten = false, Color = multiplyColor // 乗算色\n });\n\n _userScreenColors.Add(new DrawableColorData {\n IsOverwritten = false, Color = screenColor // スクリーン色\n });\n\n _userCullings.Add(userCulling);\n\n var parentIndex = CubismCore.GetDrawableParentPartIndices(Model)[i];\n if ( parentIndex >= 0 )\n {\n _partChildDrawables[parentIndex].Add(i);\n }\n }\n }\n\n /// \n /// モデル\n /// \n public IntPtr Model { get; }\n\n public void Dispose()\n {\n CubismFramework.DeallocateAligned(Model);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// partのOverwriteColor Set関数\n /// \n public void SetPartColor(int partIndex, float r, float g, float b, float a,\n List partColors, List drawableColors)\n {\n partColors[partIndex].Color.R = r;\n partColors[partIndex].Color.G = g;\n partColors[partIndex].Color.B = b;\n partColors[partIndex].Color.A = a;\n\n if ( partColors[partIndex].IsOverwritten )\n {\n for ( var i = 0; i < _partChildDrawables[partIndex].Count; i++ )\n {\n var drawableIndex = _partChildDrawables[partIndex][i];\n drawableColors[drawableIndex].Color.R = r;\n drawableColors[drawableIndex].Color.G = g;\n drawableColors[drawableIndex].Color.B = b;\n drawableColors[drawableIndex].Color.A = a;\n }\n }\n }\n\n /// \n /// partのOverwriteFlag Set関数\n /// \n public void SetOverwriteColorForPartColors(int partIndex, bool value,\n List partColors, List drawableColors)\n {\n partColors[partIndex].IsOverwritten = value;\n\n for ( var i = 0; i < _partChildDrawables[partIndex].Count; i++ )\n {\n var drawableIndex = _partChildDrawables[partIndex][i];\n drawableColors[drawableIndex].IsOverwritten = value;\n if ( value )\n {\n drawableColors[drawableIndex].Color.R = partColors[partIndex].Color.R;\n drawableColors[drawableIndex].Color.G = partColors[partIndex].Color.G;\n drawableColors[drawableIndex].Color.B = partColors[partIndex].Color.B;\n drawableColors[drawableIndex].Color.A = partColors[partIndex].Color.A;\n }\n }\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n public void Update()\n {\n // Update model.\n CubismCore.UpdateModel(Model);\n // Reset dynamic drawable flags.\n CubismCore.ResetDrawableDynamicFlags(Model);\n }\n\n /// \n /// Pixel単位でキャンバスの幅の取得\n /// \n /// キャンバスの幅(pixel)\n public float GetCanvasWidthPixel()\n {\n if ( Model == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out _);\n\n return tmpSizeInPixels.X;\n }\n\n /// \n /// Pixel単位でキャンバスの高さの取得\n /// \n /// キャンバスの高さ(pixel)\n public float GetCanvasHeightPixel()\n {\n if ( new IntPtr(Model) == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out _);\n\n return tmpSizeInPixels.Y;\n }\n\n /// \n /// PixelsPerUnitを取得する。\n /// \n /// PixelsPerUnit\n public float GetPixelsPerUnit()\n {\n if ( new IntPtr(Model) == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out _, out _, out var tmpPixelsPerUnit);\n\n return tmpPixelsPerUnit;\n }\n\n /// \n /// Unit単位でキャンバスの幅の取得\n /// \n /// キャンバスの幅(Unit)\n public float GetCanvasWidth()\n {\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out var tmpPixelsPerUnit);\n\n return tmpSizeInPixels.X / tmpPixelsPerUnit;\n }\n\n /// \n /// Unit単位でキャンバスの高さの取得\n /// \n /// キャンバスの高さ(Unit)\n public float GetCanvasHeight()\n {\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out var tmpPixelsPerUnit);\n\n return tmpSizeInPixels.Y / tmpPixelsPerUnit;\n }\n\n /// \n /// パーツのインデックスを取得する。\n /// \n /// パーツのID\n /// パーツのインデックス\n public int GetPartIndex(string partId)\n {\n var partIndex = PartIds.IndexOf(partId);\n if ( partIndex != -1 )\n {\n return partIndex;\n }\n\n var partCount = CubismCore.GetPartCount(Model);\n\n // モデルに存在していない場合、非存在パーツIDリスト内にあるかを検索し、そのインデックスを返す\n if ( _notExistPartId.TryGetValue(partId, out var item) )\n {\n return item;\n }\n\n // 非存在パーツIDリストにない場合、新しく要素を追加する\n partIndex = partCount + _notExistPartId.Count;\n\n _notExistPartId.TryAdd(partId, partIndex);\n _notExistPartOpacities.Add(partIndex, 0);\n\n return partIndex;\n }\n\n /// \n /// パーツのIDを取得する。\n /// \n /// パーツのIndex\n /// パーツのID\n public string GetPartId(int partIndex)\n {\n if ( 0 <= partIndex && partIndex < PartIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of PartIds size\");\n }\n\n return PartIds[partIndex];\n }\n\n /// \n /// パーツの個数を取得する。\n /// \n /// パーツの個数\n public int GetPartCount() { return CubismCore.GetPartCount(Model); }\n\n /// \n /// パーツの不透明度を設定する。\n /// \n /// パーツのID\n /// 不透明度\n public void SetPartOpacity(string partId, float opacity)\n {\n // 高速化のためにPartIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var index = GetPartIndex(partId);\n\n if ( index < 0 )\n {\n return; // パーツが無いのでスキップ\n }\n\n SetPartOpacity(index, opacity);\n }\n\n /// \n /// パーツの不透明度を設定する。\n /// \n /// パーツのインデックス\n /// パーツの不透明度\n public unsafe void SetPartOpacity(int partIndex, float opacity)\n {\n if ( _notExistPartOpacities.ContainsKey(partIndex) )\n {\n _notExistPartOpacities[partIndex] = opacity;\n\n return;\n }\n\n //インデックスの範囲内検知\n if ( 0 > partIndex || partIndex >= GetPartCount() )\n {\n throw new ArgumentException(\"partIndex out of range\");\n }\n\n _partOpacities[partIndex] = opacity;\n }\n\n /// \n /// パーツの不透明度を取得する。\n /// \n /// パーツのID\n /// パーツの不透明度\n public float GetPartOpacity(string partId)\n {\n // 高速化のためにPartIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var index = GetPartIndex(partId);\n\n if ( index < 0 )\n {\n return 0; //パーツが無いのでスキップ\n }\n\n return GetPartOpacity(index);\n }\n\n /// \n /// パーツの不透明度を取得する。\n /// \n /// パーツのインデックス\n /// パーツの不透明度\n public unsafe float GetPartOpacity(int partIndex)\n {\n if ( _notExistPartOpacities.TryGetValue(partIndex, out var value) )\n {\n // モデルに存在しないパーツIDの場合、非存在パーツリストから不透明度を返す\n return value;\n }\n\n //インデックスの範囲内検知\n if ( 0 > partIndex || partIndex >= GetPartCount() )\n {\n throw new ArgumentException(\"partIndex out of range\");\n }\n\n return _partOpacities[partIndex];\n }\n\n /// \n /// パラメータのインデックスを取得する。\n /// \n /// パラメータID\n /// パラメータのインデックス\n public int GetParameterIndex(string parameterId)\n {\n var parameterIndex = ParameterIds.IndexOf(parameterId);\n if ( parameterIndex != -1 )\n {\n return parameterIndex;\n }\n\n // モデルに存在していない場合、非存在パラメータIDリスト内を検索し、そのインデックスを返す\n if ( _notExistParameterId.TryGetValue(parameterId, out var data) )\n {\n return data;\n }\n\n // 非存在パラメータIDリストにない場合、新しく要素を追加する\n parameterIndex = CubismCore.GetParameterCount(Model) + _notExistParameterId.Count;\n\n _notExistParameterId.TryAdd(parameterId, parameterIndex);\n _notExistParameterValues.Add(parameterIndex, 0);\n\n return parameterIndex;\n }\n\n /// \n /// パラメータの個数を取得する。\n /// \n /// パラメータの個数\n public int GetParameterCount() { return CubismCore.GetParameterCount(Model); }\n\n /// \n /// パラメータの種類を取得する。\n /// \n /// パラメータのインデックス\n /// \n /// csmParameterType_Normal -> 通常のパラメータ\n /// csmParameterType_BlendShape -> ブレンドシェイプパラメータ\n /// \n public unsafe int GetParameterType(int parameterIndex) { return CubismCore.GetParameterTypes(Model)[parameterIndex]; }\n\n /// \n /// パラメータの最大値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの最大値\n public unsafe float GetParameterMaximumValue(int parameterIndex) { return CubismCore.GetParameterMaximumValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータの最小値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの最小値\n public unsafe float GetParameterMinimumValue(int parameterIndex) { return CubismCore.GetParameterMinimumValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータのデフォルト値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータのデフォルト値\n public unsafe float GetParameterDefaultValue(int parameterIndex) { return CubismCore.GetParameterDefaultValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータの値を取得する。\n /// \n /// パラメータID\n /// パラメータの値\n public float GetParameterValue(string parameterId)\n {\n // 高速化のためにParameterIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var parameterIndex = GetParameterIndex(parameterId);\n\n return GetParameterValue(parameterIndex);\n }\n\n /// \n /// パラメータの値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの値\n public unsafe float GetParameterValue(int parameterIndex)\n {\n if ( _notExistParameterValues.TryGetValue(parameterIndex, out var item) )\n {\n return item;\n }\n\n //インデックスの範囲内検知\n if ( 0 > parameterIndex || parameterIndex >= GetParameterCount() )\n {\n throw new ArgumentException(\"parameterIndex out of range\");\n }\n\n return _parameterValues[parameterIndex];\n }\n\n /// \n /// パラメータの値を設定する。\n /// \n /// パラメータID\n /// パラメータの値\n /// 重み\n public void SetParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n SetParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を設定する。\n /// \n /// パラメータのインデックス\n /// パラメータの値\n /// 重み\n public unsafe void SetParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( _notExistParameterValues.TryGetValue(parameterIndex, out var value1) )\n {\n _notExistParameterValues[parameterIndex] = weight == 1\n ? value\n : value1 * (1 - weight) + value * weight;\n\n return;\n }\n\n //インデックスの範囲内検知\n if ( 0 > parameterIndex || parameterIndex >= GetParameterCount() )\n {\n throw new ArgumentException(\"parameterIndex out of range\");\n }\n\n if ( CubismCore.GetParameterMaximumValues(Model)[parameterIndex] < value )\n {\n value = CubismCore.GetParameterMaximumValues(Model)[parameterIndex];\n }\n\n if ( CubismCore.GetParameterMinimumValues(Model)[parameterIndex] > value )\n {\n value = CubismCore.GetParameterMinimumValues(Model)[parameterIndex];\n }\n\n _parameterValues[parameterIndex] = weight == 1\n ? value\n : _parameterValues[parameterIndex] = _parameterValues[parameterIndex] * (1 - weight) + value * weight;\n }\n\n /// \n /// パラメータの値を加算する。\n /// \n /// パラメータID\n /// 加算する値\n /// 重み\n public void AddParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n AddParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を加算する。\n /// \n /// パラメータのインデックス\n /// 加算する値\n /// 重み\n public void AddParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( parameterIndex == -1 )\n {\n return;\n }\n\n SetParameterValue(parameterIndex, GetParameterValue(parameterIndex) + value * weight);\n }\n\n /// \n /// パラメータの値を乗算する。\n /// \n /// パラメータID\n /// 乗算する値\n /// 重み\n public void MultiplyParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n MultiplyParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を乗算する。\n /// \n /// パラメータのインデックス\n /// 乗算する値\n /// 重み\n public void MultiplyParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( parameterIndex == -1 )\n {\n return;\n }\n\n SetParameterValue(parameterIndex, GetParameterValue(parameterIndex) * (1.0f + (value - 1.0f) * weight));\n }\n\n /// \n /// Drawableのインデックスを取得する。\n /// \n /// DrawableのID\n /// Drawableのインデックス\n public int GetDrawableIndex(string drawableId) { return DrawableIds.IndexOf(drawableId); }\n\n /// \n /// Drawableの個数を取得する。\n /// \n /// Drawableの個数\n public int GetDrawableCount() { return CubismCore.GetDrawableCount(Model); }\n\n /// \n /// DrawableのIDを取得する。\n /// \n /// Drawableのインデックス\n /// DrawableのID\n public string GetDrawableId(int drawableIndex)\n {\n if ( 0 <= drawableIndex && drawableIndex < DrawableIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of DrawableIds size\");\n }\n\n return DrawableIds[drawableIndex];\n }\n\n /// \n /// Drawableの描画順リストを取得する。\n /// \n /// Drawableの描画順リスト\n public unsafe int* GetDrawableRenderOrders() { return CubismCore.GetDrawableRenderOrders(Model); }\n\n /// \n /// Drawableのテクスチャインデックスリストの取得\n /// 関数名が誤っていたため、代替となる getDrawableTextureIndex を追加し、この関数は非推奨となりました。\n /// \n /// Drawableのインデックス\n /// Drawableのテクスチャインデックスリスト\n public int GetDrawableTextureIndices(int drawableIndex) { return GetDrawableTextureIndex(drawableIndex); }\n\n /// \n /// Drawableのテクスチャインデックスを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのテクスチャインデックス\n public unsafe int GetDrawableTextureIndex(int drawableIndex)\n {\n var textureIndices = CubismCore.GetDrawableTextureIndices(Model);\n\n return textureIndices[drawableIndex];\n }\n\n /// \n /// Drawableの頂点インデックスの個数を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点インデックスの個数\n public unsafe int GetDrawableVertexIndexCount(int drawableIndex) { return CubismCore.GetDrawableIndexCounts(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点の個数を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点の個数\n public unsafe int GetDrawableVertexCount(int drawableIndex) { return CubismCore.GetDrawableVertexCounts(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点リストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点リスト\n public unsafe float* GetDrawableVertices(int drawableIndex) { return (float*)GetDrawableVertexPositions(drawableIndex); }\n\n /// \n /// Drawableの頂点インデックスリストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点インデックスリスト\n public unsafe ushort* GetDrawableVertexIndices(int drawableIndex) { return CubismCore.GetDrawableIndices(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点リストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点リスト\n public unsafe Vector2* GetDrawableVertexPositions(int drawableIndex) { return CubismCore.GetDrawableVertexPositions(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点のUVリストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点のUVリスト\n public unsafe Vector2* GetDrawableVertexUvs(int drawableIndex) { return CubismCore.GetDrawableVertexUvs(Model)[drawableIndex]; }\n\n /// \n /// Drawableの不透明度を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの不透明度\n public unsafe float GetDrawableOpacity(int drawableIndex) { return CubismCore.GetDrawableOpacities(Model)[drawableIndex]; }\n\n /// \n /// Drawableの乗算色を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの乗算色\n public unsafe Vector4 GetDrawableMultiplyColor(int drawableIndex) { return CubismCore.GetDrawableMultiplyColors(Model)[drawableIndex]; }\n\n /// \n /// Drawableのスクリーン色を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのスクリーン色\n public unsafe Vector4 GetDrawableScreenColor(int drawableIndex) { return CubismCore.GetDrawableScreenColors(Model)[drawableIndex]; }\n\n /// \n /// Drawableの親パーツのインデックスを取得する。\n /// \n /// Drawableのインデックス\n /// drawableの親パーツのインデックス\n public unsafe int GetDrawableParentPartIndex(int drawableIndex) { return CubismCore.GetDrawableParentPartIndices(Model)[drawableIndex]; }\n\n /// \n /// Drawableのブレンドモードを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのブレンドモード\n public unsafe CubismBlendMode GetDrawableBlendMode(int drawableIndex)\n {\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model)[drawableIndex];\n\n return IsBitSet(constantFlags, CsmEnum.CsmBlendAdditive)\n ? CubismBlendMode.Additive\n : IsBitSet(constantFlags, CsmEnum.CsmBlendMultiplicative)\n ? CubismBlendMode.Multiplicative\n : CubismBlendMode.Normal;\n }\n\n /// \n /// Drawableのマスク使用時の反転設定を取得する。\n /// マスクを使用しない場合は無視される\n /// \n /// Drawableのインデックス\n /// Drawableのマスクの反転設定\n public unsafe bool GetDrawableInvertedMask(int drawableIndex)\n {\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model)[drawableIndex];\n\n return IsBitSet(constantFlags, CsmEnum.CsmIsInvertedMask);\n }\n\n /// \n /// Drawableの表示情報を取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableが表示\n /// false Drawableが非表示\n /// \n public unsafe bool GetDrawableDynamicFlagIsVisible(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmIsVisible);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの表示状態が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの表示状態が直近のCubismModel::Update関数で変化した\n /// false Drawableの表示状態が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagVisibilityDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmVisibilityDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの不透明度が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの不透明度が直近のCubismModel::Update関数で変化した\n /// false Drawableの不透明度が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagOpacityDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmOpacityDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableのDrawOrderが変化したかを取得する。\n /// DrawOrderはArtMesh上で指定する0から1000の情報\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの不透明度が直近のCubismModel::Update関数で変化した\n /// false Drawableの不透明度が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagDrawOrderDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmDrawOrderDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの描画の順序が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの描画の順序が直近のCubismModel::Update関数で変化した\n /// false Drawableの描画の順序が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagRenderOrderDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmRenderOrderDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの頂点情報が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの頂点情報が直近のCubismModel::Update関数で変化した\n /// false Drawableの頂点情報が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagVertexPositionsDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmVertexPositionsDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの乗算色・スクリーン色が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの乗算色・スクリーン色が直近のCubismModel::Update関数で変化した\n /// false Drawableの乗算色・スクリーン色が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagBlendColorDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmBlendColorDidChange);\n }\n\n /// \n /// Drawableのクリッピングマスクリストを取得する。\n /// \n /// Drawableのクリッピングマスクリスト\n public unsafe int** GetDrawableMasks() { return CubismCore.GetDrawableMasks(Model); }\n\n /// \n /// Drawableのクリッピングマスクの個数リストを取得する。\n /// \n /// Drawableのクリッピングマスクの個数リスト\n public unsafe int* GetDrawableMaskCounts() { return CubismCore.GetDrawableMaskCounts(Model); }\n\n /// \n /// クリッピングマスクを使用しているかどうか?\n /// \n /// \n /// true クリッピングマスクを使用している\n /// false クリッピングマスクを使用していない\n /// \n public unsafe bool IsUsingMasking()\n {\n for ( var d = 0; d < CubismCore.GetDrawableCount(Model); ++d )\n {\n if ( CubismCore.GetDrawableMaskCounts(Model)[d] <= 0 )\n {\n continue;\n }\n\n return true;\n }\n\n return false;\n }\n\n /// \n /// 保存されたパラメータを読み込む\n /// \n public unsafe void LoadParameters()\n {\n var parameterCount = CubismCore.GetParameterCount(Model);\n var savedParameterCount = _savedParameters.Count;\n\n if ( parameterCount > savedParameterCount )\n {\n parameterCount = savedParameterCount;\n }\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n _parameterValues[i] = _savedParameters[i];\n }\n }\n\n /// \n /// パラメータを保存する。\n /// \n public unsafe void SaveParameters()\n {\n var parameterCount = CubismCore.GetParameterCount(Model);\n var savedParameterCount = _savedParameters.Count;\n\n if ( savedParameterCount != parameterCount )\n {\n _savedParameters.Clear();\n for ( var i = 0; i < parameterCount; ++i )\n {\n _savedParameters.Add(_parameterValues[i]);\n }\n }\n else\n {\n for ( var i = 0; i < parameterCount; ++i )\n {\n _savedParameters[i] = _parameterValues[i];\n }\n }\n }\n\n /// \n /// drawableの乗算色を取得する\n /// \n public CubismTextureColor GetMultiplyColor(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelMultiplyColors() ||\n GetOverwriteFlagForDrawableMultiplyColors(drawableIndex) )\n {\n return _userMultiplyColors[drawableIndex].Color;\n }\n\n var color = GetDrawableMultiplyColor(drawableIndex);\n\n return new CubismTextureColor(color.X, color.Y, color.Z, color.W);\n }\n\n /// \n /// drawableのスクリーン色を取得する\n /// \n public CubismTextureColor GetScreenColor(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelScreenColors() ||\n GetOverwriteFlagForDrawableScreenColors(drawableIndex) )\n {\n return _userScreenColors[drawableIndex].Color;\n }\n\n var color = GetDrawableScreenColor(drawableIndex);\n\n return new CubismTextureColor(color.X, color.Y, color.Z, color.W);\n }\n\n /// \n /// drawableの乗算色を設定する\n /// \n public void SetMultiplyColor(int drawableIndex, CubismTextureColor color) { SetMultiplyColor(drawableIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// drawableの乗算色を設定する\n /// \n public void SetMultiplyColor(int drawableIndex, float r, float g, float b, float a = 1.0f)\n {\n _userMultiplyColors[drawableIndex].Color.R = r;\n _userMultiplyColors[drawableIndex].Color.G = g;\n _userMultiplyColors[drawableIndex].Color.B = b;\n _userMultiplyColors[drawableIndex].Color.A = a;\n }\n\n /// \n /// drawableのスクリーン色を設定する\n /// \n /// \n /// \n public void SetScreenColor(int drawableIndex, CubismTextureColor color) { SetScreenColor(drawableIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// drawableのスクリーン色を設定する\n /// \n public void SetScreenColor(int drawableIndex, float r, float g, float b, float a = 1.0f)\n {\n _userScreenColors[drawableIndex].Color.R = r;\n _userScreenColors[drawableIndex].Color.G = g;\n _userScreenColors[drawableIndex].Color.B = b;\n _userScreenColors[drawableIndex].Color.A = a;\n }\n\n /// \n /// partの乗算色を取得する\n /// \n public CubismTextureColor GetPartMultiplyColor(int partIndex) { return _userPartMultiplyColors[partIndex].Color; }\n\n /// \n /// partの乗算色を取得する\n /// \n public CubismTextureColor GetPartScreenColor(int partIndex) { return _userPartScreenColors[partIndex].Color; }\n\n /// \n /// partのスクリーン色を設定する\n /// \n public void SetPartMultiplyColor(int partIndex, CubismTextureColor color) { SetPartMultiplyColor(partIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// partの乗算色を設定する\n /// \n public void SetPartMultiplyColor(int partIndex, float r, float g, float b, float a = 1.0f) { SetPartColor(partIndex, r, g, b, a, _userPartMultiplyColors, _userMultiplyColors); }\n\n /// \n /// partのスクリーン色を設定する\n /// \n public void SetPartScreenColor(int partIndex, CubismTextureColor color) { SetPartScreenColor(partIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// partのスクリーン色を設定する\n /// \n /// \n public void SetPartScreenColor(int partIndex, float r, float g, float b, float a = 1.0f) { SetPartColor(partIndex, r, g, b, a, _userPartScreenColors, _userScreenColors); }\n\n /// \n /// SDKからモデル全体の乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForModelMultiplyColors() { return _isOverwrittenModelMultiplyColors; }\n\n /// \n /// SDKからモデル全体のスクリーン色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForModelScreenColors() { return _isOverwrittenModelScreenColors; }\n\n /// \n /// SDKからモデル全体の乗算色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForModelMultiplyColors(bool value) { _isOverwrittenModelMultiplyColors = value; }\n\n /// \n /// SDKからモデル全体のスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForModelScreenColors(bool value) { _isOverwrittenModelScreenColors = value; }\n\n /// \n /// SDKからdrawableの乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForDrawableMultiplyColors(int drawableIndex) { return _userMultiplyColors[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableのスクリーン色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForDrawableScreenColors(int drawableIndex) { return _userScreenColors[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableの乗算色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableMultiplyColors(int drawableIndex, bool value) { _userMultiplyColors[drawableIndex].IsOverwritten = value; }\n\n /// \n /// SDKからdrawableのスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableScreenColors(int drawableIndex, bool value) { _userScreenColors[drawableIndex].IsOverwritten = value; }\n\n /// \n /// SDKからpartの乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteColorForPartMultiplyColors(int partIndex) { return _userPartMultiplyColors[partIndex].IsOverwritten; }\n\n /// \n /// SDKからpartのスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public bool GetOverwriteColorForPartScreenColors(int partIndex) { return _userPartScreenColors[partIndex].IsOverwritten; }\n\n /// \n /// Drawableのカリング情報を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのカリング情報\n public unsafe bool GetDrawableCulling(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelCullings() || GetOverwriteFlagForDrawableCullings(drawableIndex) )\n {\n return _userCullings[drawableIndex].IsCulling;\n }\n\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model);\n\n return !IsBitSet(constantFlags[drawableIndex], CsmEnum.CsmIsDoubleSided);\n }\n\n /// \n /// Drawableのカリング情報を設定する\n /// \n public void SetDrawableCulling(int drawableIndex, bool isCulling) { _userCullings[drawableIndex].IsCulling = isCulling; }\n\n /// \n /// SDKからモデル全体のカリング設定を上書きするか。\n /// \n /// \n /// true -> SDK上のカリング設定を使用\n /// false -> モデルのカリング設定を使用\n /// \n public bool GetOverwriteFlagForModelCullings() { return _isOverwrittenCullings; }\n\n /// \n /// SDKからモデル全体のカリング設定を上書きするかをセットする\n /// SDK上のカリング設定を使うならtrue、モデルのカリング設定を使うならfalse\n /// \n public void SetOverwriteFlagForModelCullings(bool value) { _isOverwrittenCullings = value; }\n\n /// \n /// SDKからdrawableのカリング設定を上書きするか。\n /// \n /// \n /// true -> SDK上のカリング設定を使用\n /// false -> モデルのカリング設定を使用\n /// \n public bool GetOverwriteFlagForDrawableCullings(int drawableIndex) { return _userCullings[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableのカリング設定を上書きするかをセットする\n /// SDK上のカリング設定を使うならtrue、モデルのカリング設定を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableCullings(int drawableIndex, bool value) { _userCullings[drawableIndex].IsOverwritten = value; }\n\n /// \n /// モデルの不透明度を取得する\n /// \n /// 不透明度の値\n public float GetModelOpacity() { return _modelOpacity; }\n\n /// \n /// モデルの不透明度を設定する\n /// \n /// 不透明度の値\n public void SetModelOpacity(float value) { _modelOpacity = value; }\n\n private static bool IsBitSet(byte data, byte mask) { return (data & mask) == mask; }\n\n public void SetOverwriteColorForPartMultiplyColors(int partIndex, bool value)\n {\n _userPartMultiplyColors[partIndex].IsOverwritten = value;\n SetOverwriteColorForPartColors(partIndex, value, _userPartMultiplyColors, _userMultiplyColors);\n }\n\n public void SetOverwriteColorForPartScreenColors(int partIndex, bool value)\n {\n _userPartScreenColors[partIndex].IsOverwritten = value;\n SetOverwriteColorForPartColors(partIndex, value, _userPartScreenColors, _userScreenColors);\n }\n\n /// \n /// パラメータのIDを取得する。\n /// \n /// パラメータのIndex\n /// パラメータのID\n public string GetParameterId(int parameterIndex)\n {\n if ( 0 <= parameterIndex && parameterIndex < ParameterIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of ParameterIds size\");\n }\n\n return ParameterIds[parameterIndex];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/WaveFileUtils.cs", "using System.Buffers;\n\nusing PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.Utils;\n\n/// \n/// Utility class for reading and writing wave files.\n/// \ninternal class WaveFileUtils\n{\n private static readonly byte[] ExpectedSubFormatForPcm = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71];\n\n public static async Task ParseHeaderAsync(Stream stream, CancellationToken cancellationToken)\n {\n var toReturn = new List();\n try\n {\n var headerChunks = new MergedMemoryChunks();\n\n // We load the first 44 bytes directly as we know that is the minimum size for a wave file header.\n if ( !await HaveEnoughDataAsync(headerChunks, 44, stream, toReturn, cancellationToken) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n AudioSourceHeader? header = null;\n\n var chunkID = headerChunks.ReadUInt32LittleEndian();\n // Skip the file size\n headerChunks.TrySkip(4);\n var riffType = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkID != 0x46464952 /*'RIFF'*/ || riffType != 0x45564157 /*'WAVE'*/ )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file header.\");\n }\n\n // Read chunks until we find 'fmt ' and 'data'\n while ( true )\n {\n if ( !await HaveEnoughDataAsync(headerChunks, 8, stream, toReturn, cancellationToken) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n var chunkType = headerChunks.ReadUInt32LittleEndian();\n var chunkSize = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkType == 0x20746D66 /*'fmt '*/ )\n {\n if ( chunkSize < 16 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n if ( !await HaveEnoughDataAsync(headerChunks, chunkSize, stream, toReturn, cancellationToken) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n var formatTag = headerChunks.ReadUInt16LittleEndian();\n var channels = headerChunks.ReadUInt16LittleEndian();\n var sampleRate = headerChunks.ReadUInt32LittleEndian();\n var avgBytesPerSec = headerChunks.ReadUInt32LittleEndian();\n var blockAlign = headerChunks.ReadUInt16LittleEndian();\n var bitsPerSample = headerChunks.ReadUInt16LittleEndian();\n\n if ( formatTag != 1 && formatTag != 0xFFFE ) // PCM or WAVE_FORMAT_EXTENSIBLE\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n\n ushort? cbSize = null;\n ushort? validBitsPerSample = null;\n uint? channelMask = null;\n if ( formatTag == 0xFFFE )\n {\n // WAVE_FORMAT_EXTENSIBLE\n if ( chunkSize < 40 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n cbSize = headerChunks.ReadUInt16LittleEndian();\n validBitsPerSample = headerChunks.ReadUInt16LittleEndian();\n channelMask = headerChunks.ReadUInt32LittleEndian();\n var subFormatChunk = headerChunks.GetChunk(16);\n\n if ( !subFormatChunk.Span.SequenceEqual(ExpectedSubFormatForPcm) )\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n }\n\n if ( channels == 0 )\n {\n return HeaderParseResult.NotSupported(\"Cannot read wave file with 0 channels.\");\n }\n\n // Skip any remaining bytes in fmt chunk\n var remainingBytes = chunkSize - (formatTag == 1 ? 16u : 40u);\n if ( !SkipData(headerChunks, remainingBytes, stream) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n header = new AudioSourceHeader { Channels = channels, SampleRate = sampleRate, BitsPerSample = bitsPerSample };\n }\n else if ( chunkType == 0x61746164 /*'data'*/ )\n {\n if ( header == null )\n {\n return HeaderParseResult.Corrupt(\"Data chunk found before format chunk.\");\n }\n\n // Found 'data' chunk\n // We can start processing samples after this point\n var dataOffset = (int)(headerChunks.Position - headerChunks.AbsolutePositionOfCurrentChunk);\n\n return HeaderParseResult.Success(header, dataOffset, chunkSize);\n }\n else\n {\n if ( !SkipData(headerChunks, chunkSize, stream) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n }\n }\n }\n catch\n {\n foreach ( var rented in toReturn )\n {\n ArrayPool.Shared.Return(rented, ArrayPoolConfig.ClearOnReturn);\n }\n }\n\n return HeaderParseResult.WaitingForMoreData;\n }\n\n public static HeaderParseResult ParseHeader(MergedMemoryChunks headerChunks)\n {\n if ( headerChunks.Length < 12 )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n AudioSourceHeader? header = null;\n\n var chunkID = headerChunks.ReadUInt32LittleEndian();\n // Skip the file size\n headerChunks.TrySkip(4);\n var riffType = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkID != 0x46464952 /*'RIFF'*/ || riffType != 0x45564157 /*'WAVE'*/ )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file header.\");\n }\n\n // Read chunks until we find 'fmt ' and 'data'\n while ( headerChunks.Position + 8 <= headerChunks.Length )\n {\n var chunkType = headerChunks.ReadUInt32LittleEndian();\n var chunkSize = headerChunks.ReadUInt32LittleEndian();\n\n if ( chunkType == 0x20746D66 /*'fmt '*/ )\n {\n if ( chunkSize < 16 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n if ( headerChunks.Position + chunkSize > headerChunks.Length )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n var formatTag = headerChunks.ReadUInt16LittleEndian();\n var channels = headerChunks.ReadUInt16LittleEndian();\n var sampleRate = headerChunks.ReadUInt32LittleEndian();\n headerChunks.TrySkip(6); // avgBytesPerSec + blockAlign\n\n var bitsPerSample = headerChunks.ReadUInt16LittleEndian();\n\n if ( formatTag != 1 && formatTag != 0xFFFE ) // PCM or WAVE_FORMAT_EXTENSIBLE\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n\n if ( formatTag == 0xFFFE )\n {\n // WAVE_FORMAT_EXTENSIBLE\n if ( chunkSize < 40 )\n {\n return HeaderParseResult.Corrupt(\"Invalid wave file format chunk.\");\n }\n\n headerChunks.TrySkip(8); // cbSize + validBitsPerSample + channelMask\n var subFormatChunk = headerChunks.GetChunk(16);\n\n if ( !subFormatChunk.Span.SequenceEqual(ExpectedSubFormatForPcm) )\n {\n return HeaderParseResult.NotSupported(\"Unsupported wave file format.\");\n }\n }\n\n if ( channels == 0 )\n {\n return HeaderParseResult.NotSupported(\"Cannot read wave file with 0 channels.\");\n }\n\n // Skip any remaining bytes in fmt chunk\n if ( !headerChunks.TrySkip(chunkSize - (formatTag == 1 ? 16u : 40u)) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n\n header = new AudioSourceHeader { Channels = channels, SampleRate = sampleRate, BitsPerSample = bitsPerSample };\n }\n else if ( chunkType == 0x61746164 /*'data'*/ )\n {\n if ( header == null )\n {\n return HeaderParseResult.Corrupt(\"Data chunk found before format chunk.\");\n }\n\n // Found 'data' chunk\n // We can start processing samples after this point\n var dataOffset = (int)(headerChunks.Position - headerChunks.AbsolutePositionOfCurrentChunk);\n\n return HeaderParseResult.Success(header, dataOffset, chunkSize);\n }\n else\n {\n if ( !headerChunks.TrySkip(chunkSize) )\n {\n return HeaderParseResult.WaitingForMoreData;\n }\n }\n }\n\n return HeaderParseResult.WaitingForMoreData;\n }\n\n /// \n /// Ensures that the given number of bytes can be read from the memory chunks.\n /// \n /// \n private static async Task HaveEnoughDataAsync(MergedMemoryChunks headerChunks, uint requiredBytes, Stream stream, List returnItems, CancellationToken cancellationToken)\n {\n var extraBytesNeeded = (int)(requiredBytes - (headerChunks.Length - headerChunks.Position));\n if ( extraBytesNeeded <= 0 )\n {\n return true;\n }\n\n // We try to read the next chunk from the stream\n var nextChunk = ArrayPool.Shared.Rent(extraBytesNeeded);\n returnItems.Add(nextChunk);\n var chunkMemory = nextChunk.AsMemory(0, extraBytesNeeded);\n\n var actualReadNext = await stream.ReadAsync(chunkMemory, cancellationToken);\n\n if ( actualReadNext != extraBytesNeeded )\n {\n return false;\n }\n\n headerChunks.AddChunk(chunkMemory);\n\n return true;\n }\n\n private static bool SkipData(MergedMemoryChunks headerChunks, uint skipBytes, Stream stream)\n {\n var extraBytesNeededToSkip = (int)(skipBytes - (headerChunks.Length - headerChunks.Position));\n if ( extraBytesNeededToSkip <= 0 )\n {\n return headerChunks.TrySkip(skipBytes);\n }\n\n // We skip all the bytes we have in the current chunks + the remaining bytes from the stream directly\n if ( !headerChunks.TrySkip((uint)(headerChunks.Length - headerChunks.Position)) )\n {\n return false;\n }\n\n var skipped = stream.Seek(skipBytes, SeekOrigin.Current);\n\n return skipped == extraBytesNeededToSkip;\n }\n\n internal class HeaderParseResult(bool isSuccess, bool isIncomplete, bool isCorrupt, bool isNotSupported, int dataOffset, long dataChunkSize, AudioSourceHeader? header, string? errorMessage)\n {\n public static HeaderParseResult WaitingForMoreData { get; } = new(false, true, false, false, 0, 0, null, \"Not enough data available.\");\n\n public bool IsSuccess { get; } = isSuccess;\n\n public bool IsIncomplete { get; } = isIncomplete;\n\n public bool IsCorrupt { get; } = isCorrupt;\n\n public bool IsNotSupported { get; } = isNotSupported;\n\n public int DataOffset { get; } = dataOffset;\n\n public long DataChunkSize { get; } = dataChunkSize;\n\n public AudioSourceHeader? Header { get; } = header;\n\n public string? ErrorMessage { get; } = errorMessage;\n\n public static HeaderParseResult Corrupt(string message) { return new HeaderParseResult(true, false, true, true, 0, 0, null, message); }\n\n public static HeaderParseResult NotSupported(string message) { return new HeaderParseResult(false, false, false, true, 0, 0, null, message); }\n\n public static HeaderParseResult Success(AudioSourceHeader header, int dataOffset, long dataChunkSize) { return new HeaderParseResult(true, false, false, false, dataOffset, dataChunkSize, header, null); }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnx.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnx : IF0Predictor\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n private readonly float[] _inputBatchBuffer;\n\n // Preallocated buffers for zero-allocation processing\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Additional preallocated buffers for Viterbi decoding\n private readonly float[,] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[,] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[,] _transitionMatrix;\n\n private readonly float[,] _transOutBuffer;\n\n private readonly float[,] _valueBuffer;\n\n private readonly float[] _windowBuffer;\n\n public CrepeOnnx(string modelPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Preallocate buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _windowBuffer = new float[WINDOW_SIZE];\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Preallocate Viterbi algorithm buffers\n _logProbBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE, PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = CreateTransitionMatrix();\n _transOutBuffer = new float[PITCH_BINS, PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n\n // Initialize _logPInitBuffer with equal probabilities\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _logPInitBuffer[i] = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n }\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n var wavSpan = wav.Span;\n var outputSpan = f0Output.Span;\n\n if ( length > outputSpan.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Preallocate periodicity data buffer\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = new Span(pdBuffer, 0, length);\n\n // Process the audio to extract F0\n Crepe(wavSpan, outputSpan.Slice(0, length), pdSpan);\n\n // Apply post-processing\n for ( var i = 0; i < length; i++ )\n {\n if ( pdSpan[i] < 0.1 )\n {\n outputSpan[i] = 0;\n }\n }\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var total_frames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < total_frames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, total_frames - b);\n\n // Fill the batch input buffer\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame\n Normalize(frame);\n }\n\n private void Normalize(Span input)\n {\n // Mean center and scale\n float sum = 0;\n for ( var j = 0; j < input.Length; j++ )\n {\n sum += input[j];\n }\n\n var mean = sum / input.Length;\n float stdValue = 0;\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] - mean;\n stdValue += input[j] * input[j];\n }\n\n stdValue = stdValue / input.Length;\n stdValue = (float)Math.Sqrt(stdValue);\n\n if ( stdValue < 1e-10 )\n {\n stdValue = 1e-10f;\n }\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] / stdValue;\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor\n for ( var i = 0; i < batchSize; i++ )\n {\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[i * WINDOW_SIZE + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Remove frequencies outside of allowable range\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n for ( var t = 0; t < outputSize; t++ )\n {\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n if ( i < minidx || i >= maxidx )\n {\n probabilities[t * PITCH_BINS + i] = float.NegativeInfinity;\n }\n }\n }\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0, pd, outputSize, offset);\n }\n\n private void DecodeViterbi(float[] probabilities, Span f0, Span pd, int nSteps, int offset)\n {\n // Transfer probabilities to log_prob buffer and apply softmax\n for ( var i = 0; i < nSteps * PITCH_BINS; i++ )\n {\n _logProbBuffer[i / PITCH_BINS, i % PITCH_BINS] = probabilities[i];\n }\n\n Softmax(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n for ( var y = 0; y < nSteps; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _logProbBuffer[y, x] = (float)Math.Log(_logProbBuffer[y, x] + float.Epsilon);\n }\n }\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[0, i] = _logProbBuffer[0, i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm\n for ( var t = 1; t < nSteps; t++ )\n {\n // Calculate transition outputs\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _transOutBuffer[y, x] = _valueBuffer[t - 1, x] + _transitionMatrix[x, y]; // Transposed matrix\n }\n }\n\n for ( var j = 0; j < PITCH_BINS; j++ )\n {\n // Find argmax\n var maxI = 0;\n var maxProb = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb < _transOutBuffer[j, k] )\n {\n maxProb = _transOutBuffer[j, k];\n maxI = k;\n }\n }\n\n _ptrBuffer[t, j] = maxI;\n _valueBuffer[t, j] = _logProbBuffer[t, j] + _transOutBuffer[j, _ptrBuffer[t, j]];\n }\n }\n\n // Find the most likely final state\n var maxI2 = 0;\n var maxProb2 = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb2 < _valueBuffer[nSteps - 1, k] )\n {\n maxProb2 = _valueBuffer[nSteps - 1, k];\n maxI2 = k;\n }\n }\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI2;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[t + 1, _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values\n for ( var t = 0; t < nSteps; t++ )\n {\n var bins = _stateBuffer[t];\n var periodicity = Periodicity(probabilities, t, bins);\n var frequency = ConvertToFrequency(bins);\n\n if ( offset + t < f0.Length )\n {\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n }\n\n private void Softmax(float[,] data, int nSteps)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n sum += (float)Math.Exp(data[t, i]);\n }\n\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[t, i] = (float)Math.Exp(data[t, i]) / sum;\n }\n }\n }\n\n private float[,] CreateTransitionMatrix()\n {\n var transition = new float[PITCH_BINS, PITCH_BINS];\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n var v = 12 - Math.Abs(x - y);\n if ( v < 0 )\n {\n v = 0;\n }\n\n transition[y, x] = v;\n sum += v;\n }\n\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n transition[y, x] = transition[y, x] / sum;\n\n // Pre-apply log to the transition matrix for efficiency\n transition[y, x] = (float)Math.Log(transition[y, x] + float.Epsilon);\n }\n }\n\n return transition;\n }\n\n private float Periodicity(float[] probabilities, int t, int bins) { return probabilities[t * PITCH_BINS + bins]; }\n\n private float ConvertToFrequency(int bin)\n {\n float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n var frequency = 10 * (float)Math.Pow(2, cents / 1200);\n\n return frequency;\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n // Fill the window buffer\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n _medianBuffer[j] = original[k];\n }\n\n // Sort the window\n Array.Sort(_medianBuffer, 0, windowSize);\n\n // Set the median value\n data[i] = _medianBuffer[windowSize / 2];\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n float sum = 0;\n\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n sum += original[k];\n }\n\n // Set the mean value\n data[i] = sum / windowSize;\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Vision/VisualQAService.cs", "using System.Text;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.SemanticKernel.Connectors.OpenAI;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.LLM;\n\nnamespace PersonaEngine.Lib.Vision;\n\npublic class VisualQAService : IVisualQAService\n{\n private readonly WindowCaptureService _captureService;\n\n private readonly IVisualChatEngine _chatEngine;\n\n private readonly VisionConfig _config;\n\n private readonly SemaphoreSlim _fileChangeSemaphore = new(1, 1);\n\n private readonly CancellationTokenSource _internalCts = new();\n\n private readonly ILogger _logger;\n\n private DateTimeOffset _lastProcessedTimestamp = DateTimeOffset.MinValue;\n\n public VisualQAService(\n IOptions config,\n WindowCaptureService captureService,\n IVisualChatEngine chatEngine,\n ILogger logger)\n {\n _config = config.Value.Vision;\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n _captureService = captureService;\n _chatEngine = chatEngine;\n\n _captureService.OnCaptureFrame += OnCaptureFrame;\n }\n\n public string? ScreenCaption { get; private set; }\n\n public Task StartAsync(CancellationToken cancellationToken = default)\n {\n if ( !_config.Enabled )\n {\n return Task.CompletedTask;\n }\n\n CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _internalCts.Token);\n _logger.LogDebug(\"Starting Visual QA Service\");\n _captureService.StartAsync(cancellationToken);\n\n return Task.CompletedTask;\n }\n\n public async Task StopAsync()\n {\n _logger.LogDebug(\"Stopping Visual QA Service\");\n await _internalCts.CancelAsync();\n await _captureService.StopAsync();\n }\n\n public async ValueTask DisposeAsync()\n {\n await StopAsync();\n _internalCts.Dispose();\n _fileChangeSemaphore.Dispose();\n _captureService.OnCaptureFrame -= OnCaptureFrame;\n }\n\n private async void OnCaptureFrame(object? sender, CaptureFrameEventArgs e)\n {\n await _fileChangeSemaphore.WaitAsync(_internalCts.Token);\n\n try\n {\n var currentTimestamp = DateTimeOffset.Now;\n if ( (currentTimestamp - _lastProcessedTimestamp).TotalMilliseconds < 100 )\n {\n return;\n }\n\n _lastProcessedTimestamp = currentTimestamp;\n\n var result = await ProcessVisualQAFrame(e.FrameData);\n ScreenCaption = result;\n }\n finally\n {\n _fileChangeSemaphore.Release();\n }\n }\n\n private async Task ProcessVisualQAFrame(ReadOnlyMemory imageData)\n {\n try\n {\n var question = \"Describe the main content of this screenshot objectivly in great detail.\";\n var chatMessage = new VisualChatMessage(question, imageData);\n var caption = new StringBuilder();\n var settings = new OpenAIPromptExecutionSettings { FrequencyPenalty = 1.1, Temperature = 0.1, PresencePenalty = 1.1, MaxTokens = 256 };\n await foreach ( var response in _chatEngine.GetStreamingChatResponseAsync(chatMessage, settings, _internalCts.Token) )\n {\n caption.Append(response);\n }\n\n return caption.ToString();\n }\n catch (Exception e)\n {\n _logger.LogError(e, \"Failed to caption screen frame\");\n\n return null;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismClippingManager.cs", "using System.Numerics;\n\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\nusing PersonaEngine.Lib.Live2D.Framework.Type;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic class CubismClippingManager\n{\n /// \n /// 実験時に1チャンネルの場合は1、RGBだけの場合は3、アルファも含める場合は4\n /// \n public const int ColorChannelCount = 4;\n\n /// \n /// 通常のフレームバッファ1枚あたりのマスク最大数\n /// \n public const int ClippingMaskMaxCountOnDefault = 36;\n\n /// \n /// フレームバッファが2枚以上ある場合のフレームバッファ1枚あたりのマスク最大数\n /// \n public const int ClippingMaskMaxCountOnMultiRenderTexture = 32;\n\n private readonly RenderType _renderType;\n\n protected List ChannelColors = [];\n\n /// \n /// マスクのクリアフラグの配列\n /// \n protected List ClearedMaskBufferFlags = [];\n\n /// \n /// マスク用クリッピングコンテキストのリスト\n /// \n protected List ClippingContextListForMask = [];\n\n /// \n /// オフスクリーンサーフェイスのアドレス\n /// \n protected CubismOffscreenSurface_OpenGLES2 CurrentMaskBuffer;\n\n /// \n /// マスク配置計算用の矩形\n /// \n protected RectF TmpBoundsOnModel = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrix = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrixForDraw = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrixForMask = new();\n\n public CubismClippingManager(RenderType render)\n {\n _renderType = render;\n ClippingMaskBufferSize = new Vector2(256, 256);\n\n ChannelColors.Add(new CubismTextureColor(1.0f, 0f, 0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 1.0f, 0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 0f, 1.0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 0f, 0f, 1.0f));\n }\n\n /// \n /// 描画用クリッピングコンテキストのリスト\n /// \n public List ClippingContextListForDraw { get; init; } = [];\n\n /// \n /// クリッピングマスクのバッファサイズ(初期値:256)\n /// \n public Vector2 ClippingMaskBufferSize { get; private set; }\n\n /// \n /// 生成するレンダーテクスチャの枚数\n /// \n public int RenderTextureCount { get; private set; }\n\n public void Close()\n {\n ClippingContextListForDraw.Clear();\n ClippingContextListForMask.Clear();\n ChannelColors.Clear();\n ClearedMaskBufferFlags.Clear();\n }\n\n /// \n /// マネージャの初期化処理\n /// クリッピングマスクを使う描画オブジェクトの登録を行う\n /// \n /// モデルのインスタンス\n /// バッファの生成数\n public unsafe void Initialize(CubismModel model, int maskBufferCount)\n {\n RenderTextureCount = maskBufferCount;\n\n // レンダーテクスチャのクリアフラグの設定\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n\n //クリッピングマスクを使う描画オブジェクトを全て登録する\n //クリッピングマスクは、通常数個程度に限定して使うものとする\n for ( var i = 0; i < model.GetDrawableCount(); i++ )\n {\n if ( model.GetDrawableMaskCounts()[i] <= 0 )\n {\n //クリッピングマスクが使用されていないアートメッシュ(多くの場合使用しない)\n ClippingContextListForDraw.Add(null);\n\n continue;\n }\n\n // 既にあるClipContextと同じかチェックする\n var cc = FindSameClip(model.GetDrawableMasks()[i], model.GetDrawableMaskCounts()[i]);\n if ( cc == null )\n {\n // 同一のマスクが存在していない場合は生成する\n if ( _renderType == RenderType.OpenGL )\n {\n cc = new CubismClippingContext_OpenGLES2(this, model, model.GetDrawableMasks()[i], model.GetDrawableMaskCounts()[i]);\n }\n else\n {\n throw new Exception(\"Only OpenGL\");\n }\n\n ClippingContextListForMask.Add(cc);\n }\n\n cc.AddClippedDrawable(i);\n\n ClippingContextListForDraw.Add(cc);\n }\n }\n\n /// \n /// 既にマスクを作っているかを確認。\n /// 作っているようであれば該当するクリッピングマスクのインスタンスを返す。\n /// 作っていなければNULLを返す\n /// \n /// 描画オブジェクトをマスクする描画オブジェクトのリスト\n /// 描画オブジェクトをマスクする描画オブジェクトの数\n /// 該当するクリッピングマスクが存在すればインスタンスを返し、なければNULLを返す。\n private unsafe CubismClippingContext? FindSameClip(int* drawableMasks, int drawableMaskCounts)\n {\n // 作成済みClippingContextと一致するか確認\n for ( var i = 0; i < ClippingContextListForMask.Count; i++ )\n {\n var cc = ClippingContextListForMask[i];\n var count = cc.ClippingIdCount;\n if ( count != drawableMaskCounts )\n {\n continue; //個数が違う場合は別物\n }\n\n var samecount = 0;\n\n // 同じIDを持つか確認。配列の数が同じなので、一致した個数が同じなら同じ物を持つとする。\n for ( var j = 0; j < count; j++ )\n {\n var clipId = cc.ClippingIdList[j];\n for ( var k = 0; k < count; k++ )\n {\n if ( drawableMasks[k] == clipId )\n {\n samecount++;\n\n break;\n }\n }\n }\n\n if ( samecount == count )\n {\n return cc;\n }\n }\n\n return null; //見つからなかった\n }\n\n /// \n /// 高精細マスク処理用の行列を計算する\n /// \n /// モデルのインスタンス\n /// 処理が右手系であるか\n public void SetupMatrixForHighPrecision(CubismModel model, bool isRightHanded)\n {\n // 全てのクリッピングを用意する\n // 同じクリップ(複数の場合はまとめて1つのクリップ)を使う場合は1度だけ設定する\n var usingClipCount = 0;\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // 1つのクリッピングマスクに関して\n var cc = ClippingContextListForMask[clipIndex];\n\n // このクリップを利用する描画オブジェクト群全体を囲む矩形を計算\n CalcClippedDrawTotalBounds(model, cc);\n\n if ( cc.IsUsing )\n {\n usingClipCount++; //使用中としてカウント\n }\n }\n\n if ( usingClipCount <= 0 )\n {\n return;\n }\n\n // マスク行列作成処理\n SetupLayoutBounds(0);\n\n // サイズがレンダーテクスチャの枚数と合わない場合は合わせる\n if ( ClearedMaskBufferFlags.Count != RenderTextureCount )\n {\n ClearedMaskBufferFlags.Clear();\n\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n }\n else\n {\n // マスクのクリアフラグを毎フレーム開始時に初期化\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags[i] = false;\n }\n }\n\n // 実際にマスクを生成する\n // 全てのマスクをどの様にレイアウトして描くかを決定し、ClipContext , ClippedDrawContext に記憶する\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // --- 実際に1つのマスクを描く ---\n var clipContext = ClippingContextListForMask[clipIndex];\n var allClippedDrawRect = clipContext.AllClippedDrawRect; //このマスクを使う、全ての描画オブジェクトの論理座標上の囲み矩形\n var layoutBoundsOnTex01 = clipContext.LayoutBounds; //この中にマスクを収める\n var MARGIN = 0.05f;\n float scaleX;\n float scaleY;\n var ppu = model.GetPixelsPerUnit();\n var maskPixelWidth = clipContext.Manager.ClippingMaskBufferSize.X;\n var maskPixelHeight = clipContext.Manager.ClippingMaskBufferSize.Y;\n var physicalMaskWidth = layoutBoundsOnTex01.Width * maskPixelWidth;\n var physicalMaskHeight = layoutBoundsOnTex01.Height * maskPixelHeight;\n\n TmpBoundsOnModel.SetRect(allClippedDrawRect);\n if ( TmpBoundsOnModel.Width * ppu > physicalMaskWidth )\n {\n TmpBoundsOnModel.Expand(allClippedDrawRect.Width * MARGIN, 0.0f);\n scaleX = layoutBoundsOnTex01.Width / TmpBoundsOnModel.Width;\n }\n else\n {\n scaleX = ppu / physicalMaskWidth;\n }\n\n if ( TmpBoundsOnModel.Height * ppu > physicalMaskHeight )\n {\n TmpBoundsOnModel.Expand(0.0f, allClippedDrawRect.Height * MARGIN);\n scaleY = layoutBoundsOnTex01.Height / TmpBoundsOnModel.Height;\n }\n else\n {\n scaleY = ppu / physicalMaskHeight;\n }\n\n // マスク生成時に使う行列を求める\n CreateMatrixForMask(isRightHanded, layoutBoundsOnTex01, scaleX, scaleY);\n\n clipContext.MatrixForMask.SetMatrix(TmpMatrixForMask.Tr);\n clipContext.MatrixForDraw.SetMatrix(TmpMatrixForDraw.Tr);\n }\n }\n\n /// \n /// マスク作成・描画用の行列を作成する。\n /// \n /// 座標を右手系として扱うかを指定\n /// マスクを収める領域\n /// 描画オブジェクトの伸縮率\n /// 描画オブジェクトの伸縮率\n protected void CreateMatrixForMask(bool isRightHanded, RectF layoutBoundsOnTex01, float scaleX, float scaleY)\n {\n TmpMatrix.LoadIdentity();\n {\n // Layout0..1 を -1..1に変換\n TmpMatrix.TranslateRelative(-1.0f, -1.0f);\n TmpMatrix.ScaleRelative(2.0f, 2.0f);\n }\n\n {\n // view to Layout0..1\n TmpMatrix.TranslateRelative(layoutBoundsOnTex01.X, layoutBoundsOnTex01.Y); //new = [translate]\n TmpMatrix.ScaleRelative(scaleX, scaleY); //new = [translate][scale]\n TmpMatrix.TranslateRelative(-TmpBoundsOnModel.X, -TmpBoundsOnModel.Y); //new = [translate][scale][translate]\n }\n\n // tmpMatrixForMask が計算結果\n TmpMatrixForMask.SetMatrix(TmpMatrix.Tr);\n\n TmpMatrix.LoadIdentity();\n {\n TmpMatrix.TranslateRelative(layoutBoundsOnTex01.X, layoutBoundsOnTex01.Y * (isRightHanded ? -1.0f : 1.0f)); //new = [translate]\n TmpMatrix.ScaleRelative(scaleX, scaleY * (isRightHanded ? -1.0f : 1.0f)); //new = [translate][scale]\n TmpMatrix.TranslateRelative(-TmpBoundsOnModel.X, -TmpBoundsOnModel.Y); //new = [translate][scale][translate]\n }\n\n TmpMatrixForDraw.SetMatrix(TmpMatrix.Tr);\n }\n\n /// \n /// クリッピングコンテキストを配置するレイアウト。\n /// ひとつのレンダーテクスチャを極力いっぱいに使ってマスクをレイアウトする。\n /// マスクグループの数が4以下ならRGBA各チャンネルに1つずつマスクを配置し、5以上6以下ならRGBAを2,2,1,1と配置する。\n /// \n /// 配置するクリッピングコンテキストの数\n protected void SetupLayoutBounds(int usingClipCount)\n {\n var useClippingMaskMaxCount = RenderTextureCount <= 1\n ? ClippingMaskMaxCountOnDefault\n : ClippingMaskMaxCountOnMultiRenderTexture * RenderTextureCount;\n\n if ( usingClipCount <= 0 || usingClipCount > useClippingMaskMaxCount )\n {\n if ( usingClipCount > useClippingMaskMaxCount )\n {\n // マスクの制限数の警告を出す\n var count = usingClipCount - useClippingMaskMaxCount;\n CubismLog.Error(\"not supported mask count : %d\\n[Details] render texture count: %d\\n, mask count : %d\"\n , count, RenderTextureCount, usingClipCount);\n }\n\n // この場合は一つのマスクターゲットを毎回クリアして使用する\n for ( var index = 0; index < ClippingContextListForMask.Count; index++ )\n {\n var cc = ClippingContextListForMask[index];\n cc.LayoutChannelIndex = 0; // どうせ毎回消すので固定で良い\n cc.LayoutBounds.X = 0.0f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 1.0f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = 0;\n }\n\n return;\n }\n\n // レンダーテクスチャが1枚なら9分割する(最大36枚)\n var layoutCountMaxValue = RenderTextureCount <= 1 ? 9 : 8;\n\n // ひとつのRenderTextureを極力いっぱいに使ってマスクをレイアウトする\n // マスクグループの数が4以下ならRGBA各チャンネルに1つずつマスクを配置し、5以上6以下ならRGBAを2,2,1,1と配置する\n var countPerSheetDiv = (usingClipCount + RenderTextureCount - 1) / RenderTextureCount; // レンダーテクスチャ1枚あたり何枚割り当てるか(切り上げ)\n var reduceLayoutTextureCount = usingClipCount % RenderTextureCount; // レイアウトの数を1枚減らすレンダーテクスチャの数(この数だけのレンダーテクスチャが対象)\n\n // RGBAを順番に使っていく\n var divCount = countPerSheetDiv / ColorChannelCount; //1チャンネルに配置する基本のマスク個数\n var modCount = countPerSheetDiv % ColorChannelCount; //余り、この番号のチャンネルまでに1つずつ配分する\n\n // RGBAそれぞれのチャンネルを用意していく(0:R , 1:G , 2:B, 3:A, )\n var curClipIndex = 0; //順番に設定していく\n\n for ( var renderTextureIndex = 0; renderTextureIndex < RenderTextureCount; renderTextureIndex++ )\n {\n for ( var channelIndex = 0; channelIndex < ColorChannelCount; channelIndex++ )\n {\n // このチャンネルにレイアウトする数\n // NOTE: レイアウト数 = 1チャンネルに配置する基本のマスク + 余りのマスクを置くチャンネルなら1つ追加\n var layoutCount = divCount + (channelIndex < modCount ? 1 : 0);\n\n // レイアウトの数を1枚減らす場合にそれを行うチャンネルを決定\n // divが0の時は正常なインデックスの範囲内になるように調整\n var checkChannelIndex = modCount + (divCount < 1 ? -1 : 0);\n\n // 今回が対象のチャンネルかつ、レイアウトの数を1枚減らすレンダーテクスチャが存在する場合\n if ( channelIndex == checkChannelIndex && reduceLayoutTextureCount > 0 )\n {\n // 現在のレンダーテクスチャが、対象のレンダーテクスチャであればレイアウトの数を1枚減らす\n layoutCount -= !(renderTextureIndex < reduceLayoutTextureCount) ? 1 : 0;\n }\n\n // 分割方法を決定する\n if ( layoutCount == 0 )\n {\n // 何もしない\n }\n else if ( layoutCount == 1 )\n {\n //全てをそのまま使う\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n cc.LayoutBounds.X = 0.0f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 1.0f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = renderTextureIndex;\n }\n else if ( layoutCount == 2 )\n {\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 2;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos * 0.5f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 0.5f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = renderTextureIndex;\n //UVを2つに分解して使う\n }\n }\n else if ( layoutCount <= 4 )\n {\n //4分割して使う\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 2;\n var ypos = i / 2;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos * 0.5f;\n cc.LayoutBounds.Y = ypos * 0.5f;\n cc.LayoutBounds.Width = 0.5f;\n cc.LayoutBounds.Height = 0.5f;\n cc.BufferIndex = renderTextureIndex;\n }\n }\n else if ( layoutCount <= layoutCountMaxValue )\n {\n //9分割して使う\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 3;\n var ypos = i / 3;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos / 3.0f;\n cc.LayoutBounds.Y = ypos / 3.0f;\n cc.LayoutBounds.Width = 1.0f / 3.0f;\n cc.LayoutBounds.Height = 1.0f / 3.0f;\n cc.BufferIndex = renderTextureIndex;\n }\n }\n // マスクの制限枚数を超えた場合の処理\n else\n {\n var count = usingClipCount - useClippingMaskMaxCount;\n\n // 開発モードの場合は停止させる\n throw new Exception($\"not supported mask count : {count}\\n[Details] render texture count: {RenderTextureCount}\\n, mask count : {usingClipCount}\");\n }\n }\n }\n }\n\n /// \n /// マスクされる描画オブジェクト群全体を囲む矩形(モデル座標系)を計算する\n /// \n /// モデルのインスタンス\n /// クリッピングマスクのコンテキスト\n protected unsafe void CalcClippedDrawTotalBounds(CubismModel model, CubismClippingContext clippingContext)\n {\n // 被クリッピングマスク(マスクされる描画オブジェクト)の全体の矩形\n float clippedDrawTotalMinX = float.MaxValue,\n clippedDrawTotalMinY = float.MaxValue;\n\n float clippedDrawTotalMaxX = float.MinValue,\n clippedDrawTotalMaxY = float.MinValue;\n\n // このマスクが実際に必要か判定する\n // このクリッピングを利用する「描画オブジェクト」がひとつでも使用可能であればマスクを生成する必要がある\n\n var clippedDrawCount = clippingContext.ClippedDrawableIndexList.Count;\n for ( var clippedDrawableIndex = 0; clippedDrawableIndex < clippedDrawCount; clippedDrawableIndex++ )\n {\n // マスクを使用する描画オブジェクトの描画される矩形を求める\n var drawableIndex = clippingContext.ClippedDrawableIndexList[clippedDrawableIndex];\n\n var drawableVertexCount = model.GetDrawableVertexCount(drawableIndex);\n var drawableVertexes = model.GetDrawableVertices(drawableIndex);\n\n float minX = float.MaxValue,\n minY = float.MaxValue;\n\n float maxX = float.MinValue,\n maxY = float.MinValue;\n\n var loop = drawableVertexCount * CubismFramework.VertexStep;\n for ( var pi = CubismFramework.VertexOffset; pi < loop; pi += CubismFramework.VertexStep )\n {\n var x = drawableVertexes[pi];\n var y = drawableVertexes[pi + 1];\n if ( x < minX )\n {\n minX = x;\n }\n\n if ( x > maxX )\n {\n maxX = x;\n }\n\n if ( y < minY )\n {\n minY = y;\n }\n\n if ( y > maxY )\n {\n maxY = y;\n }\n }\n\n //\n if ( minX == float.MaxValue )\n {\n continue; //有効な点がひとつも取れなかったのでスキップする\n }\n\n // 全体の矩形に反映\n if ( minX < clippedDrawTotalMinX )\n {\n clippedDrawTotalMinX = minX;\n }\n\n if ( minY < clippedDrawTotalMinY )\n {\n clippedDrawTotalMinY = minY;\n }\n\n if ( maxX > clippedDrawTotalMaxX )\n {\n clippedDrawTotalMaxX = maxX;\n }\n\n if ( maxY > clippedDrawTotalMaxY )\n {\n clippedDrawTotalMaxY = maxY;\n }\n }\n\n if ( clippedDrawTotalMinX == float.MaxValue )\n {\n clippingContext.AllClippedDrawRect.X = 0.0f;\n clippingContext.AllClippedDrawRect.Y = 0.0f;\n clippingContext.AllClippedDrawRect.Width = 0.0f;\n clippingContext.AllClippedDrawRect.Height = 0.0f;\n clippingContext.IsUsing = false;\n }\n else\n {\n clippingContext.IsUsing = true;\n var w = clippedDrawTotalMaxX - clippedDrawTotalMinX;\n var h = clippedDrawTotalMaxY - clippedDrawTotalMinY;\n clippingContext.AllClippedDrawRect.X = clippedDrawTotalMinX;\n clippingContext.AllClippedDrawRect.Y = clippedDrawTotalMinY;\n clippingContext.AllClippedDrawRect.Width = w;\n clippingContext.AllClippedDrawRect.Height = h;\n }\n }\n\n /// \n /// カラーチャンネル(RGBA)のフラグを取得する\n /// \n /// カラーチャンネル(RGBA)の番号(0:R , 1:G , 2:B, 3:A)\n /// \n public CubismTextureColor GetChannelFlagAsColor(int channelNo) { return ChannelColors[channelNo]; }\n\n /// \n /// クリッピングマスクバッファのサイズを設定する\n /// \n /// クリッピングマスクバッファのサイズ\n /// クリッピングマスクバッファのサイズ\n public void SetClippingMaskBufferSize(float width, float height) { ClippingMaskBufferSize = new Vector2(width, height); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnxSimd.cs", "using System.Buffers;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\nusing System.Runtime.Intrinsics.X86;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnxSimd : IF0Predictor, IDisposable\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n // Preallocated buffers\n private readonly float[] _inputBatchBuffer;\n\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Flattened arrays for better cache locality and SIMD operations\n private readonly float[] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[] _tempBuffer; // Used for temporary calculations\n\n private readonly float[] _transitionMatrix;\n\n private readonly float[] _transOutBuffer;\n\n private readonly float[] _valueBuffer;\n\n // SIMD vector size based on hardware\n private readonly int _vectorSize;\n\n public CrepeOnnxSimd(string modelPath)\n {\n // Determine vector size based on hardware capabilities\n _vectorSize = Vector.Count;\n\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n // Use hardware specific optimizations if available\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Initialize preallocated buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Initialize flattened buffers for Viterbi algorithm\n _logProbBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE * PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = new float[PITCH_BINS * PITCH_BINS];\n _transOutBuffer = new float[PITCH_BINS * PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n _tempBuffer = new float[Math.Max(BATCH_SIZE, PITCH_BINS) * _vectorSize];\n\n // Initialize logPInitBuffer with equal probabilities\n var logInitProb = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n FillArray(_logPInitBuffer, logInitProb);\n\n // Initialize transition matrix\n InitializeTransitionMatrix(_transitionMatrix);\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n if ( length > f0Output.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Rent buffer from pool for periodicity data\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = pdBuffer.AsSpan(0, length);\n var wavSpan = wav.Span;\n var f0Span = f0Output.Span.Slice(0, length);\n\n // Process audio to extract F0\n Crepe(wavSpan, f0Span, pdSpan);\n\n // Apply post-processing with SIMD\n ApplyPeriodicityThreshold(f0Span, pdSpan, length);\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var totalFrames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < totalFrames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, totalFrames - b);\n\n // Fill the batch input buffer with SIMD\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing with SIMD\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection padding\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection padding\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame using SIMD\n NormalizeAvx(frame);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeSimd(Span input)\n {\n // 1. Calculate mean using SIMD\n float sum = 0;\n var vectorCount = input.Length / _vectorSize;\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var v = new Vector(input.Slice(i * _vectorSize, _vectorSize));\n sum += Vector.Sum(v);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n sum += input[i];\n }\n\n var mean = sum / input.Length;\n\n // 2. Subtract mean and calculate variance using SIMD\n float variance = 0;\n var meanVector = new Vector(mean);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var centered = v - meanVector;\n centered.CopyTo(slice);\n variance += Vector.Sum(centered * centered);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] -= mean;\n variance += input[i] * input[i];\n }\n\n // 3. Calculate stddev and normalize\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVector = new Vector(stddev);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var normalized = v / stddevVector;\n normalized.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] /= stddev;\n }\n }\n\n // Hardware-specific optimization for AVX2-capable systems\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeAvx(Span input)\n {\n if ( !Avx.IsSupported || input.Length < 8 )\n {\n NormalizeSimd(input);\n\n return;\n }\n\n unsafe\n {\n fixed (float* pInput = input)\n {\n // Calculate sum using AVX\n var sumVec = Vector256.Zero;\n var avxVectorCount = input.Length / 8;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n sumVec = Avx.Add(sumVec, v);\n }\n\n // Horizontal sum\n var sumArray = stackalloc float[8];\n Avx.Store(sumArray, sumVec);\n\n float sum = 0;\n for ( var i = 0; i < 8; i++ )\n {\n sum += sumArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n sum += pInput[i];\n }\n\n var mean = sum / input.Length;\n var meanVec = Vector256.Create(mean);\n\n // Subtract mean and compute variance\n var varianceVec = Vector256.Zero;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var centered = Avx.Subtract(v, meanVec);\n Avx.Store(pInput + i * 8, centered);\n varianceVec = Avx.Add(varianceVec, Avx.Multiply(centered, centered));\n }\n\n // Get variance\n var varArray = stackalloc float[8];\n Avx.Store(varArray, varianceVec);\n\n float variance = 0;\n for ( var i = 0; i < 8; i++ )\n {\n variance += varArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] -= mean;\n variance += pInput[i] * pInput[i];\n }\n\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVec = Vector256.Create(stddev);\n\n // Normalize\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var normalized = Avx.Divide(v, stddevVec);\n Avx.Store(pInput + i * 8, normalized);\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] /= stddev;\n }\n }\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor using SIMD where possible\n for ( var i = 0; i < batchSize; i++ )\n {\n var inputOffset = i * WINDOW_SIZE;\n var vectorCount = WINDOW_SIZE / _vectorSize;\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var vectorOffset = v * _vectorSize;\n var source = new Vector(_inputBatchBuffer.AsSpan(inputOffset + vectorOffset, _vectorSize));\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n _inputTensor[i, vectorOffset + j] = source[j];\n }\n }\n\n // Handle remainder\n for ( var j = vectorCount * _vectorSize; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[inputOffset + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Apply frequency range limitation using SIMD where possible\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n ApplyFrequencyRangeLimit(probabilities, outputSize, minidx, maxidx);\n\n // Make a safe copy of the spans since we can't capture them in parallel operations\n var f0Array = new float[f0.Length];\n var pdArray = new float[pd.Length];\n f0.CopyTo(f0Array);\n pd.CopyTo(pdArray);\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0Array, pdArray, outputSize, offset);\n\n // Copy results back\n for ( var i = 0; i < outputSize; i++ )\n {\n if ( offset + i < f0.Length )\n {\n f0[offset + i] = f0Array[offset + i];\n pd[offset + i] = pdArray[offset + i];\n }\n }\n }\n\n private void ApplyFrequencyRangeLimit(float[] probabilities, int outputSize, int minIdx, int maxIdx)\n {\n // Set values outside the frequency range to negative infinity\n Parallel.For(0, outputSize, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Handle first part (below minIdx)\n for ( var i = 0; i < minIdx; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n\n // Handle second part (above maxIdx)\n for ( var i = maxIdx; i < PITCH_BINS; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n });\n }\n\n private void DecodeViterbi(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n // Transfer probabilities to logProbBuffer and apply softmax\n Buffer.BlockCopy(probabilities, 0, _logProbBuffer, 0, nSteps * PITCH_BINS * sizeof(float));\n\n // Apply softmax with SIMD\n SoftmaxSimd(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n ApplyLogToProbs(_logProbBuffer, nSteps);\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[i] = _logProbBuffer[i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm (forward pass)\n for ( var t = 1; t < nSteps; t++ )\n {\n ViterbiForward(t, nSteps);\n }\n\n // Find the most likely final state\n var maxI = FindArgMax(_valueBuffer, (nSteps - 1) * PITCH_BINS, PITCH_BINS);\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[(t + 1) * PITCH_BINS + _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values and apply periodicity\n ConvertToF0(probabilities, f0, pd, nSteps, offset);\n }\n\n private void SoftmaxSimd(float[] data, int nSteps)\n {\n Parallel.For(0, nSteps, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Find max for numerical stability\n var max = float.NegativeInfinity;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n max = Math.Max(max, data[baseIdx + i]);\n }\n\n // Compute exp(x - max) and sum\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[baseIdx + i] = MathF.Exp(data[baseIdx + i] - max);\n sum += data[baseIdx + i];\n }\n\n // Normalize\n var invSum = 1.0f / sum;\n var vecCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var idx = baseIdx + v * _vectorSize;\n var values = new Vector(data.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n data[idx + j] = normalized[j];\n }\n }\n\n // Handle remainder\n for ( var i = baseIdx + vecCount * _vectorSize; i < baseIdx + PITCH_BINS; i++ )\n {\n data[i] *= invSum;\n }\n });\n }\n\n private void ApplyLogToProbs(float[] data, int nSteps)\n {\n var totalSize = nSteps * PITCH_BINS;\n var vecCount = totalSize / _vectorSize;\n var dataSpan = data.AsSpan(0, totalSize);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var slice = dataSpan.Slice(v * _vectorSize, _vectorSize);\n var values = new Vector(slice);\n var logValues = Vector.Log(values + new Vector(float.Epsilon));\n logValues.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vecCount * _vectorSize; i < totalSize; i++ )\n {\n data[i] = MathF.Log(data[i] + float.Epsilon);\n }\n }\n\n private void ViterbiForward(int t, int nSteps)\n {\n var baseIdxCurrent = t * PITCH_BINS;\n var baseIdxPrev = (t - 1) * PITCH_BINS;\n\n // Fixed number of threads to avoid thread contention\n var threadCount = Math.Min(Environment.ProcessorCount, PITCH_BINS);\n\n Parallel.For(0, threadCount, threadIdx =>\n {\n // Each thread processes a chunk of states\n var statesPerThread = (PITCH_BINS + threadCount - 1) / threadCount;\n var startState = threadIdx * statesPerThread;\n var endState = Math.Min(startState + statesPerThread, PITCH_BINS);\n\n for ( var j = startState; j < endState; j++ )\n {\n var maxI = 0;\n var maxVal = float.NegativeInfinity;\n\n // Find max transition - this could be further vectorized for specific hardware\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n var transVal = _valueBuffer[baseIdxPrev + k] + _transitionMatrix[j * PITCH_BINS + k];\n if ( transVal > maxVal )\n {\n maxVal = transVal;\n maxI = k;\n }\n }\n\n _ptrBuffer[baseIdxCurrent + j] = maxI;\n _valueBuffer[baseIdxCurrent + j] = _logProbBuffer[baseIdxCurrent + j] + maxVal;\n }\n });\n }\n\n private int FindArgMax(float[] data, int offset, int length)\n {\n var maxIdx = 0;\n var maxVal = float.NegativeInfinity;\n\n for ( var i = 0; i < length; i++ )\n {\n if ( data[offset + i] > maxVal )\n {\n maxVal = data[offset + i];\n maxIdx = i;\n }\n }\n\n return maxIdx;\n }\n\n private void ConvertToF0(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n if ( offset + t >= f0.Length )\n {\n break;\n }\n\n var bin = _stateBuffer[t];\n var periodicity = probabilities[t * PITCH_BINS + bin];\n var frequency = ConvertBinToFrequency(bin);\n\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n\n private void ApplyPeriodicityThreshold(Span f0, Span pd, int length)\n {\n const float threshold = 0.1f;\n var vecCount = length / _vectorSize;\n\n // Use SIMD for bulk processing\n for ( var v = 0; v < vecCount; v++ )\n {\n var offset = v * _vectorSize;\n var pdSlice = pd.Slice(offset, _vectorSize);\n var f0Slice = f0.Slice(offset, _vectorSize);\n\n var pdVec = new Vector(pdSlice);\n var thresholdVec = new Vector(threshold);\n var zeroVec = new Vector(0.0f);\n var f0Vec = new Vector(f0Slice);\n\n // Where pd < threshold, set f0 to 0\n var mask = Vector.LessThan(pdVec, thresholdVec);\n var result = Vector.ConditionalSelect(mask, zeroVec, f0Vec);\n\n result.CopyTo(f0Slice);\n }\n\n // Handle remainder with scalar code\n for ( var i = vecCount * _vectorSize; i < length; i++ )\n {\n if ( pd[i] < threshold )\n {\n f0[i] = 0;\n }\n }\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use thread-local window buffers for parallel processing\n Parallel.For(0, length, i =>\n {\n // Allocate a local median buffer for each thread\n var localMedianBuffer = new float[windowSize];\n\n // Get window values\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - radius;\n k = Math.Clamp(k, 0, length - 1);\n localMedianBuffer[j] = original[k];\n }\n\n // Simple sort for small window\n Array.Sort(localMedianBuffer, 0, windowSize);\n result[i] = localMedianBuffer[radius];\n });\n\n // Copy results back to the span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n // Copy to array for processing\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use arrays instead of spans for parallel processing\n Parallel.For(0, length, i =>\n {\n float sum = 0;\n for ( var j = -radius; j <= radius; j++ )\n {\n var k = Math.Clamp(i + j, 0, length - 1);\n sum += original[k];\n }\n\n result[i] = sum / windowSize;\n });\n\n // Copy back to span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void InitializeTransitionMatrix(float[] transitionMatrix)\n {\n Parallel.For(0, PITCH_BINS, y =>\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n float v = 12 - Math.Abs(x - y);\n v = Math.Max(v, 0);\n transitionMatrix[y * PITCH_BINS + x] = v;\n sum += v;\n }\n\n // Normalize and pre-apply log\n var invSum = 1.0f / sum;\n var vectorCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n var epsilonVec = new Vector(float.Epsilon);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var idx = y * PITCH_BINS + v * _vectorSize;\n var values = new Vector(transitionMatrix.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n var logValues = Vector.Log(normalized + epsilonVec);\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n transitionMatrix[idx + j] = logValues[j];\n }\n }\n\n // Handle remainder\n for ( var x = vectorCount * _vectorSize; x < PITCH_BINS; x++ )\n {\n var idx = y * PITCH_BINS + x;\n transitionMatrix[idx] = transitionMatrix[idx] * invSum;\n transitionMatrix[idx] = MathF.Log(transitionMatrix[idx] + float.Epsilon);\n }\n });\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private float ConvertBinToFrequency(int bin)\n {\n const float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n\n return 10 * MathF.Pow(2, cents / 1200);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void FillArray(Span array, float value)\n {\n var vectorCount = array.Length / _vectorSize;\n var valueVec = new Vector(value);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n valueVec.CopyTo(array.Slice(v * _vectorSize, _vectorSize));\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < array.Length; i++ )\n {\n array[i] = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismModelSettingJson.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class CubismModelSettingJson\n{\n // JSON keys\n public const string Version = \"Version\";\n\n public const string FileReferences = \"FileReferences\";\n\n public const string Groups = \"Groups\";\n\n public const string Layout = \"Layout\";\n\n public const string HitAreas = \"HitAreas\";\n\n public const string Moc = \"Moc\";\n\n public const string Textures = \"Textures\";\n\n public const string Physics = \"Physics\";\n\n public const string DisplayInfo = \"DisplayInfo\";\n\n public const string Pose = \"Pose\";\n\n public const string Expressions = \"Expressions\";\n\n public const string Motions = \"Motions\";\n\n public const string UserData = \"UserData\";\n\n public const string Name = \"Name\";\n\n public const string FilePath = \"File\";\n\n public const string Id = \"Id\";\n\n public const string Ids = \"Ids\";\n\n public const string Target = \"Target\";\n\n // Motions\n public const string Idle = \"Idle\";\n\n public const string TapBody = \"TapBody\";\n\n public const string PinchIn = \"PinchIn\";\n\n public const string PinchOut = \"PinchOut\";\n\n public const string Shake = \"Shake\";\n\n public const string FlickHead = \"FlickHead\";\n\n public const string Parameter = \"Parameter\";\n\n public const string SoundPath = \"Sound\";\n\n public const string FadeInTime = \"FadeInTime\";\n\n public const string FadeOutTime = \"FadeOutTime\";\n\n // Layout\n public const string CenterX = \"CenterX\";\n\n public const string CenterY = \"CenterY\";\n\n public const string X = \"X\";\n\n public const string Y = \"Y\";\n\n public const string Width = \"Width\";\n\n public const string Height = \"Height\";\n\n public const string LipSync = \"LipSync\";\n\n public const string EyeBlink = \"EyeBlink\";\n\n public const string InitParameter = \"init_param\";\n\n public const string InitPartsVisible = \"init_parts_visible\";\n\n public const string Val = \"val\";\n\n public static bool GetLayoutMap(this ModelSettingObj obj, Dictionary outLayoutMap)\n {\n var node = obj.Layout;\n if ( node == null )\n {\n return false;\n }\n\n var ret = false;\n foreach ( var item in node )\n {\n if ( outLayoutMap.ContainsKey(item.Key) )\n {\n outLayoutMap[item.Key] = item.Value;\n }\n else\n {\n outLayoutMap.Add(item.Key, item.Value);\n }\n\n ret = true;\n }\n\n return ret;\n }\n\n public static bool IsExistEyeBlinkParameters(this ModelSettingObj obj)\n {\n var node = obj.Groups;\n if ( node == null )\n {\n return false;\n }\n\n foreach ( var item in node )\n {\n if ( item.Name == EyeBlink )\n {\n return true;\n }\n }\n\n return false;\n }\n\n public static bool IsExistLipSyncParameters(this ModelSettingObj obj)\n {\n var node = obj.Groups;\n if ( node == null )\n {\n return false;\n }\n\n foreach ( var item in node )\n {\n if ( item.Name == LipSync )\n {\n return true;\n }\n }\n\n return false;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/BufferedMemoryAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that stores audio samples in memory.\n/// \n/// \n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class BufferedMemoryAudioSource : IAudioSource, IMemoryBackedAudioSource\n{\n public const int DefaultInitialSize = 1024 * 16;\n\n private readonly IChannelAggregationStrategy? aggregationStrategy;\n\n protected byte[]? ByteFrames;\n\n protected float[]? FloatFrames;\n\n private long framesCount;\n\n private bool isDisposed;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// A value indicating whether to store samples as floats. Default true.\n /// A value indicating whether to store samples as byte[]. Default false.\n /// Optional. The channel aggregation strategy to use.\n public BufferedMemoryAudioSource(IReadOnlyDictionary metadata,\n bool storeFloats = true,\n bool storeBytes = false,\n int initialSizeFloats = DefaultInitialSize,\n int initialSizeBytes = DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n {\n Metadata = metadata;\n this.aggregationStrategy = aggregationStrategy;\n\n if ( !storeFloats && !storeBytes )\n {\n throw new ArgumentException(\"At least one of storeFloats or storeBytes must be true.\");\n }\n\n if ( storeFloats )\n {\n FloatFrames = new float[initialSizeFloats];\n }\n\n if ( storeBytes )\n {\n ByteFrames = new byte[initialSizeBytes];\n }\n }\n\n /// \n /// Gets the header of the audio source.\n /// \n protected AudioSourceHeader Header { get; private set; } = null!;\n\n /// \n /// Gets the size of a single frame in the current wave file.\n /// \n public int FrameSize => BitsPerSample * ChannelCount / 8;\n\n /// \n /// Represents the actual number of channels in the source.\n /// \n /// \n /// Note, that the actual number of channels may be different from the number of channels in the header if the source\n /// uses an aggregation strategy.\n /// \n public ushort ChannelCount => aggregationStrategy == null ? Header.Channels : (ushort)1;\n\n /// \n /// Gets the number of samples for each channel.\n /// \n public virtual long FramesCount => framesCount;\n\n /// \n /// Gets a value indicating whether the source is initialized.\n /// \n public bool IsInitialized { get; private set; }\n\n public uint SampleRate => Header.SampleRate;\n\n public ushort BitsPerSample => Header.BitsPerSample;\n\n public IReadOnlyDictionary Metadata { get; }\n\n public virtual TimeSpan Duration => TimeSpan.FromMilliseconds(FramesCount * 1000d / SampleRate);\n\n public virtual TimeSpan TotalDuration => TimeSpan.FromMilliseconds(framesCount * 1000d / SampleRate);\n\n /// \n public void Dispose()\n {\n if ( isDisposed )\n {\n return;\n }\n\n Dispose(true);\n GC.SuppressFinalize(this);\n isDisposed = true;\n }\n\n public virtual Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ThrowIfNotInitialized();\n\n // We first check if we have the samples as floats, if not we deserialize them from bytes\n if ( FloatFrames != null )\n {\n return Task.FromResult(GetFloatFramesSlice(startFrame, maxFrames));\n }\n\n var byteSlice = GetByteFramesSlice(startFrame, maxFrames);\n\n return Task.FromResult(SampleSerializer.Deserialize(byteSlice, BitsPerSample));\n }\n\n public virtual Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n // We first check if we have the samples as bytes, if not we serialize them from floats\n if ( ByteFrames != null )\n {\n return Task.FromResult(GetByteFramesSlice(startFrame, maxFrames));\n }\n\n var slice = GetFloatFramesSlice(startFrame, maxFrames);\n\n return Task.FromResult(SampleSerializer.Serialize(slice, BitsPerSample));\n }\n\n public virtual Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n if ( ByteFrames != null )\n {\n var slice = GetByteFramesSlice(startFrame, maxFrames);\n\n slice.CopyTo(destination);\n var byteFrameCount = slice.Length / FrameSize;\n\n return Task.FromResult(byteFrameCount);\n }\n\n var floatSlice = GetFloatFramesSlice(startFrame, maxFrames);\n SampleSerializer.Serialize(floatSlice, destination, BitsPerSample);\n\n var frameCount = floatSlice.Length / ChannelCount;\n\n return Task.FromResult(frameCount);\n }\n\n public bool StoresFloats => FloatFrames != null;\n\n public bool StoresBytes => ByteFrames != null;\n\n ~BufferedMemoryAudioSource() { Dispose(false); }\n\n /// \n /// Initializes the source with the specified header.\n /// \n /// The audio source header.\n /// Thrown when the source is already initialized.\n public virtual void Initialize(AudioSourceHeader header)\n {\n if ( IsInitialized )\n {\n throw new InvalidOperationException(\"The source is already initialized.\");\n }\n\n Header = header;\n IsInitialized = true;\n }\n\n /// \n /// Adds frames to the source.\n /// \n /// The frame of samples to add.\n /// Thrown when the source is not initialized.\n /// Thrown when the frame size does not match the channels.\n public virtual void AddFrame(ReadOnlyMemory frame)\n {\n ThrowIfNotInitialized();\n\n if ( frame.Length != Header.Channels )\n {\n throw new ArgumentException(\"The frame size does not match the channels.\", nameof(frame));\n }\n\n if ( FloatFrames != null )\n {\n AddFrameToSamples(frame);\n }\n\n if ( ByteFrames != null )\n {\n AddFrameToFrames(frame);\n }\n\n framesCount++;\n }\n\n /// \n /// Adds frames to the source.\n /// \n /// The frame buffer to add.\n /// Thrown when the source is not initialized.\n /// Thrown when the frame size does not match the channels.\n public virtual void AddFrame(ReadOnlyMemory frame)\n {\n ThrowIfNotInitialized();\n if ( frame.Length != Header.Channels * Header.BitsPerSample / 8 )\n {\n throw new ArgumentException(\"The frame size does not match the channels.\", nameof(frame));\n }\n\n if ( FloatFrames != null )\n {\n AddFrameToSamples(frame);\n }\n\n if ( ByteFrames != null )\n {\n AddFrameToFrames(frame);\n }\n\n framesCount++;\n }\n\n protected void ThrowIfNotInitialized()\n {\n if ( !IsInitialized )\n {\n throw new InvalidOperationException(\"The source is not initialized.\");\n }\n }\n\n /// \n /// Disposes the object.\n /// \n /// A value indicating whether the method is called from Dispose.\n protected virtual void Dispose(bool disposing)\n {\n if ( disposing )\n {\n FloatFrames = [];\n ByteFrames = [];\n }\n }\n\n private Memory GetFloatFramesSlice(long startFrame, int maxFrames)\n {\n var startSample = (int)(startFrame * ChannelCount);\n var length = (int)(Math.Min(maxFrames, FramesCount - startFrame) * ChannelCount);\n\n return FloatFrames.AsMemory(startSample, length);\n }\n\n private Memory GetByteFramesSlice(long startFrame, int maxFrames)\n {\n var startByte = (int)(startFrame * FrameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * FrameSize);\n\n return ByteFrames.AsMemory(startByte, lengthBytes);\n }\n\n private void AddFrameToFrames(ReadOnlyMemory frame)\n {\n if ( ByteFrames!.Length <= FramesCount * FrameSize )\n {\n Array.Resize(ref ByteFrames, ByteFrames.Length * 2);\n }\n\n var startByte = (int)(FramesCount * FrameSize);\n var destinationMemory = ByteFrames.AsMemory(startByte);\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory, BitsPerSample);\n }\n else\n {\n frame.Span.CopyTo(destinationMemory.Span);\n }\n }\n\n private void AddFrameToSamples(ReadOnlyMemory frame)\n {\n if ( FloatFrames!.Length <= FramesCount * ChannelCount )\n {\n Array.Resize(ref FloatFrames, FloatFrames.Length * 2);\n }\n\n var destinationMemory = FloatFrames.AsMemory((int)(FramesCount * ChannelCount));\n\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory, BitsPerSample);\n }\n else\n {\n SampleSerializer.Deserialize(frame, FloatFrames.AsMemory((int)(FramesCount * ChannelCount)), BitsPerSample);\n }\n }\n\n private void AddFrameToFrames(ReadOnlyMemory frame)\n {\n if ( ByteFrames!.Length <= FramesCount * FrameSize )\n {\n Array.Resize(ref ByteFrames, ByteFrames.Length * 2);\n }\n\n var startByte = (int)(FramesCount * FrameSize);\n var destinationMemory = ByteFrames.AsMemory(startByte);\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory, BitsPerSample);\n }\n else\n {\n SampleSerializer.Serialize(frame, ByteFrames.AsMemory(startByte), BitsPerSample);\n }\n }\n\n private void AddFrameToSamples(ReadOnlyMemory frame)\n {\n if ( FloatFrames!.Length <= FramesCount * ChannelCount )\n {\n Array.Resize(ref FloatFrames, FloatFrames.Length * 2);\n }\n\n var destinationMemory = FloatFrames.AsMemory((int)(FramesCount * ChannelCount));\n if ( aggregationStrategy != null )\n {\n aggregationStrategy.Aggregate(frame, destinationMemory);\n }\n else\n {\n frame.Span.CopyTo(destinationMemory.Span);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/ACubismMotion.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションの抽象基底クラス。MotionQueueManagerによってモーションの再生を管理する。\n/// \npublic abstract class ACubismMotion\n{\n protected readonly List FiredEventValues = [];\n\n /// \n /// コンストラクタ。\n /// \n public ACubismMotion()\n {\n FadeInSeconds = -1.0f;\n FadeOutSeconds = -1.0f;\n Weight = 1.0f;\n }\n\n /// \n /// フェードインにかかる時間[秒]\n /// \n public float FadeInSeconds { get; set; }\n\n /// \n /// フェードアウトにかかる時間[秒]\n /// \n public float FadeOutSeconds { get; set; }\n\n /// \n /// モーションの重み\n /// \n public float Weight { get; set; }\n\n /// \n /// モーション再生の開始時刻[秒]\n /// \n public float OffsetSeconds { get; set; }\n\n // モーション再生終了コールバック関数\n public FinishedMotionCallback? OnFinishedMotion { get; set; }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// CubismMotionQueueManagerで管理されているモーション\n /// デルタ時間の積算値[秒]\n public void UpdateParameters(CubismModel model, CubismMotionQueueEntry motionQueueEntry, float userTimeSeconds)\n {\n if ( !motionQueueEntry.Available || motionQueueEntry.Finished )\n {\n return;\n }\n\n SetupMotionQueueEntry(motionQueueEntry, userTimeSeconds);\n\n var fadeWeight = UpdateFadeWeight(motionQueueEntry, userTimeSeconds);\n\n //---- 全てのパラメータIDをループする ----\n DoUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry);\n\n //後処理\n //終了時刻を過ぎたら終了フラグを立てる(CubismMotionQueueManager)\n if ( motionQueueEntry.EndTime > 0 && motionQueueEntry.EndTime < userTimeSeconds )\n {\n motionQueueEntry.Finished = true; //終了\n }\n }\n\n /// \n /// モーションの再生を開始するためのセットアップを行う。\n /// \n /// CubismMotionQueueManagerによって管理されるモーション\n /// 総再生時間(秒)\n public void SetupMotionQueueEntry(CubismMotionQueueEntry motionQueueEntry, float userTimeSeconds)\n {\n if ( !motionQueueEntry.Available || motionQueueEntry.Finished )\n {\n return;\n }\n\n if ( motionQueueEntry.Started )\n {\n return;\n }\n\n motionQueueEntry.Started = true;\n motionQueueEntry.StartTime = userTimeSeconds - OffsetSeconds; //モーションの開始時刻を記録\n motionQueueEntry.FadeInStartTime = userTimeSeconds; //フェードインの開始時刻\n\n var duration = GetDuration();\n\n if ( motionQueueEntry.EndTime < 0 )\n {\n //開始していないうちに終了設定している場合がある。\n motionQueueEntry.EndTime = duration <= 0 ? -1 : motionQueueEntry.StartTime + duration;\n //duration == -1 の場合はループする\n }\n }\n\n /// \n /// モーションのウェイトを更新する。\n /// \n /// CubismMotionQueueManagerで管理されているモーション\n /// デルタ時間の積算値[秒]\n /// \n /// \n public float UpdateFadeWeight(CubismMotionQueueEntry? motionQueueEntry, float userTimeSeconds)\n {\n if ( motionQueueEntry == null )\n {\n CubismLog.Error(\"motionQueueEntry is null.\");\n\n return 0;\n }\n\n var fadeWeight = Weight; //現在の値と掛け合わせる割合\n\n //---- フェードイン・アウトの処理 ----\n //単純なサイン関数でイージングする\n var fadeIn = FadeInSeconds == 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((userTimeSeconds - motionQueueEntry.FadeInStartTime) / FadeInSeconds);\n\n var fadeOut = FadeOutSeconds == 0.0f || motionQueueEntry.EndTime < 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((motionQueueEntry.EndTime - userTimeSeconds) / FadeOutSeconds);\n\n fadeWeight = fadeWeight * fadeIn * fadeOut;\n\n motionQueueEntry.SetState(userTimeSeconds, fadeWeight);\n\n if ( 0.0f > fadeWeight || fadeWeight > 1.0f )\n {\n throw new Exception(\"fadeWeight out of range\");\n }\n\n return fadeWeight;\n }\n\n /// \n /// モーションの長さを取得する。\n /// ループのときは「-1」。\n /// ループではない場合は、オーバーライドする。\n /// 正の値の時は取得される時間で終了する。\n /// 「-1」のときは外部から停止命令が無い限り終わらない処理となる。\n /// \n /// モーションの長さ[秒]\n public virtual float GetDuration() { return -1.0f; }\n\n /// \n /// モーションのループ1回分の長さを取得する。\n /// ループしない場合は GetDuration()と同じ値を返す。\n /// ループ一回分の長さが定義できない場合(プログラム的に動き続けるサブクラスなど)の場合は「-1」を返す\n /// \n /// モーションのループ1回分の長さ[秒]\n public virtual float GetLoopDuration() { return -1.0f; }\n\n /// \n /// イベント発火のチェック。\n /// 入力する時間は呼ばれるモーションタイミングを0とした秒数で行う。\n /// \n /// 前回のイベントチェック時間[秒]\n /// 今回の再生時間[秒]\n /// \n public virtual List GetFiredEvent(float beforeCheckTimeSeconds, float motionTimeSeconds) { return FiredEventValues; }\n\n /// \n /// 透明度のカーブが存在するかどうかを確認する\n /// \n /// \n /// true . キーが存在する\n /// false . キーが存在しない\n /// \n public virtual bool IsExistModelOpacity() { return false; }\n\n /// \n /// 透明度のカーブのインデックスを返す\n /// \n /// success:透明度のカーブのインデックス\n public virtual int GetModelOpacityIndex() { return -1; }\n\n /// \n /// 透明度のIdを返す\n /// \n /// 透明度のId\n public virtual string? GetModelOpacityId(int index) { return \"\"; }\n\n public virtual float GetModelOpacityValue() { return 1.0f; }\n\n public abstract void DoUpdateParameters(CubismModel model, float userTimeSeconds, float weight, CubismMotionQueueEntry motionQueueEntry);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/FileModelProvider.cs", "using System.Collections.Concurrent;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// File-based model provider implementation\n/// \npublic class FileModelProvider : IModelProvider\n{\n private readonly string _baseDirectory;\n\n private readonly ILogger _logger;\n\n private readonly ConcurrentDictionary _modelCache = new();\n\n private bool _disposed;\n\n public FileModelProvider(string baseDirectory, ILogger logger)\n {\n _baseDirectory = baseDirectory ?? throw new ArgumentNullException(nameof(baseDirectory));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n if ( !Directory.Exists(_baseDirectory) )\n {\n throw new DirectoryNotFoundException($\"Model directory not found: {_baseDirectory}\");\n }\n }\n\n /// \n /// Gets a model by type\n /// \n public Task GetModelAsync(ModelType modelType, CancellationToken cancellationToken = default)\n {\n // Check if already cached\n if ( _modelCache.TryGetValue(modelType, out var cachedModel) )\n {\n return Task.FromResult(cachedModel);\n }\n\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Map model type to path\n var modelPath = GetModelPath(modelType);\n\n // Create new model resource\n var model = new ModelResource(modelPath);\n\n // Cache the model\n _modelCache[modelType] = model;\n\n _logger.LogInformation(\"Loaded model {ModelType} from {Path}\", modelType, modelPath);\n\n return Task.FromResult(model);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading model {ModelType}\", modelType);\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n // Dispose all cached models\n foreach ( var model in _modelCache.Values )\n {\n model.Dispose();\n }\n\n _modelCache.Clear();\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Maps model type to file path\n /// \n private string GetModelPath(ModelType modelType)\n {\n var fullPath = Path.Combine(_baseDirectory, modelType.GetDescription());\n\n return fullPath;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Vision/WindowCaptureService.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.Formats.Png;\nusing SixLabors.ImageSharp.PixelFormats;\nusing SixLabors.ImageSharp.Processing;\n\nusing uniffi.rust_lib;\n\nnamespace PersonaEngine.Lib.Vision;\n\npublic class CaptureFrameEventArgs : EventArgs\n{\n public CaptureFrameEventArgs(ReadOnlyMemory frameData) { FrameData = frameData; }\n\n public ReadOnlyMemory FrameData { get; }\n}\n\npublic class WindowCaptureService : IDisposable\n{\n private readonly VisionConfig _config;\n\n private readonly CancellationTokenSource _cts = new();\n\n private readonly Lock _lock = new();\n\n private readonly ILogger _logger;\n\n private Task? _captureTask;\n\n public WindowCaptureService(IOptions config, ILogger? logger = null)\n\n {\n _config = config.Value.Vision ?? throw new ArgumentNullException(nameof(config));\n _logger = logger ?? NullLogger.Instance;\n }\n\n public void Dispose()\n {\n StopAsync().GetAwaiter().GetResult();\n _cts.Dispose();\n GC.SuppressFinalize(this);\n }\n\n public event EventHandler? OnCaptureFrame;\n\n private void HandleCaptureFrame(ReadOnlyMemory frameData)\n {\n try\n {\n OnCaptureFrame?.Invoke(this, new CaptureFrameEventArgs(frameData));\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error raising PlaybackStarted event\");\n }\n }\n\n public Task StartAsync(CancellationToken cancellationToken = default)\n {\n lock (_lock)\n {\n if ( _captureTask != null )\n {\n return Task.CompletedTask;\n }\n\n _captureTask = Task.Run(() => CaptureLoop(_cts.Token), cancellationToken);\n }\n\n return Task.CompletedTask;\n }\n\n public async Task StopAsync()\n {\n lock (_lock)\n {\n if ( _captureTask == null )\n {\n return;\n }\n\n _cts.Cancel();\n }\n\n try\n {\n await _captureTask.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n // Expected when cancellation is requested.\n }\n finally\n {\n lock (_lock)\n {\n _captureTask = null;\n }\n }\n }\n\n private async Task CaptureLoop(CancellationToken token)\n {\n while ( !token.IsCancellationRequested )\n {\n try\n {\n if ( OnCaptureFrame == null )\n {\n return;\n }\n\n var result = RustLibMethods.CaptureWindowByTitle(_config.WindowTitle);\n if ( result.image != null )\n {\n var imageData = await ProcessImage(result, token);\n HandleCaptureFrame(imageData);\n }\n }\n catch (OperationCanceledException)\n {\n break;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during capture\");\n }\n\n try\n {\n await Task.Delay(_config.CaptureInterval, token).ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n break;\n }\n }\n }\n\n private async Task> ProcessImage(ImageData imageData, CancellationToken token)\n {\n var minPixels = _config.CaptureMinPixels;\n var maxPixels = _config.CaptureMaxPixels;\n\n var width = (int)imageData.width;\n var height = (int)imageData.height;\n using var image = Image.LoadPixelData(imageData.image, width, height);\n var currentPixels = width * height;\n if ( currentPixels < minPixels || currentPixels > maxPixels )\n {\n double scaleFactor;\n if ( currentPixels < minPixels )\n {\n scaleFactor = Math.Sqrt((double)minPixels / currentPixels);\n }\n else\n {\n scaleFactor = Math.Sqrt((double)maxPixels / currentPixels);\n }\n\n var newWidth = (int)(width * scaleFactor);\n var newHeight = (int)(height * scaleFactor);\n\n image.Mutate(x => x.Resize(newWidth, newHeight));\n }\n\n using var memStream = new MemoryStream();\n await image.SaveAsync(memStream, PngFormat.Instance, token);\n\n return new ReadOnlyMemory(memStream.ToArray());\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionAudioFilter.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Audio filter that attaches emotion data to segments during processing\n/// \npublic class EmotionAudioFilter : IAudioFilter\n{\n private readonly IEmotionService _emotionService;\n\n private readonly ILogger _logger;\n\n public EmotionAudioFilter(IEmotionService emotionService, ILoggerFactory loggerFactory)\n {\n _emotionService = emotionService ?? throw new ArgumentNullException(nameof(emotionService));\n _logger = loggerFactory?.CreateLogger() ??\n throw new ArgumentNullException(nameof(loggerFactory));\n }\n\n /// \n /// Priority of the filter (should run after other filters)\n /// \n public int Priority => -100;\n\n /// \n /// Processes the audio segment to attach emotion data\n /// \n public void Process(AudioSegment segment)\n {\n // No modification to the audio data is needed\n // This filter is just here to hook into the audio processing pipeline\n // and could be used to perform any additional emotion-related processing if needed\n\n var emotions = _emotionService.GetEmotions(segment.Id);\n if ( emotions.Any() )\n {\n _logger.LogDebug(\"Audio segment {SegmentId} has {Count} emotions\", segment.Id, emotions.Count);\n\n // The emotions are already registered with the emotion service\n // We could attach them directly to the segment if needed via a custom extension method\n // or simply document that they should be retrieved via the service\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiConfigurationManager.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements centralized configuration management\n/// \npublic class UiConfigurationManager : IUiConfigurationManager\n{\n private readonly string _configFilePath;\n\n private readonly IOptionsMonitor _configMonitor;\n\n private AvatarAppConfig _currentConfig;\n\n public UiConfigurationManager(\n IOptionsMonitor configMonitor,\n string configFilePath = \"appsettings.json\")\n {\n _configMonitor = configMonitor ?? throw new ArgumentNullException(nameof(configMonitor));\n _configFilePath = configFilePath;\n _currentConfig = _configMonitor.CurrentValue;\n\n // Subscribe to configuration changes\n _configMonitor.OnChange(config =>\n {\n _currentConfig = config;\n OnConfigurationChanged(null, ConfigurationChangedEventArgs.ChangeType.Reloaded);\n });\n }\n\n public event EventHandler ConfigurationChanged;\n\n public T GetConfiguration(string sectionKey = null)\n {\n if ( sectionKey == null )\n {\n if ( typeof(T) == typeof(AvatarAppConfig) )\n {\n return (T)(object)_currentConfig;\n }\n\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} without section key\");\n }\n\n return sectionKey switch {\n \"TTS\" => (T)(object)_currentConfig.Tts,\n \"Voice\" => (T)(object)_currentConfig.Tts.Voice,\n \"RouletteWheel\" => (T)(object)_currentConfig.RouletteWheel,\n \"Microphone\" => (T)(object)_currentConfig.Microphone,\n _ => throw new ArgumentException($\"Unknown section key: {sectionKey}\")\n };\n }\n\n public void UpdateConfiguration(T configuration, string? sectionKey = null)\n {\n if ( sectionKey == null )\n {\n if ( configuration is AvatarAppConfig appConfig )\n {\n _currentConfig = appConfig;\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n\n return;\n }\n\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} without section key\");\n }\n\n switch ( sectionKey )\n {\n case \"TTS\":\n if ( configuration is TtsConfiguration ttsConfig )\n {\n _currentConfig = _currentConfig with { Tts = ttsConfig };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n\n break;\n\n case \"Voice\":\n if ( configuration is KokoroVoiceOptions voiceOptions )\n {\n var tts = _currentConfig.Tts;\n _currentConfig = _currentConfig with { Tts = tts with { Voice = voiceOptions } };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n\n break;\n\n case \"Roulette\":\n if ( configuration is RouletteWheelOptions rouletteWheelOptions )\n {\n _currentConfig = _currentConfig with { RouletteWheel = rouletteWheelOptions };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n\n break;\n case \"Microphone\":\n if ( configuration is MicrophoneConfiguration microphoneConfig )\n {\n _currentConfig = _currentConfig with { Microphone = microphoneConfig };\n OnConfigurationChanged(sectionKey, ConfigurationChangedEventArgs.ChangeType.Updated);\n }\n else\n {\n throw new ArgumentException($\"Invalid configuration type {typeof(T).Name} for section {sectionKey}\");\n }\n \n break;\n default:\n throw new ArgumentException($\"Unknown section key: {sectionKey}\");\n }\n }\n\n public void SaveConfiguration()\n {\n // Save the configuration to the JSON file\n try\n {\n var jsonString = JsonSerializer.Serialize(\n new Dictionary { { \"Config\", _currentConfig } },\n new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }\n );\n\n File.WriteAllText(_configFilePath, jsonString);\n OnConfigurationChanged(null, ConfigurationChangedEventArgs.ChangeType.Saved);\n }\n catch (Exception ex)\n {\n // Convert to a more specific exception type with details\n throw new ConfigurationSaveException($\"Failed to save configuration to {_configFilePath}\", ex);\n }\n }\n\n public void ReloadConfiguration()\n {\n // Load the latest configuration from options monitor\n _currentConfig = _configMonitor.CurrentValue;\n OnConfigurationChanged(null, ConfigurationChangedEventArgs.ChangeType.Reloaded);\n }\n\n private void OnConfigurationChanged(string sectionKey, ConfigurationChangedEventArgs.ChangeType type) { ConfigurationChanged?.Invoke(this, new ConfigurationChangedEventArgs(sectionKey, type)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TextNormalizer.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Normalizes text for better TTS pronunciation\n/// \npublic class TextNormalizer : ITextNormalizer\n{\n // Whitespace normalization\n private static readonly Regex NonStandardWhitespaceRegex = new(@\"[^\\S \\n]\", RegexOptions.Compiled);\n\n private static readonly Regex MultipleSpacesRegex = new(@\" {2,}\", RegexOptions.Compiled);\n\n private static readonly Regex SpaceBeforePunctuationRegex = new(@\"\\s+([.,;:?!])\", RegexOptions.Compiled);\n\n // Quotation marks\n private static readonly Regex CurlyQuotesRegex = new(@\"[\\u2018\\u2019\\u201C\\u201D]\", RegexOptions.Compiled);\n\n // Abbreviations\n private static readonly Dictionary CommonAbbreviations = new() {\n { new Regex(@\"\\bDr\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Doctor\" },\n { new Regex(@\"\\bMr\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Mister\" },\n { new Regex(@\"\\bMs\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Miss\" },\n { new Regex(@\"\\bMrs\\.(?=\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Missus\" },\n { new Regex(@\"\\betc\\.(?!\\s+[A-Z])\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"etcetera\" },\n { new Regex(@\"\\bSt\\.(?=\\s+)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Street\" },\n { new Regex(@\"\\bAve\\.(?=\\s+)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Avenue\" },\n { new Regex(@\"\\bRd\\.(?=\\s+)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"Road\" },\n { new Regex(@\"\\bPh\\.D\\.(?=\\s+|\\b)\", RegexOptions.Compiled | RegexOptions.IgnoreCase), \"PhD\" }\n };\n\n // Number regex for finding numeric patterns\n private static readonly Regex NumberRegex = new(@\"(? _logger;\n\n public TextNormalizer(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }\n\n /// \n /// Normalizes text for TTS synthesis\n /// \n public string Normalize(string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n return string.Empty;\n }\n\n try\n {\n text = text.Normalize(NormalizationForm.FormC);\n\n text = CleanupLines(text);\n\n text = NormalizeCharacters(text);\n\n text = ProcessUrlsAndEmails(text);\n\n text = ExpandAbbreviations(text);\n\n text = NormalizeWhitespaceAndPunctuation(text);\n\n text = RemoveInvalidSurrogates(text);\n\n return text.Trim();\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during text normalization\");\n\n return text;\n }\n }\n\n private string CleanupLines(string text)\n {\n // Split by line, trim each line, and remove empty ones\n var lines = text.Split('\\n');\n var nonEmptyLines = new List();\n\n foreach ( var line in lines )\n {\n var trimmedLine = line.Trim();\n if ( !string.IsNullOrEmpty(trimmedLine) )\n {\n nonEmptyLines.Add(trimmedLine);\n }\n }\n\n return string.Join(\"\\n\", nonEmptyLines);\n }\n\n private string NormalizeCharacters(string text)\n {\n // Convert curly quotes to straight quotes\n text = CurlyQuotesRegex.Replace(text, match =>\n {\n return match.Value switch {\n \"\\u2018\" or \"\\u2019\" => \"'\",\n \"\\u201C\" or \"\\u201D\" => \"\\\"\",\n _ => match.Value\n };\n });\n\n // Replace other special characters\n text = text\n .Replace(\"…\", \"...\")\n .Replace(\"–\", \"-\")\n .Replace(\"—\", \" - \")\n .Replace(\"•\", \"*\")\n .Replace(\"®\", \" registered \")\n .Replace(\"©\", \" copyright \")\n .Replace(\"™\", \" trademark \");\n\n // Convert Unicode fractions to text\n text = text\n .Replace(\"½\", \" one half \")\n .Replace(\"¼\", \" one quarter \")\n .Replace(\"¾\", \" three quarters \");\n\n return text;\n }\n\n private string RemoveInvalidSurrogates(string input)\n {\n var sb = new StringBuilder();\n for ( var i = 0; i < input.Length; i++ )\n {\n if ( char.IsHighSurrogate(input[i]) )\n {\n // Check if there's a valid low surrogate following\n if ( i + 1 < input.Length && char.IsLowSurrogate(input[i + 1]) )\n {\n sb.Append(input[i]);\n sb.Append(input[i + 1]);\n i++; // Skip the next character as we've already handled it\n }\n // Otherwise, skip the invalid high surrogate\n }\n else if ( !char.IsLowSurrogate(input[i]) )\n {\n // Keep normal characters, skip orphaned low surrogates\n sb.Append(input[i]);\n }\n }\n\n return sb.ToString();\n }\n\n private bool IsValidUtf16(string input)\n {\n for ( var i = 0; i < input.Length; i++ )\n {\n if ( char.IsHighSurrogate(input[i]) )\n {\n if ( i + 1 >= input.Length || !char.IsLowSurrogate(input[i + 1]) )\n {\n return false;\n }\n\n i++; // Skip the low surrogate\n }\n else if ( char.IsLowSurrogate(input[i]) )\n {\n return false; // Unexpected low surrogate\n }\n }\n\n return true;\n }\n\n private string ProcessUrlsAndEmails(string text)\n {\n // Replace URLs with placeholder text\n text = UrlRegex.Replace(text, match => \" URL \");\n\n // Replace email addresses with readable text\n text = EmailRegex.Replace(text, match =>\n {\n var parts = match.Value.Split('@');\n if ( parts.Length != 2 )\n {\n return \" email address \";\n }\n\n var username = string.Join(\" \", SplitCamelCase(parts[0]));\n var domain = parts[1].Replace(\".\", \" dot \");\n\n return $\" {username} at {domain} \";\n });\n\n return text;\n }\n\n private IEnumerable SplitCamelCase(string text)\n {\n var buffer = new StringBuilder();\n\n foreach ( var c in text )\n {\n if ( char.IsUpper(c) && buffer.Length > 0 )\n {\n yield return buffer.ToString();\n buffer.Clear();\n }\n\n buffer.Append(char.ToLower(c));\n }\n\n if ( buffer.Length > 0 )\n {\n yield return buffer.ToString();\n }\n }\n\n private string ExpandAbbreviations(string text)\n {\n foreach ( var kvp in CommonAbbreviations )\n {\n text = kvp.Key.Replace(text, kvp.Value);\n }\n\n return text;\n }\n\n private string NormalizeWhitespaceAndPunctuation(string text)\n {\n // Replace non-standard whitespace with normal spaces\n text = NonStandardWhitespaceRegex.Replace(text, \" \");\n\n // Collapse multiple spaces into one\n text = MultipleSpacesRegex.Replace(text, \" \");\n\n // Fix spacing around punctuation\n text = SpaceBeforePunctuationRegex.Replace(text, \"$1\");\n\n return text;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/PcmResampler.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic class PcmResampler\n{\n // Constants for audio format\n private const int BYTES_PER_SAMPLE = 2;\n\n private const int MAX_FRAME_SIZE = 1920;\n\n private readonly float[] _filterCoefficients;\n\n private readonly int _filterDelay;\n\n // Filter configuration\n private readonly int _filterTaps;\n\n private readonly float[] _floatHistory;\n\n private readonly short[] _history;\n\n // Sample rate configuration\n\n // Pre-allocated working buffers\n private readonly short[] _inputSamples;\n\n private int _historyLength;\n\n // State tracking\n private float _position = 0.0f;\n\n public PcmResampler(int inputSampleRate = 48000, int outputSampleRate = 16000)\n {\n if ( inputSampleRate <= 0 || outputSampleRate <= 0 )\n {\n throw new ArgumentException(\"Sample rates must be positive values\");\n }\n\n InputSampleRate = inputSampleRate;\n OutputSampleRate = outputSampleRate;\n ResampleRatio = (float)InputSampleRate / OutputSampleRate;\n\n _filterTaps = DetermineOptimalFilterTaps(ResampleRatio);\n _filterDelay = _filterTaps / 2;\n\n var cutoffFrequency = Math.Min(0.45f * OutputSampleRate, 0.9f * OutputSampleRate / 2) / InputSampleRate;\n _filterCoefficients = GenerateLowPassFilter(_filterTaps, cutoffFrequency);\n\n _history = new short[_filterTaps + 10];\n _floatHistory = new float[_filterTaps + 10];\n _historyLength = 0;\n\n _inputSamples = new short[MAX_FRAME_SIZE];\n }\n\n public float ResampleRatio { get; }\n\n public int InputSampleRate { get; }\n\n public int OutputSampleRate { get; }\n\n private int DetermineOptimalFilterTaps(float ratio)\n {\n if ( Math.Abs(ratio - Math.Round(ratio)) < 0.01f )\n {\n return Math.Max(24, (int)(12 * ratio));\n }\n\n return Math.Max(36, (int)(18 * ratio));\n }\n\n private float[] GenerateLowPassFilter(int taps, float cutoff)\n {\n var coefficients = new float[taps];\n var center = taps / 2;\n\n var sum = 0.0;\n for ( var i = 0; i < taps; i++ )\n {\n if ( i == center )\n {\n coefficients[i] = (float)(2.0 * Math.PI * cutoff);\n }\n else\n {\n var x = 2.0 * Math.PI * cutoff * (i - center);\n coefficients[i] = (float)(Math.Sin(x) / x);\n }\n\n var window = 0.42 - 0.5 * Math.Cos(2.0 * Math.PI * i / (taps - 1))\n + 0.08 * Math.Cos(4.0 * Math.PI * i / (taps - 1));\n\n coefficients[i] *= (float)window;\n\n sum += coefficients[i];\n }\n\n for ( var i = 0; i < taps; i++ )\n {\n coefficients[i] /= (float)sum;\n }\n\n return coefficients;\n }\n\n public int Process(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length / BYTES_PER_SAMPLE;\n ConvertToShorts(input, _inputSamples, inputSampleCount);\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples * BYTES_PER_SAMPLE )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetSampleWithHistory(sampleIndex, _inputSamples, inputSampleCount);\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n if ( outputIndex < maxOutputSamples )\n {\n BinaryPrimitives.WriteInt16LittleEndian(\n output.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateHistory(_inputSamples, inputSampleCount);\n _position -= inputSampleCount;\n\n return outputIndex * BYTES_PER_SAMPLE;\n }\n\n public int Process(Stream input, Memory output)\n {\n var buffer = new byte[MAX_FRAME_SIZE * BYTES_PER_SAMPLE];\n var bytesRead = input.Read(buffer, 0, buffer.Length);\n\n return Process(buffer.AsSpan(0, bytesRead), output.Span);\n }\n\n public int ProcessInPlace(Span buffer)\n {\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length / BYTES_PER_SAMPLE;\n\n // Make a copy of the input for processing\n Span inputCopy = stackalloc short[inputSampleCount];\n for ( var i = 0; i < inputSampleCount; i++ )\n {\n inputCopy[i] = BinaryPrimitives.ReadInt16LittleEndian(buffer.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // Calculate positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n short sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _history[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n BinaryPrimitives.WriteInt16LittleEndian(\n buffer.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n // We need to keep the input history despite having processed in-place\n UpdateHistory(inputCopy.ToArray(), inputSampleCount);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount * BYTES_PER_SAMPLE;\n }\n\n public int ProcessFloat(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length;\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetFloatSampleWithHistory(sampleIndex, input);\n sum += sample * _filterCoefficients[tap];\n }\n\n if ( outputIndex < maxOutputSamples )\n {\n output[outputIndex] = sum;\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateFloatHistory(input);\n _position -= inputSampleCount;\n\n return outputIndex;\n }\n\n public int ProcessFloatInPlace(Span buffer)\n {\n // For in-place, we must work backward to avoid overwriting unprocessed input\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length;\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // First, store the full input for history and reference\n var inputCopy = new float[inputSampleCount];\n buffer.CopyTo(inputCopy);\n\n // Calculate sample positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n float sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _floatHistory[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0f;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n buffer[outputIndex] = sum;\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n UpdateFloatHistory(inputCopy);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount;\n }\n\n private short GetSampleWithHistory(int index, short[] inputSamples, int inputSampleCount)\n {\n if ( index >= 0 && index < inputSampleCount )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _history[_historyLength + index];\n }\n\n return 0;\n }\n\n private float GetFloatSampleWithHistory(int index, ReadOnlySpan inputSamples)\n {\n if ( index >= 0 && index < inputSamples.Length )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _floatHistory[_historyLength + index];\n }\n\n return 0f;\n }\n\n private void UpdateHistory(short[] currentFrame, int frameLength)\n {\n var samplesToKeep = Math.Min(frameLength, _history.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _history.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_history, _historyLength - unusedHistorySamples, _history, 0, unusedHistorySamples);\n }\n\n Array.Copy(currentFrame, frameLength - samplesToKeep, _history, unusedHistorySamples, samplesToKeep);\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _history.Length);\n }\n\n private void UpdateFloatHistory(ReadOnlySpan currentFrame)\n {\n var samplesToKeep = Math.Min(currentFrame.Length, _floatHistory.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _floatHistory.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_floatHistory, _historyLength - unusedHistorySamples, _floatHistory, 0, unusedHistorySamples);\n }\n\n for ( var i = 0; i < samplesToKeep; i++ )\n {\n _floatHistory[unusedHistorySamples + i] = currentFrame[currentFrame.Length - samplesToKeep + i];\n }\n\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _floatHistory.Length);\n }\n\n private void ConvertToShorts(ReadOnlySpan input, short[] output, int sampleCount)\n {\n for ( var i = 0; i < sampleCount; i++ )\n {\n output[i] = BinaryPrimitives.ReadInt16LittleEndian(input.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n }\n\n public void Reset()\n {\n _position = 0;\n _historyLength = 0;\n Array.Clear(_history, 0, _history.Length);\n Array.Clear(_floatHistory, 0, _floatHistory.Length);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismShader_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal class CubismShader_OpenGLES2(OpenGLApi gl)\n{\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_HIGH = \"highp\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_MID = \"mediump\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_LOW = \"lowp\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION = CSM_FRAGMENT_SHADER_FP_PRECISION_HIGH;\n\n private const string GLES2 = \"#version 100\\n\";\n\n private const string GLES2C = GLES2 + \"precision \" + CSM_FRAGMENT_SHADER_FP_PRECISION + \" float;\";\n\n private const string Normal = \"#version 120\\n\";\n\n private const string Tegra = \"#version 100\\n\" +\n \"#extension GL_NV_shader_framebuffer_fetch : enable\\n\" +\n \"precision \" + CSM_FRAGMENT_SHADER_FP_PRECISION + \" float;\";\n\n // SetupMask\n public const string VertShaderSrcSetupMask_ES2 =\n GLES2 + VertShaderSrcSetupMask_Base;\n\n public const string VertShaderSrcSetupMask_Normal =\n Normal + VertShaderSrcSetupMask_Base;\n\n private const string VertShaderSrcSetupMask_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nvarying vec4 v_myPos;\nuniform mat4 u_clipMatrix;\nvoid main()\n{\ngl_Position = u_clipMatrix * a_position;\nv_myPos = u_clipMatrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n public const string FragShaderSrcSetupMask_ES2 = GLES2C + FragShaderSrcSetupMask_Base;\n\n public const string FragShaderSrcSetupMask_Normal = Normal + FragShaderSrcSetupMask_Base;\n\n private const string FragShaderSrcSetupMask_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_myPos;\nuniform sampler2D s_texture0;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nvoid main()\n{\nfloat isInside = \n step(u_baseColor.x, v_myPos.x/v_myPos.w)\n* step(u_baseColor.y, v_myPos.y/v_myPos.w)\n* step(v_myPos.x/v_myPos.w, u_baseColor.z)\n* step(v_myPos.y/v_myPos.w, u_baseColor.w);\ngl_FragColor = u_channelFlag * texture2D(s_texture0 , v_texCoord).a * isInside;\n}\";\n\n public const string FragShaderSrcSetupMaskTegra =\n Tegra + FragShaderSrcSetupMask_Base;\n\n //----- バーテックスシェーダプログラム -----\n // Normal & Add & Mult 共通\n public const string VertShaderSrc_ES2 = GLES2 + VertShaderSrc_Base;\n\n public const string VertShaderSrc_Normal = Normal + VertShaderSrc_Base;\n\n private const string VertShaderSrc_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nuniform mat4 u_matrix;\nvoid main()\n{\ngl_Position = u_matrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用)\n public const string VertShaderSrcMasked_ES2 = GLES2 + VertShaderSrcMasked_Base;\n\n public const string VertShaderSrcMasked_Normal = Normal + VertShaderSrcMasked_Base;\n\n private const string VertShaderSrcMasked_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform mat4 u_matrix;\nuniform mat4 u_clipMatrix;\nvoid main()\n{\ngl_Position = u_matrix * a_position;\nv_clipPos = u_clipMatrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n //----- フラグメントシェーダプログラム -----\n // Normal & Add & Mult 共通\n public const string FragShaderSrc_ES2 = GLES2C + FragShaderSrc_Base;\n\n public const string FragShaderSrc_Normal = Normal + FragShaderSrc_Base;\n\n public const string FragShaderSrc_Base =\n @\"varying vec2 v_texCoord;\nuniform sampler2D s_texture0;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 color = texColor * u_baseColor;\ngl_FragColor = vec4(color.rgb * color.a, color.a);\n}\";\n\n public const string FragShaderSrcTegra = Tegra + FragShaderSrc_Base;\n\n // Normal & Add & Mult 共通 (PremultipliedAlpha)\n public const string FragShaderSrcPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcPremultipliedAlpha_Base;\n\n public const string FragShaderSrcPremultipliedAlpha_Normal = Normal + FragShaderSrcPremultipliedAlpha_Base;\n\n public const string FragShaderSrcPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\nuniform sampler2D s_texture0;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\ngl_FragColor = texColor * u_baseColor;\n}\";\n\n public const string FragShaderSrcPremultipliedAlphaTegra = Tegra + FragShaderSrcPremultipliedAlpha_Base;\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用)\n public const string FragShaderSrcMask_ES2 = GLES2C + FragShaderSrcMask_Base;\n\n public const string FragShaderSrcMask_Normal = Normal + FragShaderSrcMask_Base;\n\n public const string FragShaderSrcMask_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\ncol_formask.rgb = col_formask.rgb * col_formask.a ;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * maskVal;\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskTegra = Tegra + FragShaderSrcMask_Base;\n\n // Normal & Add & Mult 共通(クリッピングされて反転使用の描画用)\n public const string FragShaderSrcMaskInverted_ES2 = GLES2C + FragShaderSrcMaskInverted_Base;\n\n public const string FragShaderSrcMaskInverted_Normal = Normal + FragShaderSrcMaskInverted_Base;\n\n public const string FragShaderSrcMaskInverted_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\ncol_formask.rgb = col_formask.rgb * col_formask.a ;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * (1.0 - maskVal);\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskInvertedTegra = Tegra + FragShaderSrcMaskInverted_Base;\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用、PremultipliedAlphaの場合)\n public const string FragShaderSrcMaskPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskPremultipliedAlpha_Normal = Normal + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\n varying vec4 v_clipPos;\n uniform sampler2D s_texture0;\n uniform sampler2D s_texture1;\n uniform vec4 u_channelFlag;\n uniform vec4 u_baseColor;\n uniform vec4 u_multiplyColor;\n uniform vec4 u_screenColor;\n void main()\n {\n vec4 texColor = texture2D(s_texture0 , v_texCoord);\n texColor.rgb = texColor.rgb * u_multiplyColor.rgb;\n texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\n vec4 col_formask = texColor * u_baseColor;\n vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\n float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\n col_formask = col_formask * maskVal;\n gl_FragColor = col_formask;\n }\";\n\n public const string FragShaderSrcMaskPremultipliedAlphaTegra = Tegra + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n // Normal & Add & Mult 共通(クリッピングされて反転使用の描画用、PremultipliedAlphaの場合)\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_Normal = Normal + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * (1.0 - maskVal);\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlphaTegra = Tegra + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const int ShaderCount = 19; // シェーダの数 = マスク生成用 + (通常 + 加算 + 乗算) * (マスク無 + マスク有 + マスク有反転 + マスク無の乗算済アルファ対応版 + マスク有の乗算済アルファ対応版 + マスク有反転の乗算済アルファ対応版)\n\n /// \n /// ロードしたシェーダプログラムを保持する変数\n /// \n private readonly List _shaderSets = [];\n\n /// \n /// Tegra対応.拡張方式で描画\n /// \n internal bool s_extMode;\n\n /// \n /// 拡張方式のPA設定用の変数\n /// \n internal bool s_extPAMode;\n\n /// \n /// シェーダプログラムの一連のセットアップを実行する\n /// \n /// レンダラのインスタンス\n /// GPUのテクスチャID\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 不透明度\n /// カラーブレンディングのタイプ\n /// ベースカラー\n /// \n /// \n /// 乗算済みアルファかどうか\n /// Model-View-Projection行列\n /// マスクを反転して使用するフラグ\n internal void SetupShaderProgramForDraw(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index)\n {\n if ( _shaderSets.Count == 0 )\n {\n GenerateShaders();\n }\n\n // Blending\n int SRC_COLOR;\n int DST_COLOR;\n int SRC_ALPHA;\n int DST_ALPHA;\n\n // _shaderSets用のオフセット計算\n var masked = renderer.ClippingContextBufferForDraw != null; // この描画オブジェクトはマスク対象か\n var invertedMask = model.GetDrawableInvertedMask(index);\n var isPremultipliedAlpha = renderer.IsPremultipliedAlpha;\n var offset = (masked ? invertedMask ? 2 : 1 : 0) + (isPremultipliedAlpha ? 3 : 0);\n\n CubismShaderSet shaderSet;\n switch ( model.GetDrawableBlendMode(index) )\n {\n case CubismBlendMode.Normal:\n default:\n shaderSet = _shaderSets[(int)ShaderNames.Normal + offset];\n SRC_COLOR = gl.GL_ONE;\n DST_COLOR = gl.GL_ONE_MINUS_SRC_ALPHA;\n SRC_ALPHA = gl.GL_ONE;\n DST_ALPHA = gl.GL_ONE_MINUS_SRC_ALPHA;\n\n break;\n\n case CubismBlendMode.Additive:\n shaderSet = _shaderSets[(int)ShaderNames.Add + offset];\n SRC_COLOR = gl.GL_ONE;\n DST_COLOR = gl.GL_ONE;\n SRC_ALPHA = gl.GL_ZERO;\n DST_ALPHA = gl.GL_ONE;\n\n break;\n\n case CubismBlendMode.Multiplicative:\n shaderSet = _shaderSets[(int)ShaderNames.Mult + offset];\n SRC_COLOR = gl.GL_DST_COLOR;\n DST_COLOR = gl.GL_ONE_MINUS_SRC_ALPHA;\n SRC_ALPHA = gl.GL_ZERO;\n DST_ALPHA = gl.GL_ONE;\n\n break;\n }\n\n gl.UseProgram(shaderSet.ShaderProgram);\n\n // 頂点配列の設定\n SetupTexture(renderer, model, index, shaderSet);\n\n // テクスチャ頂点の設定\n SetVertexAttributes(shaderSet);\n\n if ( masked )\n {\n gl.ActiveTexture(gl.GL_TEXTURE1);\n\n var draw = renderer.ClippingContextBufferForDraw!;\n\n // frameBufferに書かれたテクスチャ\n var tex = renderer.GetMaskBuffer(draw.BufferIndex).ColorBuffer;\n\n gl.BindTexture(gl.GL_TEXTURE_2D, tex);\n gl.Uniform1i(shaderSet.SamplerTexture1Location, 1);\n\n // View座標をClippingContextの座標に変換するための行列を設定\n gl.UniformMatrix4fv(shaderSet.UniformClipMatrixLocation, 1, false, draw.MatrixForDraw.Tr);\n\n // 使用するカラーチャンネルを設定\n SetColorChannelUniformVariables(shaderSet, renderer.ClippingContextBufferForDraw!);\n }\n\n //座標変換\n gl.UniformMatrix4fv(shaderSet.UniformMatrixLocation, 1, false, renderer.GetMvpMatrix().Tr);\n\n // ユニフォーム変数設定\n var baseColor = renderer.GetModelColorWithOpacity(model.GetDrawableOpacity(index));\n var multiplyColor = model.GetMultiplyColor(index);\n var screenColor = model.GetScreenColor(index);\n SetColorUniformVariables(shaderSet, baseColor, multiplyColor, screenColor);\n\n gl.BlendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);\n }\n\n internal void SetupShaderProgramForMask(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index)\n {\n if ( _shaderSets.Count == 0 )\n {\n GenerateShaders();\n }\n\n // Blending\n var SRC_COLOR = gl.GL_ZERO;\n var DST_COLOR = gl.GL_ONE_MINUS_SRC_COLOR;\n var SRC_ALPHA = gl.GL_ZERO;\n var DST_ALPHA = gl.GL_ONE_MINUS_SRC_ALPHA;\n\n var shaderSet = _shaderSets[(int)ShaderNames.SetupMask];\n gl.UseProgram(shaderSet.ShaderProgram);\n\n var draw = renderer.ClippingContextBufferForMask!;\n\n //テクスチャ設定\n SetupTexture(renderer, model, index, shaderSet);\n\n // 頂点配列の設定\n SetVertexAttributes(shaderSet);\n\n // 使用するカラーチャンネルを設定\n SetColorChannelUniformVariables(shaderSet, draw);\n\n gl.UniformMatrix4fv(shaderSet.UniformClipMatrixLocation, 1, false, draw.MatrixForMask.Tr);\n\n var rect = draw.LayoutBounds;\n CubismTextureColor baseColor = new(rect.X * 2.0f - 1.0f, rect.Y * 2.0f - 1.0f, rect.GetRight() * 2.0f - 1.0f, rect.GetBottom() * 2.0f - 1.0f);\n var multiplyColor = model.GetMultiplyColor(index);\n var screenColor = model.GetScreenColor(index);\n SetColorUniformVariables(shaderSet, baseColor, multiplyColor, screenColor);\n\n gl.BlendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);\n }\n\n /// \n /// シェーダプログラムを解放する\n /// \n internal void ReleaseShaderProgram()\n {\n for ( var i = 0; i < _shaderSets.Count; i++ )\n {\n if ( _shaderSets[i].ShaderProgram != 0 )\n {\n gl.DeleteProgram(_shaderSets[i].ShaderProgram);\n _shaderSets[i].ShaderProgram = 0;\n }\n }\n }\n\n /// \n /// シェーダプログラムを初期化する\n /// \n internal void GenerateShaders()\n {\n for ( var i = 0; i < ShaderCount; i++ )\n {\n _shaderSets.Add(new CubismShaderSet());\n }\n\n if ( gl.IsES2 )\n {\n if ( s_extMode )\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_ES2, FragShaderSrcSetupMaskTegra);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcTegra);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskTegra);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedTegra);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcPremultipliedAlphaTegra);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskPremultipliedAlphaTegra);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedPremultipliedAlphaTegra);\n }\n else\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_ES2, FragShaderSrcSetupMask_ES2);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrc_ES2);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMask_ES2);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInverted_ES2);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcPremultipliedAlpha_ES2);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskPremultipliedAlpha_ES2);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedPremultipliedAlpha_ES2);\n }\n\n // 加算も通常と同じシェーダーを利用する\n _shaderSets[7].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[8].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[9].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[10].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[11].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[12].ShaderProgram = _shaderSets[6].ShaderProgram;\n\n // 乗算も通常と同じシェーダーを利用する\n _shaderSets[13].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[14].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[15].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[16].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[17].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[18].ShaderProgram = _shaderSets[6].ShaderProgram;\n }\n else\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_Normal, FragShaderSrcSetupMask_Normal);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_Normal, FragShaderSrc_Normal);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMask_Normal);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskInverted_Normal);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_Normal, FragShaderSrcPremultipliedAlpha_Normal);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskPremultipliedAlpha_Normal);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskInvertedPremultipliedAlpha_Normal);\n\n // 加算も通常と同じシェーダーを利用する\n _shaderSets[7].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[8].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[9].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[10].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[11].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[12].ShaderProgram = _shaderSets[6].ShaderProgram;\n\n // 乗算も通常と同じシェーダーを利用する\n _shaderSets[13].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[14].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[15].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[16].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[17].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[18].ShaderProgram = _shaderSets[6].ShaderProgram;\n }\n\n // SetupMask\n _shaderSets[0].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[0].ShaderProgram, \"a_position\");\n _shaderSets[0].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[0].ShaderProgram, \"a_texCoord\");\n _shaderSets[0].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"s_texture0\");\n _shaderSets[0].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[0].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_channelFlag\");\n _shaderSets[0].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_baseColor\");\n _shaderSets[0].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[0].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_screenColor\");\n\n // 通常\n _shaderSets[1].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[1].ShaderProgram, \"a_position\");\n _shaderSets[1].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[1].ShaderProgram, \"a_texCoord\");\n _shaderSets[1].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"s_texture0\");\n _shaderSets[1].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_matrix\");\n _shaderSets[1].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_baseColor\");\n _shaderSets[1].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[1].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング)\n _shaderSets[2].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[2].ShaderProgram, \"a_position\");\n _shaderSets[2].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[2].ShaderProgram, \"a_texCoord\");\n _shaderSets[2].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"s_texture0\");\n _shaderSets[2].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"s_texture1\");\n _shaderSets[2].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_matrix\");\n _shaderSets[2].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[2].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_channelFlag\");\n _shaderSets[2].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_baseColor\");\n _shaderSets[2].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[2].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング・反転)\n _shaderSets[3].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[3].ShaderProgram, \"a_position\");\n _shaderSets[3].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[3].ShaderProgram, \"a_texCoord\");\n _shaderSets[3].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"s_texture0\");\n _shaderSets[3].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"s_texture1\");\n _shaderSets[3].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_matrix\");\n _shaderSets[3].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[3].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_channelFlag\");\n _shaderSets[3].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_baseColor\");\n _shaderSets[3].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[3].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_screenColor\");\n\n // 通常(PremultipliedAlpha)\n _shaderSets[4].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[4].ShaderProgram, \"a_position\");\n _shaderSets[4].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[4].ShaderProgram, \"a_texCoord\");\n _shaderSets[4].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"s_texture0\");\n _shaderSets[4].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_matrix\");\n _shaderSets[4].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_baseColor\");\n _shaderSets[4].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[4].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング、PremultipliedAlpha)\n _shaderSets[5].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[5].ShaderProgram, \"a_position\");\n _shaderSets[5].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[5].ShaderProgram, \"a_texCoord\");\n _shaderSets[5].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"s_texture0\");\n _shaderSets[5].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"s_texture1\");\n _shaderSets[5].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_matrix\");\n _shaderSets[5].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[5].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_channelFlag\");\n _shaderSets[5].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_baseColor\");\n _shaderSets[5].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[5].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[6].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[6].ShaderProgram, \"a_position\");\n _shaderSets[6].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[6].ShaderProgram, \"a_texCoord\");\n _shaderSets[6].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"s_texture0\");\n _shaderSets[6].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"s_texture1\");\n _shaderSets[6].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_matrix\");\n _shaderSets[6].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[6].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_channelFlag\");\n _shaderSets[6].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_baseColor\");\n _shaderSets[6].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[6].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_screenColor\");\n\n // 加算\n _shaderSets[7].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[7].ShaderProgram, \"a_position\");\n _shaderSets[7].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[7].ShaderProgram, \"a_texCoord\");\n _shaderSets[7].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"s_texture0\");\n _shaderSets[7].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_matrix\");\n _shaderSets[7].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_baseColor\");\n _shaderSets[7].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[7].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング)\n _shaderSets[8].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[8].ShaderProgram, \"a_position\");\n _shaderSets[8].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[8].ShaderProgram, \"a_texCoord\");\n _shaderSets[8].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"s_texture0\");\n _shaderSets[8].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"s_texture1\");\n _shaderSets[8].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_matrix\");\n _shaderSets[8].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[8].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_channelFlag\");\n _shaderSets[8].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_baseColor\");\n _shaderSets[8].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[8].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング・反転)\n _shaderSets[9].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[9].ShaderProgram, \"a_position\");\n _shaderSets[9].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[9].ShaderProgram, \"a_texCoord\");\n _shaderSets[9].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"s_texture0\");\n _shaderSets[9].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"s_texture1\");\n _shaderSets[9].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_matrix\");\n _shaderSets[9].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[9].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_channelFlag\");\n _shaderSets[9].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_baseColor\");\n _shaderSets[9].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[9].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_screenColor\");\n\n // 加算(PremultipliedAlpha)\n _shaderSets[10].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[10].ShaderProgram, \"a_position\");\n _shaderSets[10].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[10].ShaderProgram, \"a_texCoord\");\n _shaderSets[10].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"s_texture0\");\n _shaderSets[10].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_matrix\");\n _shaderSets[10].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_baseColor\");\n _shaderSets[10].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[10].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング、PremultipliedAlpha)\n _shaderSets[11].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[11].ShaderProgram, \"a_position\");\n _shaderSets[11].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[11].ShaderProgram, \"a_texCoord\");\n _shaderSets[11].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"s_texture0\");\n _shaderSets[11].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"s_texture1\");\n _shaderSets[11].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_matrix\");\n _shaderSets[11].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[11].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_channelFlag\");\n _shaderSets[11].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_baseColor\");\n _shaderSets[11].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[11].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[12].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[12].ShaderProgram, \"a_position\");\n _shaderSets[12].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[12].ShaderProgram, \"a_texCoord\");\n _shaderSets[12].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"s_texture0\");\n _shaderSets[12].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"s_texture1\");\n _shaderSets[12].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_matrix\");\n _shaderSets[12].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[12].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_channelFlag\");\n _shaderSets[12].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_baseColor\");\n _shaderSets[12].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[12].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_screenColor\");\n\n // 乗算\n _shaderSets[13].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[13].ShaderProgram, \"a_position\");\n _shaderSets[13].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[13].ShaderProgram, \"a_texCoord\");\n _shaderSets[13].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"s_texture0\");\n _shaderSets[13].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_matrix\");\n _shaderSets[13].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_baseColor\");\n _shaderSets[13].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[13].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング)\n _shaderSets[14].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[14].ShaderProgram, \"a_position\");\n _shaderSets[14].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[14].ShaderProgram, \"a_texCoord\");\n _shaderSets[14].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"s_texture0\");\n _shaderSets[14].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"s_texture1\");\n _shaderSets[14].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_matrix\");\n _shaderSets[14].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[14].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_channelFlag\");\n _shaderSets[14].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_baseColor\");\n _shaderSets[14].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[14].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング・反転)\n _shaderSets[15].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[15].ShaderProgram, \"a_position\");\n _shaderSets[15].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[15].ShaderProgram, \"a_texCoord\");\n _shaderSets[15].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"s_texture0\");\n _shaderSets[15].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"s_texture1\");\n _shaderSets[15].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_matrix\");\n _shaderSets[15].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[15].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_channelFlag\");\n _shaderSets[15].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_baseColor\");\n _shaderSets[15].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[15].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_screenColor\");\n\n // 乗算(PremultipliedAlpha)\n _shaderSets[16].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[16].ShaderProgram, \"a_position\");\n _shaderSets[16].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[16].ShaderProgram, \"a_texCoord\");\n _shaderSets[16].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"s_texture0\");\n _shaderSets[16].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_matrix\");\n _shaderSets[16].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_baseColor\");\n _shaderSets[16].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[16].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング、PremultipliedAlpha)\n _shaderSets[17].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[17].ShaderProgram, \"a_position\");\n _shaderSets[17].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[17].ShaderProgram, \"a_texCoord\");\n _shaderSets[17].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"s_texture0\");\n _shaderSets[17].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"s_texture1\");\n _shaderSets[17].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_matrix\");\n _shaderSets[17].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[17].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_channelFlag\");\n _shaderSets[17].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_baseColor\");\n _shaderSets[17].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[17].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[18].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[18].ShaderProgram, \"a_position\");\n _shaderSets[18].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[18].ShaderProgram, \"a_texCoord\");\n _shaderSets[18].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"s_texture0\");\n _shaderSets[18].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"s_texture1\");\n _shaderSets[18].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_matrix\");\n _shaderSets[18].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[18].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_channelFlag\");\n _shaderSets[18].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_baseColor\");\n _shaderSets[18].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[18].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_screenColor\");\n }\n\n /// \n /// シェーダプログラムをロードしてアドレス返す。\n /// \n /// 頂点シェーダのソース\n /// フラグメントシェーダのソース\n /// シェーダプログラムのアドレス\n internal int LoadShaderProgram(string vertShaderSrc, string fragShaderSrc)\n {\n // Create shader program.\n var shaderProgram = gl.CreateProgram();\n\n if ( !CompileShaderSource(out var vertShader, gl.GL_VERTEX_SHADER, vertShaderSrc) )\n {\n CubismLog.Error(\"[Live2D SDK]Vertex shader compile error!\");\n\n return 0;\n }\n\n // Create and compile fragment shader.\n if ( !CompileShaderSource(out var fragShader, gl.GL_FRAGMENT_SHADER, fragShaderSrc) )\n {\n CubismLog.Error(\"[Live2D SDK]Fragment shader compile error!\");\n\n return 0;\n }\n\n // Attach vertex shader to program.\n gl.AttachShader(shaderProgram, vertShader);\n\n // Attach fragment shader to program.\n gl.AttachShader(shaderProgram, fragShader);\n\n // Link program.\n if ( !LinkProgram(shaderProgram) )\n {\n CubismLog.Error(\"[Live2D SDK]Failed to link program: %d\", shaderProgram);\n\n if ( vertShader != 0 )\n {\n gl.DeleteShader(vertShader);\n }\n\n if ( fragShader != 0 )\n {\n gl.DeleteShader(fragShader);\n }\n\n if ( shaderProgram != 0 )\n {\n gl.DeleteProgram(shaderProgram);\n }\n\n return 0;\n }\n\n // Release vertex and fragment shaders.\n if ( vertShader != 0 )\n {\n gl.DetachShader(shaderProgram, vertShader);\n gl.DeleteShader(vertShader);\n }\n\n if ( fragShader != 0 )\n {\n gl.DetachShader(shaderProgram, fragShader);\n gl.DeleteShader(fragShader);\n }\n\n return shaderProgram;\n }\n\n /// \n /// シェーダプログラムをコンパイルする\n /// \n /// コンパイルされたシェーダプログラムのアドレス\n /// シェーダタイプ(Vertex/Fragment)\n /// シェーダソースコード\n /// \n /// true . コンパイル成功\n /// false . コンパイル失敗\n /// \n internal unsafe bool CompileShaderSource(out int outShader, int shaderType, string shaderSource)\n {\n int status;\n\n outShader = gl.CreateShader(shaderType);\n gl.ShaderSource(outShader, shaderSource);\n gl.CompileShader(outShader);\n\n int logLength;\n gl.GetShaderiv(outShader, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetShaderInfoLog(outShader, out var log);\n CubismLog.Error($\"[Live2D SDK]Shader compile log: {log}\");\n }\n\n gl.GetShaderiv(outShader, gl.GL_COMPILE_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n gl.DeleteShader(outShader);\n\n return false;\n }\n\n return true;\n }\n\n /// \n /// シェーダプログラムをリンクする\n /// \n /// リンクするシェーダプログラムのアドレス\n /// \n /// true . リンク成功\n /// false . リンク失敗\n /// \n internal unsafe bool LinkProgram(int shaderProgram)\n {\n int status;\n gl.LinkProgram(shaderProgram);\n\n int logLength;\n gl.GetProgramiv(shaderProgram, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetProgramInfoLog(shaderProgram, out var log);\n CubismLog.Error($\"[Live2D SDK]Program link log: {log}\");\n }\n\n gl.GetProgramiv(shaderProgram, gl.GL_LINK_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n return false;\n }\n\n return true;\n }\n\n /// \n /// シェーダプログラムを検証する\n /// \n /// 検証するシェーダプログラムのアドレス\n /// \n /// true . 正常\n /// false . 異常\n /// \n internal unsafe bool ValidateProgram(int shaderProgram)\n {\n int logLength,\n status;\n\n gl.ValidateProgram(shaderProgram);\n gl.GetProgramiv(shaderProgram, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetProgramInfoLog(shaderProgram, out var log);\n CubismLog.Error($\"[Live2D SDK]Validate program log: {log}\");\n }\n\n gl.GetProgramiv(shaderProgram, gl.GL_VALIDATE_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n return false;\n }\n\n return true;\n }\n\n /// \n /// Tegraプロセッサ対応。拡張方式による描画の有効・無効\n /// \n /// trueなら拡張方式で描画する\n /// trueなら拡張方式のPA設定を有効にする\n internal void SetExtShaderMode(bool extMode, bool extPAMode)\n {\n s_extMode = extMode;\n s_extPAMode = extPAMode;\n }\n\n /// \n /// 必要な頂点属性を設定する\n /// \n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n public void SetVertexAttributes(CubismShaderSet shaderSet)\n {\n // 頂点位置属性の設定\n gl.EnableVertexAttribArray(shaderSet.AttributePositionLocation);\n gl.VertexAttribPointer(shaderSet.AttributePositionLocation, 2, gl.GL_FLOAT, false, 4 * sizeof(float), 0);\n\n // テクスチャ座標属性の設定\n gl.EnableVertexAttribArray(shaderSet.AttributeTexCoordLocation);\n gl.VertexAttribPointer(shaderSet.AttributeTexCoordLocation, 2, gl.GL_FLOAT, false, 4 * sizeof(float), 2 * sizeof(float));\n }\n\n /// \n /// テクスチャの設定を行う\n /// \n /// レンダラー\n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n public void SetupTexture(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index, CubismShaderSet shaderSet)\n {\n var textureIndex = model.GetDrawableTextureIndex(index);\n var textureId = renderer.GetBindedTextureId(textureIndex);\n gl.ActiveTexture(gl.GL_TEXTURE0);\n gl.BindTexture(gl.GL_TEXTURE_2D, textureId);\n gl.Uniform1i(shaderSet.SamplerTexture0Location, 0);\n }\n\n /// \n /// 色関連のユニフォーム変数の設定を行う\n /// \n /// レンダラー\n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n /// ベースカラー\n /// 乗算カラー\n /// スクリーンカラー\n public void SetColorUniformVariables(CubismShaderSet shaderSet,\n CubismTextureColor baseColor, CubismTextureColor multiplyColor, CubismTextureColor screenColor)\n {\n gl.Uniform4f(shaderSet.UniformBaseColorLocation, baseColor.R, baseColor.G, baseColor.B, baseColor.A);\n gl.Uniform4f(shaderSet.UniformMultiplyColorLocation, multiplyColor.R, multiplyColor.G, multiplyColor.B, multiplyColor.A);\n gl.Uniform4f(shaderSet.UniformScreenColorLocation, screenColor.R, screenColor.G, screenColor.B, screenColor.A);\n }\n\n /// \n /// カラーチャンネル関連のユニフォーム変数の設定を行う\n /// \n /// シェーダープログラムのセット\n /// 描画コンテクスト\n public void SetColorChannelUniformVariables(CubismShaderSet shaderSet, CubismClippingContext contextBuffer)\n {\n var channelIndex = contextBuffer.LayoutChannelIndex;\n var colorChannel = contextBuffer.Manager.GetChannelFlagAsColor(channelIndex);\n gl.Uniform4f(shaderSet.UnifromChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TextProcessor.cs", "using Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of text processing for TTS\n/// \npublic class TextProcessor : ITextProcessor\n{\n private readonly ILogger _logger;\n\n private readonly ITextNormalizer _normalizer;\n\n private readonly ISentenceSegmenter _segmenter;\n\n public TextProcessor(\n ITextNormalizer normalizer,\n ISentenceSegmenter segmenter,\n ILogger logger)\n {\n _normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer));\n _segmenter = segmenter ?? throw new ArgumentNullException(nameof(segmenter));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n }\n\n /// \n /// Processes text for TTS by normalizing and segmenting into sentences\n /// \n public Task ProcessAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n _logger.LogInformation(\"Empty text received for processing\");\n\n return Task.FromResult(new ProcessedText(string.Empty, Array.Empty()));\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n // Normalize the text\n var normalizedText = _normalizer.Normalize(text);\n\n if ( string.IsNullOrEmpty(normalizedText) )\n {\n _logger.LogWarning(\"Text normalization resulted in empty text\");\n\n return Task.FromResult(new ProcessedText(string.Empty, Array.Empty()));\n }\n\n // Segment into sentences\n var sentences = _segmenter.Segment(normalizedText);\n\n _logger.LogDebug(\"Processed text into {SentenceCount} sentences\", sentences.Count);\n\n return Task.FromResult(new ProcessedText(normalizedText, sentences));\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error processing text\");\n\n throw;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppTextureManager.cs", "using System.Runtime.InteropServices;\n\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.PixelFormats;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 画像読み込み、管理を行うクラス。\n/// \npublic class LAppTextureManager(LAppDelegate lapp)\n{\n private readonly List _textures = [];\n\n /// \n /// 画像読み込み\n /// \n /// 読み込む画像ファイルパス名\n /// 画像情報。読み込み失敗時はNULLを返す\n public TextureInfo CreateTextureFromPngFile(string fileName)\n {\n //search loaded texture already.\n var item = _textures.FirstOrDefault(a => a.FileName == fileName);\n if ( item != null )\n {\n return item;\n }\n\n // Using SixLabors.ImageSharp to load the image\n using var image = Image.Load(fileName);\n var GL = lapp.GL;\n\n // OpenGL用のテクスチャを生成する\n var textureId = GL.GenTexture();\n GL.BindTexture(GL.GL_TEXTURE_2D, textureId);\n\n // Create a byte array to hold image data\n var pixelData = new byte[4 * image.Width * image.Height]; // 4 bytes per pixel (RGBA)\n\n // Access the pixel data\n image.ProcessPixelRows(accessor =>\n {\n // For each row\n for ( var y = 0; y < accessor.Height; y++ )\n {\n // Get the pixel row span\n var row = accessor.GetRowSpan(y);\n\n // For each pixel in the row\n for ( var x = 0; x < row.Length; x++ )\n {\n // Calculate the position in our byte array\n var arrayPos = (y * accessor.Width + x) * 4;\n\n // Copy RGBA components\n pixelData[arrayPos + 0] = row[x].R;\n pixelData[arrayPos + 1] = row[x].G;\n pixelData[arrayPos + 2] = row[x].B;\n pixelData[arrayPos + 3] = row[x].A;\n }\n }\n });\n\n // Pin the byte array in memory so we can pass a pointer to OpenGL\n var pinnedArray = GCHandle.Alloc(pixelData, GCHandleType.Pinned);\n try\n {\n // Get the address of the first byte in the array\n var pointer = pinnedArray.AddrOfPinnedObject();\n\n // Pass the pointer to OpenGL\n GL.TexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, image.Width, image.Height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pointer);\n GL.GenerateMipmap(GL.GL_TEXTURE_2D);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);\n }\n finally\n {\n // Free the pinned array\n pinnedArray.Free();\n }\n\n GL.BindTexture(GL.GL_TEXTURE_2D, 0);\n\n var info = new TextureInfo { FileName = fileName, Width = image.Width, Height = image.Height, ID = textureId };\n\n _textures.Add(info);\n\n return info;\n }\n\n /// \n /// 指定したテクスチャIDの画像を解放する\n /// \n /// 解放するテクスチャID\n public void ReleaseTexture(int textureId)\n {\n foreach ( var item in _textures )\n {\n if ( item.ID == textureId )\n {\n _textures.Remove(item);\n\n break;\n }\n }\n }\n\n /// \n /// テクスチャIDからテクスチャ情報を得る\n /// \n /// 取得したいテクスチャID\n /// テクスチャが存在していればTextureInfoが返る\n public TextureInfo? GetTextureInfoById(int textureId) { return _textures.FirstOrDefault(a => a.ID == textureId); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Rust/bindings/rust_lib.cs", "// \n// This file was generated by uniffi-bindgen-cs v0.8.4+v0.25.0\n// See https://github.com/NordSecurity/uniffi-bindgen-cs for more information.\n// \n\n#nullable enable\n\n\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nnamespace uniffi.rust_lib;\n\n\n\n// This is a helper for safely working with byte buffers returned from the Rust code.\n// A rust-owned buffer is represented by its capacity, its current length, and a\n// pointer to the underlying data.\n\n[StructLayout(LayoutKind.Sequential)]\ninternal struct RustBuffer {\n public int capacity;\n public int len;\n public IntPtr data;\n\n public static RustBuffer Alloc(int size) {\n return _UniffiHelpers.RustCall((ref RustCallStatus status) => {\n var buffer = _UniFFILib.ffi_rust_lib_rustbuffer_alloc(size, ref status);\n if (buffer.data == IntPtr.Zero) {\n throw new AllocationException($\"RustBuffer.Alloc() returned null data pointer (size={size})\");\n }\n return buffer;\n });\n }\n\n public static void Free(RustBuffer buffer) {\n _UniffiHelpers.RustCall((ref RustCallStatus status) => {\n _UniFFILib.ffi_rust_lib_rustbuffer_free(buffer, ref status);\n });\n }\n\n public static BigEndianStream MemoryStream(IntPtr data, int length) {\n unsafe {\n return new BigEndianStream(new UnmanagedMemoryStream((byte*)data.ToPointer(), length));\n }\n }\n\n public BigEndianStream AsStream() {\n unsafe {\n return new BigEndianStream(new UnmanagedMemoryStream((byte*)data.ToPointer(), len));\n }\n }\n\n public BigEndianStream AsWriteableStream() {\n unsafe {\n return new BigEndianStream(new UnmanagedMemoryStream((byte*)data.ToPointer(), capacity, capacity, FileAccess.Write));\n }\n }\n}\n\n// This is a helper for safely passing byte references into the rust code.\n// It's not actually used at the moment, because there aren't many things that you\n// can take a direct pointer to managed memory, and if we're going to copy something\n// then we might as well copy it into a `RustBuffer`. But it's here for API\n// completeness.\n\n[StructLayout(LayoutKind.Sequential)]\ninternal struct ForeignBytes {\n public int length;\n public IntPtr data;\n}\n\n\n// The FfiConverter interface handles converter types to and from the FFI\n//\n// All implementing objects should be public to support external types. When a\n// type is external we need to import it's FfiConverter.\ninternal abstract class FfiConverter {\n // Convert an FFI type to a C# type\n public abstract CsType Lift(FfiType value);\n\n // Convert C# type to an FFI type\n public abstract FfiType Lower(CsType value);\n\n // Read a C# type from a `ByteBuffer`\n public abstract CsType Read(BigEndianStream stream);\n\n // Calculate bytes to allocate when creating a `RustBuffer`\n //\n // This must return at least as many bytes as the write() function will\n // write. It can return more bytes than needed, for example when writing\n // Strings we can't know the exact bytes needed until we the UTF-8\n // encoding, so we pessimistically allocate the largest size possible (3\n // bytes per codepoint). Allocating extra bytes is not really a big deal\n // because the `RustBuffer` is short-lived.\n public abstract int AllocationSize(CsType value);\n\n // Write a C# type to a `ByteBuffer`\n public abstract void Write(CsType value, BigEndianStream stream);\n\n // Lower a value into a `RustBuffer`\n //\n // This method lowers a value into a `RustBuffer` rather than the normal\n // FfiType. It's used by the callback interface code. Callback interface\n // returns are always serialized into a `RustBuffer` regardless of their\n // normal FFI type.\n public RustBuffer LowerIntoRustBuffer(CsType value) {\n var rbuf = RustBuffer.Alloc(AllocationSize(value));\n try {\n var stream = rbuf.AsWriteableStream();\n Write(value, stream);\n rbuf.len = Convert.ToInt32(stream.Position);\n return rbuf;\n } catch {\n RustBuffer.Free(rbuf);\n throw;\n }\n }\n\n // Lift a value from a `RustBuffer`.\n //\n // This here mostly because of the symmetry with `lowerIntoRustBuffer()`.\n // It's currently only used by the `FfiConverterRustBuffer` class below.\n protected CsType LiftFromRustBuffer(RustBuffer rbuf) {\n var stream = rbuf.AsStream();\n try {\n var item = Read(stream);\n if (stream.HasRemaining()) {\n throw new InternalException(\"junk remaining in buffer after lifting, something is very wrong!!\");\n }\n return item;\n } finally {\n RustBuffer.Free(rbuf);\n }\n }\n}\n\n// FfiConverter that uses `RustBuffer` as the FfiType\ninternal abstract class FfiConverterRustBuffer: FfiConverter {\n public override CsType Lift(RustBuffer value) {\n return LiftFromRustBuffer(value);\n }\n public override RustBuffer Lower(CsType value) {\n return LowerIntoRustBuffer(value);\n }\n}\n\n\n// A handful of classes and functions to support the generated data structures.\n// This would be a good candidate for isolating in its own ffi-support lib.\n// Error runtime.\n[StructLayout(LayoutKind.Sequential)]\nstruct RustCallStatus {\n public sbyte code;\n public RustBuffer error_buf;\n\n public bool IsSuccess() {\n return code == 0;\n }\n\n public bool IsError() {\n return code == 1;\n }\n\n public bool IsPanic() {\n return code == 2;\n }\n}\n\n// Base class for all uniffi exceptions\ninternal class UniffiException: System.Exception {\n public UniffiException(): base() {}\n public UniffiException(string message): base(message) {}\n}\n\ninternal class UndeclaredErrorException: UniffiException {\n public UndeclaredErrorException(string message): base(message) {}\n}\n\ninternal class PanicException: UniffiException {\n public PanicException(string message): base(message) {}\n}\n\ninternal class AllocationException: UniffiException {\n public AllocationException(string message): base(message) {}\n}\n\ninternal class InternalException: UniffiException {\n public InternalException(string message): base(message) {}\n}\n\ninternal class InvalidEnumException: InternalException {\n public InvalidEnumException(string message): base(message) {\n }\n}\n\ninternal class UniffiContractVersionException: UniffiException {\n public UniffiContractVersionException(string message): base(message) {\n }\n}\n\ninternal class UniffiContractChecksumException: UniffiException {\n public UniffiContractChecksumException(string message): base(message) {\n }\n}\n\n// Each top-level error class has a companion object that can lift the error from the call status's rust buffer\ninterface CallStatusErrorHandler where E: System.Exception {\n E Lift(RustBuffer error_buf);\n}\n\n// CallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR\nclass NullCallStatusErrorHandler: CallStatusErrorHandler {\n public static NullCallStatusErrorHandler INSTANCE = new NullCallStatusErrorHandler();\n\n public UniffiException Lift(RustBuffer error_buf) {\n RustBuffer.Free(error_buf);\n return new UndeclaredErrorException(\"library has returned an error not declared in UNIFFI interface file\");\n }\n}\n\n// Helpers for calling Rust\n// In practice we usually need to be synchronized to call this safely, so it doesn't\n// synchronize itself\nclass _UniffiHelpers {\n public delegate void RustCallAction(ref RustCallStatus status);\n public delegate U RustCallFunc(ref RustCallStatus status);\n\n // Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err\n public static U RustCallWithError(CallStatusErrorHandler errorHandler, RustCallFunc callback)\n where E: UniffiException\n {\n var status = new RustCallStatus();\n var return_value = callback(ref status);\n if (status.IsSuccess()) {\n return return_value;\n } else if (status.IsError()) {\n throw errorHandler.Lift(status.error_buf);\n } else if (status.IsPanic()) {\n // when the rust code sees a panic, it tries to construct a rustbuffer\n // with the message. but if that code panics, then it just sends back\n // an empty buffer.\n if (status.error_buf.len > 0) {\n throw new PanicException(FfiConverterString.INSTANCE.Lift(status.error_buf));\n } else {\n throw new PanicException(\"Rust panic\");\n }\n } else {\n throw new InternalException($\"Unknown rust call status: {status.code}\");\n }\n }\n\n // Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err\n public static void RustCallWithError(CallStatusErrorHandler errorHandler, RustCallAction callback)\n where E: UniffiException\n {\n _UniffiHelpers.RustCallWithError(errorHandler, (ref RustCallStatus status) => {\n callback(ref status);\n return 0;\n });\n }\n\n // Call a rust function that returns a plain value\n public static U RustCall(RustCallFunc callback) {\n return _UniffiHelpers.RustCallWithError(NullCallStatusErrorHandler.INSTANCE, callback);\n }\n\n // Call a rust function that returns a plain value\n public static void RustCall(RustCallAction callback) {\n _UniffiHelpers.RustCall((ref RustCallStatus status) => {\n callback(ref status);\n return 0;\n });\n }\n}\n\nstatic class FFIObjectUtil {\n public static void DisposeAll(params Object?[] list) {\n foreach (var obj in list) {\n Dispose(obj);\n }\n }\n\n // Dispose is implemented by recursive type inspection at runtime. This is because\n // generating correct Dispose calls for recursive complex types, e.g. List>\n // is quite cumbersome.\n private static void Dispose(dynamic? obj) {\n if (obj == null) {\n return;\n }\n\n if (obj is IDisposable disposable) {\n disposable.Dispose();\n return;\n }\n\n var type = obj.GetType();\n if (type != null) {\n if (type.IsGenericType) {\n if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) {\n foreach (var value in obj) {\n Dispose(value);\n }\n } else if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>))) {\n foreach (var value in obj.Values) {\n Dispose(value);\n }\n }\n }\n }\n }\n}\n\n\n// Big endian streams are not yet available in dotnet :'(\n// https://github.com/dotnet/runtime/issues/26904\n\nclass StreamUnderflowException: System.Exception {\n public StreamUnderflowException() {\n }\n}\n\nclass BigEndianStream {\n Stream stream;\n public BigEndianStream(Stream stream) {\n this.stream = stream;\n }\n\n public bool HasRemaining() {\n return (stream.Length - stream.Position) > 0;\n }\n\n public long Position {\n get => stream.Position;\n set => stream.Position = value;\n }\n\n public void WriteBytes(byte[] value) {\n stream.Write(value, 0, value.Length);\n }\n\n public void WriteByte(byte value) {\n stream.WriteByte(value);\n }\n\n public void WriteUShort(ushort value) {\n stream.WriteByte((byte)(value >> 8));\n stream.WriteByte((byte)value);\n }\n\n public void WriteUInt(uint value) {\n stream.WriteByte((byte)(value >> 24));\n stream.WriteByte((byte)(value >> 16));\n stream.WriteByte((byte)(value >> 8));\n stream.WriteByte((byte)value);\n }\n\n public void WriteULong(ulong value) {\n WriteUInt((uint)(value >> 32));\n WriteUInt((uint)value);\n }\n\n public void WriteSByte(sbyte value) {\n stream.WriteByte((byte)value);\n }\n\n public void WriteShort(short value) {\n WriteUShort((ushort)value);\n }\n\n public void WriteInt(int value) {\n WriteUInt((uint)value);\n }\n\n public void WriteFloat(float value) {\n unsafe {\n WriteInt(*((int*)&value));\n }\n }\n\n public void WriteLong(long value) {\n WriteULong((ulong)value);\n }\n\n public void WriteDouble(double value) {\n WriteLong(BitConverter.DoubleToInt64Bits(value));\n }\n\n public byte[] ReadBytes(int length) {\n CheckRemaining(length);\n byte[] result = new byte[length];\n stream.Read(result, 0, length);\n return result;\n }\n\n public byte ReadByte() {\n CheckRemaining(1);\n return Convert.ToByte(stream.ReadByte());\n }\n\n public ushort ReadUShort() {\n CheckRemaining(2);\n return (ushort)(stream.ReadByte() << 8 | stream.ReadByte());\n }\n\n public uint ReadUInt() {\n CheckRemaining(4);\n return (uint)(stream.ReadByte() << 24\n | stream.ReadByte() << 16\n | stream.ReadByte() << 8\n | stream.ReadByte());\n }\n\n public ulong ReadULong() {\n return (ulong)ReadUInt() << 32 | (ulong)ReadUInt();\n }\n\n public sbyte ReadSByte() {\n return (sbyte)ReadByte();\n }\n\n public short ReadShort() {\n return (short)ReadUShort();\n }\n\n public int ReadInt() {\n return (int)ReadUInt();\n }\n\n public float ReadFloat() {\n unsafe {\n int value = ReadInt();\n return *((float*)&value);\n }\n }\n\n public long ReadLong() {\n return (long)ReadULong();\n }\n\n public double ReadDouble() {\n return BitConverter.Int64BitsToDouble(ReadLong());\n }\n\n private void CheckRemaining(int length) {\n if (stream.Length - stream.Position < length) {\n throw new StreamUnderflowException();\n }\n }\n}\n\n// Contains loading, initialization code,\n// and the FFI Function declarations in a com.sun.jna.Library.\n\n\n// This is an implementation detail which will be called internally by the public API.\nstatic class _UniFFILib {\n static _UniFFILib() {\n _UniFFILib.uniffiCheckContractApiVersion();\n _UniFFILib.uniffiCheckApiChecksums();\n \n }\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_fullscreen(ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_monitor(RustBuffer @name,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_rect(uint @x,uint @y,uint @width,uint @height,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_window(uint @x,uint @y,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_capture_window_by_title(RustBuffer @name,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_monitor(uint @x,uint @y,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_primary_monitor(ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_screen_dimensions(RustBuffer @name,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer uniffi_rust_lib_fn_func_get_working_area(ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rustbuffer_alloc(int @size,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rustbuffer_from_bytes(ForeignBytes @bytes,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rustbuffer_free(RustBuffer @buf,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rustbuffer_reserve(RustBuffer @buf,int @additional,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_continuation_callback_set(IntPtr @callback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u8(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern byte ffi_rust_lib_rust_future_complete_u8(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i8(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i8(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern sbyte ffi_rust_lib_rust_future_complete_i8(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u16(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort ffi_rust_lib_rust_future_complete_u16(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i16(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i16(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern short ffi_rust_lib_rust_future_complete_i16(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u32(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern uint ffi_rust_lib_rust_future_complete_u32(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i32(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern int ffi_rust_lib_rust_future_complete_i32(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_u64(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_u64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_u64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ulong ffi_rust_lib_rust_future_complete_u64(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_i64(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_i64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_i64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern long ffi_rust_lib_rust_future_complete_i64(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_f32(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_f32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_f32(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern float ffi_rust_lib_rust_future_complete_f32(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_f64(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_f64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_f64(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern double ffi_rust_lib_rust_future_complete_f64(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_pointer(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_pointer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_pointer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern IntPtr ffi_rust_lib_rust_future_complete_pointer(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_rust_buffer(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_rust_buffer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_rust_buffer(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern RustBuffer ffi_rust_lib_rust_future_complete_rust_buffer(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_poll_void(IntPtr @handle,IntPtr @uniffiCallback\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_cancel_void(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_free_void(IntPtr @handle\n );\n\n [DllImport(\"rust_lib\")]\n public static extern void ffi_rust_lib_rust_future_complete_void(IntPtr @handle,ref RustCallStatus _uniffi_out_err\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_fullscreen(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_monitor(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_rect(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_window(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_capture_window_by_title(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_monitor(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_primary_monitor(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_screen_dimensions(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern ushort uniffi_rust_lib_checksum_func_get_working_area(\n );\n\n [DllImport(\"rust_lib\")]\n public static extern uint ffi_rust_lib_uniffi_contract_version(\n );\n\n \n\n static void uniffiCheckContractApiVersion() {\n var scaffolding_contract_version = _UniFFILib.ffi_rust_lib_uniffi_contract_version();\n if (24 != scaffolding_contract_version) {\n throw new UniffiContractVersionException($\"uniffi.rust_lib: uniffi bindings expected version `24`, library returned `{scaffolding_contract_version}`\");\n }\n }\n\n static void uniffiCheckApiChecksums() {\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_fullscreen();\n if (checksum != 57650) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_fullscreen` checksum `57650`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_monitor();\n if (checksum != 7847) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_monitor` checksum `7847`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_rect();\n if (checksum != 28248) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_rect` checksum `28248`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_window();\n if (checksum != 33381) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_window` checksum `33381`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_capture_window_by_title();\n if (checksum != 11081) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_capture_window_by_title` checksum `11081`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_monitor();\n if (checksum != 29961) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_monitor` checksum `29961`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_primary_monitor();\n if (checksum != 2303) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_primary_monitor` checksum `2303`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_screen_dimensions();\n if (checksum != 2379) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_screen_dimensions` checksum `2379`, library returned `{checksum}`\");\n }\n }\n {\n var checksum = _UniFFILib.uniffi_rust_lib_checksum_func_get_working_area();\n if (checksum != 50016) {\n throw new UniffiContractChecksumException($\"uniffi.rust_lib: uniffi bindings expected function `uniffi_rust_lib_checksum_func_get_working_area` checksum `50016`, library returned `{checksum}`\");\n }\n }\n }\n}\n\n// Public interface members begin here.\n\n#pragma warning disable 8625\n\n\n\n\nclass FfiConverterUInt32: FfiConverter {\n public static FfiConverterUInt32 INSTANCE = new FfiConverterUInt32();\n\n public override uint Lift(uint value) {\n return value;\n }\n\n public override uint Read(BigEndianStream stream) {\n return stream.ReadUInt();\n }\n\n public override uint Lower(uint value) {\n return value;\n }\n\n public override int AllocationSize(uint value) {\n return 4;\n }\n\n public override void Write(uint value, BigEndianStream stream) {\n stream.WriteUInt(value);\n }\n}\n\n\n\nclass FfiConverterInt32: FfiConverter {\n public static FfiConverterInt32 INSTANCE = new FfiConverterInt32();\n\n public override int Lift(int value) {\n return value;\n }\n\n public override int Read(BigEndianStream stream) {\n return stream.ReadInt();\n }\n\n public override int Lower(int value) {\n return value;\n }\n\n public override int AllocationSize(int value) {\n return 4;\n }\n\n public override void Write(int value, BigEndianStream stream) {\n stream.WriteInt(value);\n }\n}\n\n\n\nclass FfiConverterString: FfiConverter {\n public static FfiConverterString INSTANCE = new FfiConverterString();\n\n // Note: we don't inherit from FfiConverterRustBuffer, because we use a\n // special encoding when lowering/lifting. We can use `RustBuffer.len` to\n // store our length and avoid writing it out to the buffer.\n public override string Lift(RustBuffer value) {\n try {\n var bytes = value.AsStream().ReadBytes(value.len);\n return System.Text.Encoding.UTF8.GetString(bytes);\n } finally {\n RustBuffer.Free(value);\n }\n }\n\n public override string Read(BigEndianStream stream) {\n var length = stream.ReadInt();\n var bytes = stream.ReadBytes(length);\n return System.Text.Encoding.UTF8.GetString(bytes);\n }\n\n public override RustBuffer Lower(string value) {\n var bytes = System.Text.Encoding.UTF8.GetBytes(value);\n var rbuf = RustBuffer.Alloc(bytes.Length);\n rbuf.AsWriteableStream().WriteBytes(bytes);\n return rbuf;\n }\n\n // TODO(CS)\n // We aren't sure exactly how many bytes our string will be once it's UTF-8\n // encoded. Allocate 3 bytes per unicode codepoint which will always be\n // enough.\n public override int AllocationSize(string value) {\n const int sizeForLength = 4;\n var sizeForString = value.Length * 3;\n return sizeForLength + sizeForString;\n }\n\n public override void Write(string value, BigEndianStream stream) {\n var bytes = System.Text.Encoding.UTF8.GetBytes(value);\n stream.WriteInt(bytes.Length);\n stream.WriteBytes(bytes);\n }\n}\n\n\n\n\nclass FfiConverterByteArray: FfiConverterRustBuffer {\n public static FfiConverterByteArray INSTANCE = new FfiConverterByteArray();\n\n public override byte[] Read(BigEndianStream stream) {\n var length = stream.ReadInt();\n return stream.ReadBytes(length);\n }\n\n public override int AllocationSize(byte[] value) {\n return 4 + value.Length;\n }\n\n public override void Write(byte[] value, BigEndianStream stream) {\n stream.WriteInt(value.Length);\n stream.WriteBytes(value);\n }\n}\n\n\n\ninternal record ImageData (\n byte[]? @image, \n uint @width, \n uint @height\n) {\n}\n\nclass FfiConverterTypeImageData: FfiConverterRustBuffer {\n public static FfiConverterTypeImageData INSTANCE = new FfiConverterTypeImageData();\n\n public override ImageData Read(BigEndianStream stream) {\n return new ImageData(\n @image: FfiConverterOptionalByteArray.INSTANCE.Read(stream),\n @width: FfiConverterUInt32.INSTANCE.Read(stream),\n @height: FfiConverterUInt32.INSTANCE.Read(stream)\n );\n }\n\n public override int AllocationSize(ImageData value) {\n return 0\n + FfiConverterOptionalByteArray.INSTANCE.AllocationSize(value.@image)\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@width)\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@height);\n }\n\n public override void Write(ImageData value, BigEndianStream stream) {\n FfiConverterOptionalByteArray.INSTANCE.Write(value.@image, stream);\n FfiConverterUInt32.INSTANCE.Write(value.@width, stream);\n FfiConverterUInt32.INSTANCE.Write(value.@height, stream);\n }\n}\n\n\n\ninternal record MonitorData (\n uint @width, \n uint @height, \n int @x, \n int @y, \n String @name\n) {\n}\n\nclass FfiConverterTypeMonitorData: FfiConverterRustBuffer {\n public static FfiConverterTypeMonitorData INSTANCE = new FfiConverterTypeMonitorData();\n\n public override MonitorData Read(BigEndianStream stream) {\n return new MonitorData(\n @width: FfiConverterUInt32.INSTANCE.Read(stream),\n @height: FfiConverterUInt32.INSTANCE.Read(stream),\n @x: FfiConverterInt32.INSTANCE.Read(stream),\n @y: FfiConverterInt32.INSTANCE.Read(stream),\n @name: FfiConverterString.INSTANCE.Read(stream)\n );\n }\n\n public override int AllocationSize(MonitorData value) {\n return 0\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@width)\n + FfiConverterUInt32.INSTANCE.AllocationSize(value.@height)\n + FfiConverterInt32.INSTANCE.AllocationSize(value.@x)\n + FfiConverterInt32.INSTANCE.AllocationSize(value.@y)\n + FfiConverterString.INSTANCE.AllocationSize(value.@name);\n }\n\n public override void Write(MonitorData value, BigEndianStream stream) {\n FfiConverterUInt32.INSTANCE.Write(value.@width, stream);\n FfiConverterUInt32.INSTANCE.Write(value.@height, stream);\n FfiConverterInt32.INSTANCE.Write(value.@x, stream);\n FfiConverterInt32.INSTANCE.Write(value.@y, stream);\n FfiConverterString.INSTANCE.Write(value.@name, stream);\n }\n}\n\n\n\n\n\ninternal class CaptureException: UniffiException {\n CaptureException(string message): base(message) {}\n\n // Each variant is a nested class\n // Flat enums carries a string error message, so no special implementation is necessary.\n \n public class Failed: CaptureException {\n public Failed(string message): base(message) {}\n }\n \n}\n\nclass FfiConverterTypeCaptureException : FfiConverterRustBuffer, CallStatusErrorHandler {\n public static FfiConverterTypeCaptureException INSTANCE = new FfiConverterTypeCaptureException();\n\n public override CaptureException Read(BigEndianStream stream) {\n var value = stream.ReadInt();\n switch (value) {\n case 1: return new CaptureException.Failed(FfiConverterString.INSTANCE.Read(stream));\n default:\n throw new InternalException(String.Format(\"invalid error value '{0}' in FfiConverterTypeCaptureException.Read()\", value));\n }\n }\n\n public override int AllocationSize(CaptureException value) {\n return 4 + FfiConverterString.INSTANCE.AllocationSize(value.Message);\n }\n\n public override void Write(CaptureException value, BigEndianStream stream) {\n switch (value) {\n case CaptureException.Failed:\n stream.WriteInt(1);\n break;\n default:\n throw new InternalException(String.Format(\"invalid error value '{0}' in FfiConverterTypeCaptureException.Write()\", value));\n }\n }\n}\n\n\n\n\nclass FfiConverterOptionalByteArray: FfiConverterRustBuffer {\n public static FfiConverterOptionalByteArray INSTANCE = new FfiConverterOptionalByteArray();\n\n public override byte[]? Read(BigEndianStream stream) {\n if (stream.ReadByte() == 0) {\n return null;\n }\n return FfiConverterByteArray.INSTANCE.Read(stream);\n }\n\n public override int AllocationSize(byte[]? value) {\n if (value == null) {\n return 1;\n } else {\n return 1 + FfiConverterByteArray.INSTANCE.AllocationSize((byte[])value);\n }\n }\n\n public override void Write(byte[]? value, BigEndianStream stream) {\n if (value == null) {\n stream.WriteByte(0);\n } else {\n stream.WriteByte(1);\n FfiConverterByteArray.INSTANCE.Write((byte[])value, stream);\n }\n }\n}\n#pragma warning restore 8625\ninternal static class RustLibMethods {\n public static ImageData CaptureFullscreen() {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_fullscreen( ref _status)\n));\n }\n\n\n public static ImageData CaptureMonitor(String @name) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_monitor(FfiConverterString.INSTANCE.Lower(@name), ref _status)\n));\n }\n\n\n public static ImageData CaptureRect(uint @x, uint @y, uint @width, uint @height) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_rect(FfiConverterUInt32.INSTANCE.Lower(@x), FfiConverterUInt32.INSTANCE.Lower(@y), FfiConverterUInt32.INSTANCE.Lower(@width), FfiConverterUInt32.INSTANCE.Lower(@height), ref _status)\n));\n }\n\n\n public static ImageData CaptureWindow(uint @x, uint @y) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_window(FfiConverterUInt32.INSTANCE.Lower(@x), FfiConverterUInt32.INSTANCE.Lower(@y), ref _status)\n));\n }\n\n\n /// \n public static ImageData CaptureWindowByTitle(String @name) {\n return FfiConverterTypeImageData.INSTANCE.Lift(\n _UniffiHelpers.RustCallWithError(FfiConverterTypeCaptureException.INSTANCE, (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_capture_window_by_title(FfiConverterString.INSTANCE.Lower(@name), ref _status)\n));\n }\n\n\n public static MonitorData GetMonitor(uint @x, uint @y) {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_monitor(FfiConverterUInt32.INSTANCE.Lower(@x), FfiConverterUInt32.INSTANCE.Lower(@y), ref _status)\n));\n }\n\n\n public static MonitorData GetPrimaryMonitor() {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_primary_monitor( ref _status)\n));\n }\n\n\n public static MonitorData GetScreenDimensions(String @name) {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_screen_dimensions(FfiConverterString.INSTANCE.Lower(@name), ref _status)\n));\n }\n\n\n public static MonitorData GetWorkingArea() {\n return FfiConverterTypeMonitorData.INSTANCE.Lift(\n _UniffiHelpers.RustCall( (ref RustCallStatus _status) =>\n _UniFFILib.uniffi_rust_lib_fn_func_get_working_area( ref _status)\n));\n }\n\n\n}\n\n"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OpenNlpSentenceDetector.cs", "using Microsoft.Extensions.Logging;\n\nusing OpenNLP.Tools.SentenceDetect;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of OpenNLP-based sentence detection\n/// \npublic class OpenNlpSentenceDetector : IMlSentenceDetector\n{\n private readonly EnglishMaximumEntropySentenceDetector _detector;\n\n private readonly ILogger _logger;\n\n private bool _disposed;\n\n public OpenNlpSentenceDetector(string modelPath, ILogger logger)\n {\n if ( string.IsNullOrEmpty(modelPath) )\n {\n throw new ArgumentException(\"Model path cannot be null or empty\", nameof(modelPath));\n }\n\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n try\n {\n _detector = new EnglishMaximumEntropySentenceDetector(modelPath);\n _logger.LogInformation(\"Initialized OpenNLP sentence detector from {ModelPath}\", modelPath);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to initialize OpenNLP sentence detector\");\n\n throw;\n }\n }\n\n /// \n /// Detects sentences in text using OpenNLP\n /// \n public IReadOnlyList Detect(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Array.Empty();\n }\n\n try\n {\n var sentences = _detector.SentenceDetect(text);\n\n return sentences;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error detecting sentences\");\n\n throw;\n }\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ServiceCollectionExtensions.cs", "#pragma warning disable SKEXP0001\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\n\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing Microsoft.Extensions.Options;\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.SemanticKernel;\n\nusing PersonaEngine.Lib.ASR.Transcriber;\nusing PersonaEngine.Lib.ASR.VAD;\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Input;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Output;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Metrics;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Session;\nusing PersonaEngine.Lib.Live2D;\nusing PersonaEngine.Lib.Live2D.Behaviour;\nusing PersonaEngine.Lib.Live2D.Behaviour.Emotion;\nusing PersonaEngine.Lib.Live2D.Behaviour.LipSync;\nusing PersonaEngine.Lib.LLM;\nusing PersonaEngine.Lib.Logging;\nusing PersonaEngine.Lib.TTS.Audio;\nusing PersonaEngine.Lib.TTS.Profanity;\nusing PersonaEngine.Lib.TTS.RVC;\nusing PersonaEngine.Lib.TTS.Synthesis;\nusing PersonaEngine.Lib.UI;\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.GUI;\nusing PersonaEngine.Lib.UI.RouletteWheel;\nusing PersonaEngine.Lib.UI.Text.Subtitles;\nusing PersonaEngine.Lib.Vision;\n\nusing Polly;\nusing Polly.Retry;\nusing Polly.Timeout;\n\nnamespace PersonaEngine.Lib;\n\npublic static class ServiceCollectionExtensions\n{\n public static IServiceCollection AddApp(this IServiceCollection services, IConfiguration configuration, Action? configureKernel = null)\n {\n services.Configure(configuration.GetSection(\"Config\"));\n\n services.AddConversation(configuration, configureKernel);\n services.AddUI(configuration);\n services.AddLive2D(configuration);\n services.AddSystemAudioPlayer();\n services.AddPolly(configuration);\n\n services.AddSingleton();\n\n OrtEnv.Instance().EnvLogLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR;\n\n return services;\n }\n\n public static IServiceCollection AddConversation(this IServiceCollection services, IConfiguration configuration, Action? configureKernel = null)\n {\n services.AddASRSystem(configuration);\n services.AddTTSSystem(configuration);\n services.AddRVC(configuration);\n#pragma warning disable SKEXP0010\n services.AddLLM(configuration, configureKernel);\n#pragma warning restore SKEXP0010\n services.AddChatEngineSystem(configuration);\n\n services.AddConversationPipeline(configuration);\n\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddConversationPipeline(this IServiceCollection services, IConfiguration configuration)\n {\n services.AddSingleton();\n\n services.AddSingleton();\n\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddASRSystem(this IServiceCollection services, IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Asr\"));\n services.Configure(configuration.GetSection(\"Config:Microphone\"));\n\n services.AddSingleton(sp =>\n {\n var asrOptions = sp.GetRequiredService>().Value;\n\n var siletroOptions = new SileroVadOptions(ModelUtils.GetModelPath(ModelType.Silero)) { Threshold = asrOptions.VadThreshold, ThresholdGap = asrOptions.VadThresholdGap };\n\n var vadOptions = new VadDetectorOptions { MinSpeechDuration = TimeSpan.FromMilliseconds(asrOptions.VadMinSpeechDuration), MinSilenceDuration = TimeSpan.FromMilliseconds(asrOptions.VadMinSilenceDuration) };\n\n return new SileroVadDetector(vadOptions, siletroOptions);\n });\n\n services.AddSingleton(sp =>\n {\n var asrOptions = sp.GetRequiredService>().Value;\n\n var realtimeSpeechTranscriptorOptions = new RealtimeSpeechTranscriptorOptions {\n AutodetectLanguageOnce = false, // Flag to detect the language only once or for each segment\n IncludeSpeechRecogizingEvents = true, // Flag to include speech recognizing events (RealtimeSegmentRecognizing)\n RetrieveTokenDetails = false, // Flag to retrieve token details\n LanguageAutoDetect = false, // Flag to auto-detect the language\n Language = new CultureInfo(\"en-US\"), // Language to use for transcription\n Prompt = asrOptions.TtsPrompt,\n Template = asrOptions.TtsMode\n };\n\n var realTimeOptions = new RealtimeOptions();\n\n return new RealtimeTranscriptor(\n new WhisperSpeechTranscriptorFactory(ModelUtils.GetModelPath(ModelType.WhisperGgmlTurbov3)),\n sp.GetRequiredService(),\n new WhisperSpeechTranscriptorFactory(ModelUtils.GetModelPath(ModelType.WhisperGgmlTiny)),\n realtimeSpeechTranscriptorOptions,\n realTimeOptions,\n sp.GetRequiredService>());\n });\n\n services.AddSingleton();\n services.AddSingleton(sp => sp.GetRequiredService());\n\n return services;\n }\n\n public static IServiceCollection AddSystemAudioPlayer(this IServiceCollection services)\n {\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddChatEngineSystem(this IServiceCollection services, IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Conversation\"));\n services.Configure(configuration.GetSection(\"Config:ConversationContext\"));\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n [Experimental(\"SKEXP0010\")]\n public static IServiceCollection AddLLM(this IServiceCollection services, IConfiguration configuration, Action? configureKernel = null)\n {\n services.Configure(configuration.GetSection(\"Config:Llm\"));\n\n services.AddSingleton(sp =>\n {\n var llmOptions = sp.GetRequiredService>().Value;\n var kernelBuilder = Kernel.CreateBuilder();\n\n kernelBuilder.AddOpenAIChatCompletion(llmOptions.TextModel, new Uri(llmOptions.TextEndpoint), llmOptions.TextApiKey, serviceId: \"text\");\n kernelBuilder.AddOpenAIChatCompletion(llmOptions.VisionEndpoint, new Uri(llmOptions.VisionEndpoint), llmOptions.VisionApiKey, serviceId: \"vision\");\n\n configureKernel?.Invoke(kernelBuilder);\n\n return kernelBuilder.Build();\n });\n\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddTTSSystem(\n this IServiceCollection services,\n IConfiguration configuration)\n {\n // Add configuration\n services.Configure(configuration.GetSection(\"Config:Tts\"));\n services.Configure(configuration.GetSection(\"Config:Tts:Voice\"));\n\n // Add core TTS components\n services.AddSingleton();\n\n // Add text processing components\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton(provider =>\n {\n var logger = provider.GetRequiredService>();\n var modelProvider = provider.GetRequiredService();\n var basePath = modelProvider.GetModelAsync(TTS.Synthesis.ModelType.OpenNLPDir).GetAwaiter().GetResult().Path;\n var modelPath = Path.Combine(basePath, \"EnglishSD.nbin\");\n\n return new OpenNlpSentenceDetector(modelPath, logger);\n });\n\n // Add phoneme processing components\n services.AddSingleton(provider =>\n {\n var posTagger = provider.GetRequiredService();\n var lexicon = provider.GetRequiredService();\n var fallback = provider.GetRequiredService();\n\n return new PhonemizerG2P(posTagger, lexicon, fallback);\n });\n\n services.AddSingleton(provider =>\n {\n var logger = provider.GetRequiredService>();\n var modelProvider = provider.GetRequiredService();\n\n var basePath = modelProvider.GetModelAsync(TTS.Synthesis.ModelType.OpenNLPDir).GetAwaiter().GetResult().Path;\n var modelPath = Path.Combine(basePath, \"EnglishPOS.nbin\");\n\n return new OpenNlpPosTagger(modelPath, logger);\n });\n\n services.AddSingleton();\n services.AddSingleton();\n\n services.AddSingleton();\n services.AddSingleton(provider =>\n {\n var config = provider.GetRequiredService>().Value;\n var logger = provider.GetRequiredService>();\n\n return new FileModelProvider(config.ModelDirectory, logger);\n });\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddUI(\n this IServiceCollection services,\n IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Subtitle\"));\n services.Configure(configuration.GetSection(\"Config:RouletteWheel\"));\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton(x => x.GetRequiredService());\n services.AddConfigEditor();\n\n services.AddSingleton();\n services.AddSingleton(x => x.GetRequiredService());\n\n return services;\n }\n\n public static IServiceCollection AddLive2D(\n this IServiceCollection services,\n IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Live2D\"));\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddEmotionProcessing(configuration);\n\n return services;\n }\n\n public static IServiceCollection AddConfigEditor(this IServiceCollection services)\n {\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n services.AddSingleton();\n\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddRVC(this IServiceCollection services, IConfiguration configuration)\n {\n services.Configure(configuration.GetSection(\"Config:Tts:Rvc\"));\n\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddEmotionProcessing(this IServiceCollection services, IConfiguration configuration)\n {\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n return services;\n }\n\n public static IServiceCollection AddPolly(this IServiceCollection services, IConfiguration configuration)\n {\n services.AddResiliencePipeline(\"semantickernel-chat\", pipelineBuilder =>\n {\n pipelineBuilder\n .AddTimeout(TimeSpan.FromSeconds(60))\n .AddRetry(new RetryStrategyOptions {\n Name = \"ChatServiceRetry\",\n ShouldHandle = new PredicateBuilder().Handle(ex => ex is HttpRequestException ||\n ex is TimeoutRejectedException ||\n (ex is KernelException ke && ke.Message.Contains(\"transient\", StringComparison.OrdinalIgnoreCase))),\n Delay = TimeSpan.FromSeconds(2),\n BackoffType = DelayBackoffType.Exponential,\n MaxDelay = TimeSpan.FromSeconds(30),\n MaxRetryAttempts = 3,\n UseJitter = true,\n OnRetry = args =>\n {\n var sessionId = args.Context.Properties.TryGetValue(ResilienceKeys.SessionId, out var x) ? x : Guid.Empty;\n var logger = args.Context.Properties.TryGetValue(ResilienceKeys.Logger, out var y) ? y : NullLogger.Instance;\n logger.LogWarning(\"Request failed/stopped for session {SessionId}. Retrying in {Timespan}. Attempt {RetryAttempt}...\",\n sessionId, args.Duration, args.AttemptNumber);\n\n return ValueTask.CompletedTask;\n }\n });\n });\n\n return services;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismTargetPoint.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 顔の向きの制御機能を提供するクラス。\n/// \npublic class CubismTargetPoint\n{\n public const int FrameRate = 30;\n\n public const float Epsilon = 0.01f;\n\n /// \n /// 顔の向きのX目標値(この値に近づいていく)\n /// \n private float _faceTargetX;\n\n /// \n /// 顔の向きのY目標値(この値に近づいていく)\n /// \n private float _faceTargetY;\n\n /// \n /// 顔の向きの変化速度X\n /// \n private float _faceVX;\n\n /// \n /// 顔の向きの変化速度Y\n /// \n private float _faceVY;\n\n /// \n /// 最後の実行時間[秒]\n /// \n private float _lastTimeSeconds;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n private float _userTimeSeconds;\n\n /// \n /// 顔の向きX(-1.0 - 1.0)\n /// \n public float FaceX { get; private set; }\n\n /// \n /// 顔の向きY(-1.0 - 1.0)\n /// \n public float FaceY { get; private set; }\n\n /// \n /// 更新処理を行う。\n /// \n /// デルタ時間[秒]\n public void Update(float deltaTimeSeconds)\n {\n // デルタ時間を加算する\n _userTimeSeconds += deltaTimeSeconds;\n\n // 首を中央から左右に振るときの平均的な早さは 秒程度。加速・減速を考慮して、その2倍を最高速度とする\n // 顔のふり具合を、中央(0.0)から、左右は(+-1.0)とする\n var FaceParamMaxV = 40.0f / 10.0f; // 7.5秒間に40分移動(5.3/sc)\n var MaxV = FaceParamMaxV * 1.0f / FrameRate; // 1frameあたりに変化できる速度の上限\n\n if ( _lastTimeSeconds == 0.0f )\n {\n _lastTimeSeconds = _userTimeSeconds;\n\n return;\n }\n\n var deltaTimeWeight = (_userTimeSeconds - _lastTimeSeconds) * FrameRate;\n _lastTimeSeconds = _userTimeSeconds;\n\n // 最高速度になるまでの時間を\n var TimeToMaxSpeed = 0.15f;\n var FrameToMaxSpeed = TimeToMaxSpeed * FrameRate; // sec * frame/sec\n var MaxA = deltaTimeWeight * MaxV / FrameToMaxSpeed; // 1frameあたりの加速度\n\n // 目指す向きは、(dx, dy)方向のベクトルとなる\n var dx = _faceTargetX - FaceX;\n var dy = _faceTargetY - FaceY;\n\n if ( MathF.Abs(dx) <= Epsilon && MathF.Abs(dy) <= Epsilon )\n {\n return; // 変化なし\n }\n\n // 速度の最大よりも大きい場合は、速度を落とす\n var d = MathF.Sqrt(dx * dx + dy * dy);\n\n // 進行方向の最大速度ベクトル\n var vx = MaxV * dx / d;\n var vy = MaxV * dy / d;\n\n // 現在の速度から、新規速度への変化(加速度)を求める\n var ax = vx - _faceVX;\n var ay = vy - _faceVY;\n\n var a = MathF.Sqrt(ax * ax + ay * ay);\n\n // 加速のとき\n if ( a < -MaxA || a > MaxA )\n {\n ax *= MaxA / a;\n ay *= MaxA / a;\n }\n\n // 加速度を元の速度に足して、新速度とする\n _faceVX += ax;\n _faceVY += ay;\n\n // 目的の方向に近づいたとき、滑らかに減速するための処理\n // 設定された加速度で止まることのできる距離と速度の関係から\n // 現在とりうる最高速度を計算し、それ以上のときは速度を落とす\n // ※本来、人間は筋力で力(加速度)を調整できるため、より自由度が高いが、簡単な処理ですませている\n {\n // 加速度、速度、距離の関係式。\n // 2 6 2 3\n // sqrt(a t + 16 a h t - 8 a h) - a t\n // v = --------------------------------------\n // 2\n // 4 t - 2\n // (t=1)\n // 時刻tは、あらかじめ加速度、速度を1/60(フレームレート、単位なし)で\n // 考えているので、t=1として消してよい(※未検証)\n\n var maxV = 0.5f * (MathF.Sqrt(MaxA * MaxA + 16.0f * MaxA * d - 8.0f * MaxA * d) - MaxA);\n var curV = MathF.Sqrt(_faceVX * _faceVX + _faceVY * _faceVY);\n\n if ( curV > maxV )\n {\n // 現在の速度 > 最高速度のとき、最高速度まで減速\n _faceVX *= maxV / curV;\n _faceVY *= maxV / curV;\n }\n }\n\n FaceX += _faceVX;\n FaceY += _faceVY;\n }\n\n /// \n /// 顔の向きの目標値を設定する。\n /// \n /// X軸の顔の向きの値(-1.0 - 1.0)\n /// Y軸の顔の向きの値(-1.0 - 1.0)\n public void Set(float x, float y)\n {\n _faceTargetX = x;\n _faceTargetY = y;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionService.cs", "using Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Implementation of the emotion tracking service\n/// \npublic class EmotionService : IEmotionService\n{\n private readonly Dictionary> _emotionMap = new();\n\n private readonly ILogger _logger;\n\n public EmotionService(ILogger logger) { _logger = logger; }\n\n public void RegisterEmotions(Guid segmentId, IReadOnlyList emotions)\n {\n if (_emotionMap.Count > 100)\n {\n _emotionMap.Clear();\n _logger.LogWarning(\"Emotion map cleared due to size limit\");\n }\n \n if ( emotions is not { Count: > 0 } )\n {\n return;\n }\n\n _emotionMap[segmentId] = emotions;\n _logger.LogDebug(\"Registered {Count} emotions for segment {SegmentId}\", emotions.Count, segmentId);\n }\n\n public IReadOnlyList GetEmotions(Guid segmentId)\n {\n if ( _emotionMap.TryGetValue(segmentId, out var emotions) )\n {\n return emotions;\n }\n\n return Array.Empty();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/Shader.cs", "using System.Diagnostics;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\ninternal struct UniformFieldInfo\n{\n public int Location;\n\n public string Name;\n\n public int Size;\n\n public UniformType Type;\n}\n\ninternal class Shader : IDisposable\n{\n private readonly Dictionary _attribLocation = new();\n\n private readonly (ShaderType Type, string Path)[] _files;\n\n private readonly GL _gl;\n\n private readonly Dictionary _uniformToLocation = new();\n\n private bool _initialized = false;\n\n public Shader(GL gl, string vertexShader, string fragmentShader)\n {\n _gl = gl;\n _files = [(ShaderType.VertexShader, vertexShader), (ShaderType.FragmentShader, fragmentShader)];\n Program = CreateProgram(_files);\n }\n\n public uint Program { get; private set; }\n\n public void Dispose()\n {\n if ( _initialized )\n {\n _gl.DeleteProgram(Program);\n _initialized = false;\n }\n }\n\n public void Use()\n {\n _gl.UseProgram(Program);\n _gl.CheckError();\n }\n\n public void SetUniform(string name, int value)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.Uniform1(location, value);\n _gl.CheckError();\n }\n\n public void SetUniform(string name, float value)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.Uniform1(location, value);\n _gl.CheckError();\n }\n\n public void SetUniform(string name, float value, float value2)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.Uniform2(location, value, value2);\n _gl.CheckError();\n }\n\n public unsafe void SetUniform(string name, Matrix4x4 value)\n {\n var location = GetUniformLocation(name);\n if ( location == -1 )\n {\n throw new Exception($\"{name} uniform not found on shader.\");\n }\n\n _gl.UniformMatrix4(location, 1, false, (float*)&value);\n _gl.CheckError();\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public int GetUniformLocation(string uniform)\n {\n if ( _uniformToLocation.TryGetValue(uniform, out var location) == false )\n {\n location = _gl.GetUniformLocation(Program, uniform);\n _uniformToLocation.Add(uniform, location);\n\n if ( location == -1 )\n {\n Debug.Print($\"The uniform '{uniform}' does not exist in the shader!\");\n }\n }\n\n return location;\n }\n\n public UniformFieldInfo[] GetUniforms()\n {\n _gl.GetProgram(Program, GLEnum.ActiveUniforms, out var uniformCount);\n\n var uniforms = new UniformFieldInfo[uniformCount];\n\n for ( var i = 0; i < uniformCount; i++ )\n {\n var name = _gl.GetActiveUniform(Program, (uint)i, out var size, out var type);\n\n UniformFieldInfo fieldInfo;\n fieldInfo.Location = GetUniformLocation(name);\n fieldInfo.Name = name;\n fieldInfo.Size = size;\n fieldInfo.Type = type;\n\n uniforms[i] = fieldInfo;\n }\n\n return uniforms;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public int GetAttribLocation(string attrib)\n {\n if ( _attribLocation.TryGetValue(attrib, out var location) == false )\n {\n location = _gl.GetAttribLocation(Program, attrib);\n _attribLocation.Add(attrib, location);\n\n if ( location == -1 )\n {\n Debug.Print($\"The attrib '{attrib}' does not exist in the shader!\");\n }\n }\n\n return location;\n }\n\n private uint CreateProgram(params (ShaderType Type, string source)[] shaderPaths)\n {\n var program = _gl.CreateProgram();\n\n Span shaders = stackalloc uint[shaderPaths.Length];\n for ( var i = 0; i < shaderPaths.Length; i++ )\n {\n shaders[i] = CompileShader(shaderPaths[i].Type, shaderPaths[i].source);\n }\n\n foreach ( var shader in shaders )\n {\n _gl.AttachShader(program, shader);\n }\n\n _gl.LinkProgram(program);\n\n _gl.GetProgram(program, GLEnum.LinkStatus, out var success);\n if ( success == 0 )\n {\n var info = _gl.GetProgramInfoLog(program);\n Debug.WriteLine($\"GL.LinkProgram had info log:\\n{info}\");\n }\n\n foreach ( var shader in shaders )\n {\n _gl.DetachShader(program, shader);\n _gl.DeleteShader(shader);\n }\n\n _initialized = true;\n\n return program;\n }\n\n private uint CompileShader(ShaderType type, string source)\n {\n var shader = _gl.CreateShader(type);\n _gl.ShaderSource(shader, source);\n _gl.CompileShader(shader);\n\n _gl.GetShader(shader, ShaderParameterName.CompileStatus, out var success);\n if ( success == 0 )\n {\n var info = _gl.GetShaderInfoLog(shader);\n Debug.WriteLine($\"GL.CompileShader for shader [{type}] had info log:\\n{info}\");\n }\n\n return shader;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/VisualQASemanticKernelChatEngine.cs", "using System.Runtime.CompilerServices;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.SemanticKernel;\nusing Microsoft.SemanticKernel.ChatCompletion;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic class VisualQASemanticKernelChatEngine : IVisualChatEngine\n{\n private readonly IChatCompletionService _chatCompletionService;\n\n private readonly ILogger _logger;\n\n private readonly SemaphoreSlim _semaphore = new(1, 1);\n\n public VisualQASemanticKernelChatEngine(Kernel kernel, ILogger logger)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _chatCompletionService = kernel.GetRequiredService(\"vision\");\n }\n\n public void Dispose()\n {\n try\n {\n _logger.LogInformation(\"Disposing VisualQASemanticKernelChatEngine\");\n _semaphore.Dispose();\n GC.SuppressFinalize(this);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error occurred while disposing VisualQASemanticKernelChatEngine\");\n }\n }\n\n public async IAsyncEnumerable GetStreamingChatResponseAsync(\n VisualChatMessage visualInput,\n PromptExecutionSettings? executionSettings = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n await _semaphore.WaitAsync(cancellationToken);\n\n try\n {\n var chatHistory = new ChatHistory(\"You are a helpful assistant.\");\n chatHistory.AddUserMessage(\n [\n new TextContent(visualInput.Query),\n new ImageContent(visualInput.ImageData, \"image/png\")\n ]);\n\n var chunkCount = 0;\n\n var streamingResponse = _chatCompletionService.GetStreamingChatMessageContentsAsync(\n chatHistory,\n executionSettings,\n null,\n cancellationToken);\n\n await foreach ( var chunk in streamingResponse.ConfigureAwait(false) )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n chunkCount++;\n var content = chunk.Content ?? string.Empty;\n\n yield return content;\n }\n\n _logger.LogInformation(\"Visual QA response streaming completed. Total chunks: {ChunkCount}\", chunkCount);\n }\n finally\n {\n _semaphore.Release();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppDelegate.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// アプリケーションクラス。\n/// Cubism SDK の管理を行う。\n/// \npublic class LAppDelegate : IDisposable\n{\n /// \n /// Cubism SDK Allocator\n /// \n private readonly LAppAllocator _cubismAllocator;\n\n /// \n /// Cubism SDK Option\n /// \n private readonly Option _cubismOption;\n\n /// \n /// クリックしているか\n /// \n private bool _captured;\n\n /// \n /// マウスX座標\n /// \n private float _mouseX;\n\n /// \n /// マウスY座標\n /// \n private float _mouseY;\n\n /// \n /// Initialize関数で設定したウィンドウ高さ\n /// \n private int _windowHeight;\n\n /// \n /// Initialize関数で設定したウィンドウ幅\n /// \n private int _windowWidth;\n\n public LAppDelegate(OpenGLApi gl, LogFunction log)\n {\n GL = gl;\n\n View = new LAppView(this);\n TextureManager = new LAppTextureManager(this);\n _cubismAllocator = new LAppAllocator();\n\n //テクスチャサンプリング設定\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);\n\n //透過設定\n GL.Enable(GL.GL_BLEND);\n GL.BlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);\n\n // ウィンドウサイズ記憶\n GL.GetWindowSize(out _windowWidth, out _windowHeight);\n\n //AppViewの初期化\n View.Initialize();\n\n // Cubism SDK の初期化\n _cubismOption = new Option { LogFunction = log, LoggingLevel = LAppDefine.CubismLoggingLevel };\n CubismFramework.StartUp(_cubismAllocator, _cubismOption);\n\n //Initialize cubism\n CubismFramework.Initialize();\n\n //load model\n Live2dManager = new LAppLive2DManager(this);\n\n LAppPal.DeltaTime = 0;\n }\n\n /// \n /// テクスチャマネージャー\n /// \n public LAppTextureManager TextureManager { get; private set; }\n\n public LAppLive2DManager Live2dManager { get; private set; }\n\n public OpenGLApi GL { get; }\n\n /// \n /// View情報\n /// \n public LAppView View { get; private set; }\n\n public CubismTextureColor BGColor { get; set; } = new(0, 0, 0, 0);\n\n /// \n /// 解放する。\n /// \n public void Dispose()\n {\n // リソースを解放\n Live2dManager.Dispose();\n\n //Cubism SDK の解放\n CubismFramework.Dispose();\n\n GC.SuppressFinalize(this);\n }\n\n public void Resize()\n {\n GL.GetWindowSize(out var width, out var height);\n if ( (_windowWidth != width || _windowHeight != height) && width > 0 && height > 0 )\n {\n //AppViewの初期化\n View.Initialize();\n // サイズを保存しておく\n _windowWidth = width;\n _windowHeight = height;\n }\n }\n\n public void Update(float tick)\n {\n // 時間更新\n LAppPal.DeltaTime = tick;\n }\n\n /// \n /// 実行処理。\n /// \n public void Run()\n {\n // 画面の初期化\n GL.ClearColor(BGColor.R, BGColor.G, BGColor.B, BGColor.A);\n GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n GL.ClearDepthf(1.0f);\n\n //描画更新\n View.Render();\n }\n\n /// \n /// OpenGL用 glfwSetMouseButtonCallback用関数。\n /// \n /// ボタン種類\n /// 実行結果\n public void OnMouseCallBack(bool press)\n {\n if ( press )\n {\n _captured = true;\n View.OnTouchesBegan(_mouseX, _mouseY);\n }\n else\n {\n if ( _captured )\n {\n _captured = false;\n View.OnTouchesEnded(_mouseX, _mouseY);\n }\n }\n }\n\n /// \n /// OpenGL用 glfwSetCursorPosCallback用関数。\n /// \n /// x座標\n /// x座標\n public void OnMouseCallBack(float x, float y)\n {\n if ( !_captured )\n {\n return;\n }\n\n _mouseX = x;\n _mouseY = y;\n\n View.OnTouchesMoved(_mouseX, _mouseY);\n }\n\n public void StartSpeaking(string filePath) { Live2dManager.StartSpeaking(filePath); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiStyler.cs", "using System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Static utility class for common UI styling operations\n/// \npublic static class UiStyler\n{\n /// \n /// Executes an action with a temporary style color change\n /// \n public static void WithStyleColor(ImGuiCol colorId, Vector4 color, Action action)\n {\n ImGui.PushStyleColor(colorId, color);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleColor();\n }\n }\n\n /// \n /// Executes an action with multiple temporary style color changes\n /// \n public static void WithStyleColors(IReadOnlyList<(ImGuiCol, Vector4)> colors, Action action)\n {\n foreach ( var (colorId, color) in colors )\n {\n ImGui.PushStyleColor(colorId, color);\n }\n\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleColor(colors.Count);\n }\n }\n\n /// \n /// Executes an action with a temporary style variable change\n /// \n public static void WithStyleVar(ImGuiStyleVar styleVar, Vector2 value, Action action)\n {\n ImGui.PushStyleVar(styleVar, value);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleVar();\n }\n }\n\n /// \n /// Executes an action with a temporary style variable change\n /// \n public static void WithStyleVar(ImGuiStyleVar styleVar, float value, Action action)\n {\n ImGui.PushStyleVar(styleVar, value);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleVar();\n }\n }\n\n /// \n /// Displays a help marker with a tooltip\n /// \n public static void HelpMarker(string desc)\n {\n ImGui.TextDisabled(\"(?)\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(desc);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n }\n\n /// \n /// Renders an input text field with optional validation\n /// \n public static bool ValidatedInputText(\n string label,\n ref string value,\n uint bufferSize,\n string? tooltip = null,\n Func? validator = null)\n {\n var changed = ImGui.InputText(label, ref value, bufferSize);\n\n // Show tooltip if provided\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n // Validate if changed and validator provided\n if ( changed && validator != null )\n {\n var isValid = validator(value);\n if ( !isValid )\n {\n ImGui.SameLine();\n ImGui.TextColored(new Vector4(1, 0, 0, 1), \"!\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.TextUnformatted(\"Invalid input\");\n ImGui.EndTooltip();\n }\n }\n }\n\n return changed;\n }\n\n /// \n /// Renders an input integer field with optional validation and constraints\n /// \n public static bool ValidatedInputInt(\n string label,\n ref int value,\n string? tooltip = null,\n Func? validator = null,\n int? min = null,\n int? max = null)\n {\n var changed = ImGui.InputInt(label, ref value);\n\n // Apply min/max constraints\n if ( changed )\n {\n if ( min.HasValue && value < min.Value )\n {\n value = min.Value;\n }\n\n if ( max.HasValue && value > max.Value )\n {\n value = max.Value;\n }\n }\n\n // Show tooltip if provided\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n // Validate if changed and validator provided\n if ( changed && validator != null )\n {\n var isValid = validator(value);\n if ( !isValid )\n {\n ImGui.SameLine();\n ImGui.TextColored(new Vector4(1, 0, 0, 1), \"!\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.TextUnformatted(\"Invalid input\");\n ImGui.EndTooltip();\n }\n }\n }\n\n return changed;\n }\n\n /// \n /// Renders a float slider with tooltip and optional animation\n /// \n public static bool TooltipSliderFloat(\n string label,\n ref float value,\n float min,\n float max,\n string format = \"%.3f\",\n string? tooltip = null,\n bool animate = false)\n {\n if ( animate )\n {\n // For animated sliders, use a pulsing accent color\n var time = (float)Math.Sin(ImGui.GetTime() * 2.0f) * 0.5f + 0.5f;\n var color = new Vector4(0.1f, 0.4f + time * 0.2f, 0.8f + time * 0.2f, 1.0f);\n ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.3f, 0.3f, 0.3f, 1.0f));\n ImGui.PushStyleColor(ImGuiCol.SliderGrab, color);\n }\n\n var changed = ImGui.SliderFloat(label, ref value, min, max, format);\n\n if ( animate )\n {\n ImGui.PopStyleColor(2);\n }\n\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n return changed;\n }\n\n /// \n /// Renders a collapsible section header\n /// \n /// \n /// Renders a collapsible section header\n /// \n public static bool SectionHeader(string label, bool defaultOpen = true)\n {\n // Define the style colors\n var styleColors = new List<(ImGuiCol, Vector4)> { (ImGuiCol.Header, new Vector4(0.15f, 0.45f, 0.8f, 0.8f)), (ImGuiCol.HeaderHovered, new Vector4(0.2f, 0.5f, 0.9f, 0.8f)), (ImGuiCol.HeaderActive, new Vector4(0.25f, 0.55f, 0.95f, 0.8f)) };\n\n var flags = defaultOpen ? ImGuiTreeNodeFlags.DefaultOpen : ImGuiTreeNodeFlags.None;\n flags |= ImGuiTreeNodeFlags.Framed;\n flags |= ImGuiTreeNodeFlags.SpanAvailWidth;\n flags |= ImGuiTreeNodeFlags.AllowOverlap;\n flags |= ImGuiTreeNodeFlags.FramePadding;\n\n // Use the WithStyleColors method properly - pass the actual rendering logic in the action\n var opened = false;\n WithStyleColors(styleColors, () => { WithStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 6), () => { opened = ImGui.CollapsingHeader(label, flags); }); });\n\n return opened;\n }\n\n /// \n /// Renders a button with animation effects\n /// \n public static bool AnimatedButton(string label, Vector2 size, bool isActive = false)\n {\n bool clicked;\n if ( isActive )\n {\n // Pulse animation for active button\n var time = (float)Math.Sin(ImGui.GetTime() * 2.0f) * 0.5f + 0.5f;\n var color = new Vector4(0.1f, 0.5f + time * 0.3f, 0.9f, 0.7f + time * 0.3f);\n ImGui.PushStyleColor(ImGuiCol.Button, color);\n ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(color.X, color.Y, color.Z, 1.0f));\n ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(color.X * 1.1f, color.Y * 1.1f, color.Z * 1.1f, 1.0f));\n clicked = ImGui.Button(label, size);\n ImGui.PopStyleColor(3);\n }\n else\n {\n // Default stylish button\n // ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.8f, 0.6f));\n // ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.2f, 0.5f, 0.9f, 0.7f));\n // ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.25f, 0.55f, 0.95f, 0.8f));\n clicked = ImGui.Button(label, size);\n }\n\n return clicked;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SampleSerializer.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Serializer for converting float samples to and from PCM byte buffers.\n/// \n/// \n/// For now, this class only supports 8, 16, 24, 32 and 64 bits per sample.\n/// \npublic static class SampleSerializer\n{\n /// \n /// Deserialize the PCM byte buffer into a new float samples.\n /// \n /// \n public static Memory Deserialize(ReadOnlyMemory buffer, ushort bitsPerSample)\n {\n var floatBuffer = new float[buffer.Length / (bitsPerSample / 8)];\n Deserialize(buffer, floatBuffer, bitsPerSample);\n\n return floatBuffer.AsMemory();\n }\n\n /// \n /// Serializes the float samples into a PCM byte buffer.\n /// \n /// \n public static Memory Serialize(ReadOnlyMemory samples, ushort bitsPerSample)\n {\n // Transform to long as we might overflow the int because of the multiplications (even if we cast to int later)\n var memoryBufferLength = (long)samples.Length * bitsPerSample / 8;\n\n var buffer = new byte[(int)memoryBufferLength];\n Serialize(samples, buffer, bitsPerSample);\n\n return buffer.AsMemory();\n }\n\n /// \n /// Serializes the float samples into a PCM byte buffer.\n /// \n public static void Serialize(ReadOnlyMemory samples, Memory buffer, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n var totalSamples = samples.Length;\n var totalBytes = totalSamples * bytesPerSample;\n\n if ( buffer.Length < totalBytes )\n {\n throw new ArgumentException(\"Buffer too small to hold the serialized data.\");\n }\n\n var samplesSpan = samples.Span;\n var bufferSpan = buffer.Span;\n\n var sampleIndex = 0;\n var bufferIndex = 0;\n\n while ( sampleIndex < totalSamples )\n {\n var sampleValue = samplesSpan[sampleIndex];\n WriteSample(bufferSpan, bufferIndex, sampleValue, bitsPerSample);\n bufferIndex += bytesPerSample;\n sampleIndex++;\n }\n }\n\n /// \n /// Deserializes the PCM byte buffer into float samples.\n /// \n public static void Deserialize(ReadOnlyMemory buffer, Memory samples, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n var totalSamples = buffer.Length / bytesPerSample;\n\n if ( samples.Length < totalSamples )\n {\n throw new ArgumentException(\"Samples buffer is too small to hold the deserialized data.\");\n }\n\n var bufferSpan = buffer.Span;\n var samplesSpan = samples.Span;\n\n var sampleIndex = 0;\n var bufferIndex = 0;\n\n while ( bufferIndex < bufferSpan.Length )\n {\n var sampleValue = ReadSample(bufferSpan, ref bufferIndex, bitsPerSample);\n samplesSpan[sampleIndex++] = sampleValue;\n // bufferIndex is already incremented inside ReadSample\n }\n }\n\n /// \n /// Reads a single sample from the byte span, considering the bit index and sample bit depth.\n /// \n internal static float ReadSample(ReadOnlySpan span, ref int index, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n\n float sampleValue;\n\n switch ( bitsPerSample )\n {\n case 8:\n var sampleByte = span[index];\n sampleValue = sampleByte / 127.5f - 1.0f;\n\n break;\n\n case 16:\n var sampleShort = BinaryPrimitives.ReadInt16LittleEndian(span.Slice(index, 2));\n sampleValue = sampleShort / 32768f;\n\n break;\n\n case 24:\n var sample24Bit = ReadInt24LittleEndian(span.Slice(index, 3));\n sampleValue = sample24Bit / 8388608f;\n\n break;\n\n case 32:\n var sampleInt = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(index, 4));\n sampleValue = sampleInt / 2147483648f;\n\n break;\n\n case 64:\n var sampleLong = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(index, 8));\n sampleValue = sampleLong / 9223372036854775808f;\n\n break;\n\n default:\n throw new NotSupportedException($\"Bits per sample {bitsPerSample} is not supported.\");\n }\n\n index += bytesPerSample;\n\n return sampleValue;\n }\n\n /// \n /// Writes a single sample into the byte span at the specified index.\n /// \n internal static void WriteSample(Span span, int index, float sampleValue, ushort bitsPerSample)\n {\n switch ( bitsPerSample )\n {\n case 8:\n var sampleByte = (byte)((sampleValue + 1.0f) * 127.5f);\n span[index] = sampleByte;\n\n break;\n\n case 16:\n var sampleShort = (short)(sampleValue * 32767f);\n BinaryPrimitives.WriteInt16LittleEndian(span.Slice(index, 2), sampleShort);\n\n break;\n\n case 24:\n var sample24Bit = (int)(sampleValue * 8388607f);\n WriteInt24LittleEndian(span.Slice(index, 3), sample24Bit);\n\n break;\n\n case 32:\n var sampleInt = (int)(sampleValue * 2147483647f);\n BinaryPrimitives.WriteInt32LittleEndian(span.Slice(index, 4), sampleInt);\n\n break;\n\n case 64:\n var sampleLong = (long)(sampleValue * 9223372036854775807f);\n BinaryPrimitives.WriteInt64LittleEndian(span.Slice(index, 8), sampleLong);\n\n break;\n\n default:\n throw new NotSupportedException($\"Bits per sample {bitsPerSample} is not supported.\");\n }\n }\n\n /// \n /// Reads a 24-bit integer from a byte span in little-endian order.\n /// \n private static int ReadInt24LittleEndian(ReadOnlySpan span)\n {\n int b0 = span[0];\n int b1 = span[1];\n int b2 = span[2];\n var sample = (b2 << 16) | (b1 << 8) | b0;\n\n // Sign-extend to 32 bits if necessary\n if ( (sample & 0x800000) != 0 )\n {\n sample |= unchecked((int)0xFF000000);\n }\n\n return sample;\n }\n\n /// \n /// Writes a 24-bit integer to a byte span in little-endian order.\n /// \n private static void WriteInt24LittleEndian(Span span, int value)\n {\n span[0] = (byte)(value & 0xFF);\n span[1] = (byte)((value >> 8) & 0xFF);\n span[2] = (byte)((value >> 16) & 0xFF);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionQueueEntry.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\npublic class CubismMotionQueueEntry\n{\n public CubismMotionQueueEntry()\n {\n Available = true;\n StartTime = -1.0f;\n EndTime = -1.0f;\n }\n\n /// \n /// Motion\n /// \n public required ACubismMotion Motion { get; set; }\n\n /// \n /// Activation flag\n /// \n public bool Available { get; set; }\n\n /// \n /// Completion flag\n /// \n public bool Finished { get; set; }\n\n /// \n /// Start flag (since 0.9.00)\n /// \n public bool Started { get; set; }\n\n /// \n /// Motion playback start time [seconds]\n /// \n public float StartTime { get; set; }\n\n /// \n /// Fade-in start time (only the first time for loops) [seconds]\n /// \n public float FadeInStartTime { get; set; }\n\n /// \n /// Scheduled end time [seconds]\n /// \n public float EndTime { get; set; }\n\n /// \n /// Time state [seconds]\n /// \n public float StateTime { get; private set; }\n\n /// \n /// Weight state\n /// \n public float StateWeight { get; private set; }\n\n /// \n /// Last time checked by the Motion side\n /// \n public float LastEventCheckSeconds { get; set; }\n\n public float FadeOutSeconds { get; private set; }\n\n public bool IsTriggeredFadeOut { get; private set; }\n\n /// \n /// Set the start of fade-out.\n /// \n /// Time required for fade-out [seconds]\n public void SetFadeout(float fadeOutSeconds)\n {\n FadeOutSeconds = fadeOutSeconds;\n IsTriggeredFadeOut = true;\n }\n\n /// \n /// Start fade-out.\n /// \n /// Time required for fade-out [seconds]\n /// Accumulated delta time [seconds]\n public void StartFadeout(float fadeOutSeconds, float userTimeSeconds)\n {\n var newEndTimeSeconds = userTimeSeconds + fadeOutSeconds;\n IsTriggeredFadeOut = true;\n\n if ( EndTime < 0.0f || newEndTimeSeconds < EndTime )\n {\n EndTime = newEndTimeSeconds;\n }\n }\n\n /// \n /// Set the motion state.\n /// \n /// Current time [seconds]\n /// Motion weight\n public void SetState(float timeSeconds, float weight)\n {\n StateTime = timeSeconds;\n StateWeight = weight;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MergedMemoryChunks.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// This is a little helper for using multiple chunks of memory without writing it to auxiliary buffers\n/// \n/// \n/// It is used to consume the data that was appended in multiple calls and couldn't be used previously.\n/// Note: If the requested chunks are not contiguous, the data will be copied to a new buffer.\n/// \npublic class MergedMemoryChunks\n{\n private readonly List> chunks = [];\n\n private int currentChunkIndex;\n\n public MergedMemoryChunks(ReadOnlyMemory initialChunk)\n {\n chunks.Add(initialChunk);\n Length = initialChunk.Length;\n }\n\n public MergedMemoryChunks() { }\n\n /// \n /// The total length of the chunks\n /// \n public long Length { get; private set; }\n\n /// \n /// The current position in the chunks\n /// \n public long Position { get; private set; }\n\n /// \n /// The absolute position of the current chunk\n /// \n public long AbsolutePositionOfCurrentChunk { get; private set; }\n\n public void AddChunk(ReadOnlyMemory newChunk)\n {\n chunks.Add(newChunk);\n Length += newChunk.Length;\n }\n\n /// \n /// Tries to skip the given number of bytes in the chunks, advancing the position.\n /// \n public bool TrySkip(uint count)\n {\n var bytesToSkip = count;\n while ( bytesToSkip > 0 )\n {\n var positionInCurrentChunk = Position - AbsolutePositionOfCurrentChunk;\n var currentChunk = chunks[currentChunkIndex];\n if ( positionInCurrentChunk + bytesToSkip <= currentChunk.Length )\n {\n Position += bytesToSkip;\n\n return true;\n }\n\n if ( currentChunkIndex + 1 == chunks.Count )\n {\n return false;\n }\n\n var remainingInCurrentChunk = (int)(currentChunk.Length - positionInCurrentChunk);\n\n currentChunkIndex++;\n\n Position += remainingInCurrentChunk;\n AbsolutePositionOfCurrentChunk = Position;\n bytesToSkip -= (uint)remainingInCurrentChunk;\n }\n\n return true;\n }\n\n /// \n /// Restarts the reading from the beginning of the chunks\n /// \n public void RestartRead()\n {\n currentChunkIndex = 0;\n AbsolutePositionOfCurrentChunk = 0;\n Position = 0;\n }\n\n /// \n /// Gets a slice of the given size from the chunks\n /// \n /// \n /// If the data will span multiple chunks, it will be copied to a new buffer.\n /// \n public ReadOnlyMemory GetChunk(int size)\n {\n var positionInCurrentChunk = (int)(Position - AbsolutePositionOfCurrentChunk);\n var currentChunk = chunks[currentChunkIndex];\n // First, we try to just slice the current chunk if possible\n if ( currentChunk.Length >= positionInCurrentChunk + size )\n {\n Position += size;\n if ( currentChunk.Length == positionInCurrentChunk + size )\n {\n currentChunkIndex++;\n AbsolutePositionOfCurrentChunk = Position;\n }\n\n return currentChunk.Slice(positionInCurrentChunk, size);\n }\n\n // We cannot slice it, so we need to compose it\n var buffer = new byte[size];\n var bufferIndex = 0;\n var remainingSize = size;\n while ( remainingSize > 0 )\n {\n var currentChunkAddressable = currentChunk.Slice(positionInCurrentChunk, Math.Min(remainingSize, currentChunk.Length - positionInCurrentChunk));\n\n remainingSize -= currentChunkAddressable.Length;\n Position += currentChunkAddressable.Length;\n currentChunkAddressable.CopyTo(buffer.AsMemory(bufferIndex));\n bufferIndex += currentChunkAddressable.Length;\n if ( remainingSize > 0 && currentChunkIndex >= chunks.Count )\n {\n throw new InvalidOperationException($\"Not enough data was available in the chunks to read {size} bytes.\");\n }\n\n if ( remainingSize > 0 )\n {\n positionInCurrentChunk = 0;\n currentChunkIndex++;\n AbsolutePositionOfCurrentChunk = Position;\n currentChunk = chunks[currentChunkIndex];\n }\n }\n\n return buffer.AsMemory();\n }\n\n /// \n /// Reads a 32-bit unsigned integer from the chunks\n /// \n public uint ReadUInt32LittleEndian()\n {\n var chunk = GetChunk(4);\n\n return BinaryPrimitives.ReadUInt32LittleEndian(chunk.Span);\n }\n\n /// \n /// Reads a 16-bit unsigned integer from the chunks\n /// \n public ushort ReadUInt16LittleEndian()\n {\n var chunk = GetChunk(2);\n\n return BinaryPrimitives.ReadUInt16LittleEndian(chunk.Span);\n }\n\n /// \n /// Reads a 8-bit unsigned integer from the chunks\n /// \n /// \n /// \n public byte ReadByte()\n {\n var chunk = GetChunk(1);\n\n return chunk.Span[0];\n }\n\n public short ReadInt16LittleEndian()\n {\n var chunk = GetChunk(2);\n\n return BinaryPrimitives.ReadInt16LittleEndian(chunk.Span);\n }\n\n public int ReadInt24LittleEndian()\n {\n var chunk = GetChunk(3);\n\n return chunk.Span[0] | (chunk.Span[1] << 8) | (chunk.Span[2] << 16);\n }\n\n public int ReadInt32LittleEndian()\n {\n var chunk = GetChunk(4);\n\n return BinaryPrimitives.ReadInt32LittleEndian(chunk.Span);\n }\n\n public long ReadInt64LittleEndian()\n {\n var chunk = GetChunk(8);\n\n return BinaryPrimitives.ReadInt64LittleEndian(chunk.Span);\n }\n\n /// \n /// Copies the content of the current chunks to a single buffer\n /// \n /// \n public byte[] ToArray()\n {\n var buffer = new byte[Length];\n var bufferIndex = 0;\n foreach ( var chunk in chunks )\n {\n chunk.Span.CopyTo(buffer.AsSpan(bufferIndex));\n bufferIndex += chunk.Length;\n }\n\n return buffer;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismMoc.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// Mocデータの管理を行うクラス。\n/// \npublic class CubismMoc : IDisposable\n{\n /// \n /// Mocデータ\n /// \n private readonly IntPtr _moc;\n\n /// \n /// バッファからMocファイルを読み取り、Mocデータを作成する。\n /// \n /// Mocファイルのバッファ\n /// MOCの整合性チェックフラグ(初期値 : false)\n /// \n public CubismMoc(byte[] mocBytes, bool shouldCheckMocConsistency = false)\n {\n var alignedBuffer = CubismFramework.AllocateAligned(mocBytes.Length, CsmEnum.csmAlignofMoc);\n Marshal.Copy(mocBytes, 0, alignedBuffer, mocBytes.Length);\n\n if ( shouldCheckMocConsistency )\n {\n // .moc3の整合性を確認\n var consistency = HasMocConsistency(alignedBuffer, mocBytes.Length);\n if ( !consistency )\n {\n CubismFramework.DeallocateAligned(alignedBuffer);\n\n // 整合性が確認できなければ処理しない\n throw new Exception(\"Inconsistent MOC3.\");\n }\n }\n\n var moc = CubismCore.ReviveMocInPlace(alignedBuffer, mocBytes.Length);\n\n if ( moc == IntPtr.Zero )\n {\n throw new Exception(\"MOC3 is null\");\n }\n\n _moc = moc;\n\n MocVersion = CubismCore.GetMocVersion(alignedBuffer, mocBytes.Length);\n\n var modelSize = CubismCore.GetSizeofModel(_moc);\n var modelMemory = CubismFramework.AllocateAligned(modelSize, CsmEnum.CsmAlignofModel);\n\n var model = CubismCore.InitializeModelInPlace(_moc, modelMemory, modelSize);\n\n if ( model == IntPtr.Zero )\n {\n throw new Exception(\"MODEL is null\");\n }\n\n Model = new CubismModel(model);\n }\n\n /// \n /// 読み込んだモデルの.moc3 Version\n /// \n public uint MocVersion { get; }\n\n public CubismModel Model { get; }\n\n /// \n /// デストラクタ。\n /// \n public void Dispose()\n {\n Model.Dispose();\n CubismFramework.DeallocateAligned(_moc);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// 最新の.moc3 Versionを取得する。\n /// \n /// \n public static uint GetLatestMocVersion() { return CubismCore.GetLatestMocVersion(); }\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// '1' if Moc is valid; '0' otherwise.\n public static bool HasMocConsistency(IntPtr address, int size) { return CubismCore.HasMocConsistency(address, size); }\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Mocファイルのバッファ\n /// バッファのサイズ\n /// 'true' if Moc is valid; 'false' otherwise.\n public static bool HasMocConsistencyFromUnrevivedMoc(byte[] data)\n {\n var alignedBuffer = CubismFramework.AllocateAligned(data.Length, CsmEnum.csmAlignofMoc);\n Marshal.Copy(data, 0, alignedBuffer, data.Length);\n\n var consistency = HasMocConsistency(alignedBuffer, data.Length);\n\n CubismFramework.DeallocateAligned(alignedBuffer);\n\n return consistency;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AwaitableWaveFileSource.cs", "using PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Similar with allows writing data from a wave file instead of writing the\n/// samples directly.\n/// \n/// \n/// Important: This should be used at most by one writer and one reader.\n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class AwaitableWaveFileSource(\n IReadOnlyDictionary metadata,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = BufferedMemoryAudioSource.DefaultInitialSize,\n int initialSizeBytes = BufferedMemoryAudioSource.DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : AwaitableAudioSource(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy)\n{\n private MergedMemoryChunks? headerChunks;\n\n private MergedMemoryChunks? sampleDataChunks;\n\n public void WriteData(ReadOnlyMemory data)\n {\n if ( IsFlushed )\n {\n throw new InvalidOperationException(\"Cannot write to flushed stream.\");\n }\n\n // We need the dataOffset in case the data contains both header and samples\n var dataOffset = 0;\n if ( !IsInitialized )\n {\n if ( headerChunks == null )\n {\n headerChunks = new MergedMemoryChunks(data);\n }\n else\n {\n headerChunks.AddChunk(data);\n }\n\n var headerParseResult = WaveFileUtils.ParseHeader(headerChunks);\n if ( headerParseResult.IsIncomplete )\n {\n // Need more data for header\n // We need to copy the last chunk as we'll keep it for the next iteration\n headerChunks = new MergedMemoryChunks(headerChunks.ToArray());\n\n return;\n }\n\n if ( headerParseResult.IsCorrupt )\n {\n throw new InvalidOperationException(headerParseResult.ErrorMessage);\n }\n\n if ( !headerParseResult.IsSuccess || headerParseResult.Header == null )\n {\n throw new NotSupportedException(headerParseResult.ErrorMessage);\n }\n\n base.Initialize(headerParseResult.Header);\n dataOffset = headerParseResult.DataOffset;\n }\n\n // Now process sample data\n var sampleData = dataOffset == 0 ? data : data.Slice(dataOffset);\n lock (syncRoot)\n {\n ProcessSamples(sampleData);\n }\n\n NotifyNewSamples();\n }\n\n private void ProcessSamples(ReadOnlyMemory sampleData)\n {\n if ( sampleDataChunks != null )\n {\n sampleDataChunks.AddChunk(sampleData);\n }\n else\n {\n sampleDataChunks = new MergedMemoryChunks(sampleData);\n }\n\n // Calculate how many complete frames we can process\n var framesToProcess = sampleDataChunks.Length / FrameSize;\n\n if ( framesToProcess == 0 )\n {\n // Not enough data to process even a single frame, wait for more data\n return;\n }\n\n for ( var frameIndex = 0; frameIndex < framesToProcess; frameIndex++ )\n {\n var frame = sampleDataChunks.GetChunk(FrameSize);\n AddFrame(frame);\n }\n\n // After processing, check if there are remaining bytes and store them for the next iteration\n // We need to copy the memory (with ToArray()) as otherwise, it might be overriden by the new chunk.\n sampleDataChunks = sampleDataChunks.Length > sampleDataChunks.Position\n ? new MergedMemoryChunks(sampleDataChunks.GetChunk((int)(sampleDataChunks.Length - sampleDataChunks.Position)).ToArray().AsMemory())\n : null;\n }\n\n protected override void Dispose(bool disposing)\n {\n headerChunks = null;\n sampleDataChunks = null;\n base.Dispose(disposing);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismRenderer.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// モデル描画を処理するレンダラ\n/// サブクラスに環境依存の描画命令を記述する\n/// \npublic abstract class CubismRenderer : IDisposable\n{\n /// \n /// Model-View-Projection 行列\n /// \n private readonly CubismMatrix44 _mvpMatrix4x4 = new();\n\n public CubismTextureColor ClearColor = new(0, 0, 0, 0);\n\n /// \n /// モデル自体のカラー(RGBA)\n /// \n public CubismTextureColor ModelColor = new();\n\n /// \n /// レンダラのインスタンスを生成して取得する\n /// \n public CubismRenderer(CubismModel model)\n {\n _mvpMatrix4x4.LoadIdentity();\n Model = model ?? throw new Exception(\"model is null\");\n }\n\n /// \n /// テクスチャの異方性フィルタリングのパラメータ\n /// \n public float Anisotropy { get; set; }\n\n /// \n /// レンダリング対象のモデル\n /// \n public CubismModel Model { get; private set; }\n\n /// \n /// 乗算済みαならtrue\n /// \n public bool IsPremultipliedAlpha { get; set; }\n\n /// \n /// カリングが有効ならtrue\n /// \n public bool IsCulling { get; set; }\n\n /// \n /// falseの場合、マスクを纏めて描画する trueの場合、マスクはパーツ描画ごとに書き直す\n /// \n public bool UseHighPrecisionMask { get; set; }\n\n /// \n /// レンダラのインスタンスを解放する\n /// \n public abstract void Dispose();\n\n /// \n /// モデルを描画する\n /// \n public void DrawModel()\n {\n /**\n * DoDrawModelの描画前と描画後に以下の関数を呼んでください。\n * ・SaveProfile();\n * ・RestoreProfile();\n * これはレンダラの描画設定を保存・復帰させることで、\n * モデル描画直前の状態に戻すための処理です。\n */\n\n SaveProfile();\n\n DoDrawModel();\n\n RestoreProfile();\n }\n\n /// \n /// Model-View-Projection 行列をセットする\n /// 配列は複製されるので元の配列は外で破棄して良い\n /// \n /// Model-View-Projection 行列\n public void SetMvpMatrix(CubismMatrix44 matrix4x4) { _mvpMatrix4x4.SetMatrix(matrix4x4.Tr); }\n\n /// \n /// Model-View-Projection 行列を取得する\n /// \n /// Model-View-Projection 行列\n public CubismMatrix44 GetMvpMatrix() { return _mvpMatrix4x4; }\n\n /// \n /// 透明度を考慮したモデルの色を計算する。\n /// \n /// 透明度\n /// RGBAのカラー情報\n public CubismTextureColor GetModelColorWithOpacity(float opacity)\n {\n CubismTextureColor modelColorRGBA = new(ModelColor);\n modelColorRGBA.A *= opacity;\n if ( IsPremultipliedAlpha )\n {\n modelColorRGBA.R *= modelColorRGBA.A;\n modelColorRGBA.G *= modelColorRGBA.A;\n modelColorRGBA.B *= modelColorRGBA.A;\n }\n\n return modelColorRGBA;\n }\n\n /// \n /// モデルの色をセットする。\n /// 各色0.0f~1.0fの間で指定する(1.0fが標準の状態)。\n /// \n /// 赤チャンネルの値\n /// 緑チャンネルの値\n /// 青チャンネルの値\n /// αチャンネルの値\n public void SetModelColor(float red, float green, float blue, float alpha)\n {\n if ( red < 0.0f )\n {\n red = 0.0f;\n }\n else if ( red > 1.0f )\n {\n red = 1.0f;\n }\n\n if ( green < 0.0f )\n {\n green = 0.0f;\n }\n else if ( green > 1.0f )\n {\n green = 1.0f;\n }\n\n if ( blue < 0.0f )\n {\n blue = 0.0f;\n }\n else if ( blue > 1.0f )\n {\n blue = 1.0f;\n }\n\n if ( alpha < 0.0f )\n {\n alpha = 0.0f;\n }\n else if ( alpha > 1.0f )\n {\n alpha = 1.0f;\n }\n\n ModelColor.R = red;\n ModelColor.G = green;\n ModelColor.B = blue;\n ModelColor.A = alpha;\n }\n\n /// \n /// モデル描画の実装\n /// \n protected abstract void DoDrawModel();\n\n /// \n /// 描画オブジェクト(アートメッシュ)を描画する。\n /// ポリゴンメッシュとテクスチャ番号をセットで渡す。\n /// \n /// 描画するテクスチャ番号\n /// 描画オブジェクトのインデックス値\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュ頂点のインデックス配列\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 不透明度\n /// カラーブレンディングのタイプ\n /// マスク使用時のマスクの反転使用\n internal abstract unsafe void DrawMesh(int textureNo, int indexCount, int vertexCount\n , ushort* indexArray, float* vertexArray, float* uvArray\n , float opacity, CubismBlendMode colorBlendMode, bool invertedMask);\n\n /// \n /// モデル描画直前のレンダラのステートを保持する\n /// \n protected abstract void SaveProfile();\n\n /// \n /// モデル描画直前のレンダラのステートを復帰させる\n /// \n protected abstract void RestoreProfile();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppView.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 描画クラス\n/// \n/// \n/// コンストラクタ\n/// \npublic class LAppView(LAppDelegate lapp)\n{\n /// \n /// デバイスからスクリーンへの行列\n /// \n private readonly CubismMatrix44 _deviceToScreen = new();\n\n /// \n /// タッチマネージャー\n /// \n private readonly TouchManager _touchManager = new();\n\n /// \n /// viewMatrix\n /// \n private readonly CubismViewMatrix _viewMatrix = new();\n\n /// \n /// 初期化する。\n /// \n public void Initialize()\n {\n lapp.GL.GetWindowSize(out var width, out var height);\n\n if ( width == 0 || height == 0 )\n {\n return;\n }\n\n // 縦サイズを基準とする\n var ratio = (float)width / height;\n var left = -ratio;\n var right = ratio;\n var bottom = LAppDefine.ViewLogicalLeft;\n var top = LAppDefine.ViewLogicalRight;\n\n _viewMatrix.SetScreenRect(left, right, bottom, top); // デバイスに対応する画面の範囲。 Xの左端, Xの右端, Yの下端, Yの上端\n _viewMatrix.Scale(LAppDefine.ViewScale, LAppDefine.ViewScale);\n\n _deviceToScreen.LoadIdentity(); // サイズが変わった際などリセット必須\n if ( width > height )\n {\n var screenW = MathF.Abs(right - left);\n _deviceToScreen.ScaleRelative(screenW / width, -screenW / width);\n }\n else\n {\n var screenH = MathF.Abs(top - bottom);\n _deviceToScreen.ScaleRelative(screenH / height, -screenH / height);\n }\n\n _deviceToScreen.TranslateRelative(-width * 0.5f, -height * 0.5f);\n\n // 表示範囲の設定\n _viewMatrix.MaxScale = LAppDefine.ViewMaxScale; // 限界拡大率\n _viewMatrix.MinScale = LAppDefine.ViewMinScale; // 限界縮小率\n\n // 表示できる最大範囲\n _viewMatrix.SetMaxScreenRect(\n LAppDefine.ViewLogicalMaxLeft,\n LAppDefine.ViewLogicalMaxRight,\n LAppDefine.ViewLogicalMaxBottom,\n LAppDefine.ViewLogicalMaxTop\n );\n }\n\n /// \n /// 描画する。\n /// \n public void Render()\n {\n var Live2DManager = lapp.Live2dManager;\n Live2DManager.ViewMatrix.SetMatrix(_viewMatrix);\n\n // Cubism更新・描画\n Live2DManager.OnUpdate();\n }\n\n /// \n /// タッチされたときに呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesBegan(float pointX, float pointY)\n {\n _touchManager.TouchesBegan(pointX, pointY);\n CubismLog.Debug($\"[Live2D]touchesBegan x:{pointX:#.##} y:{pointY:#.##}\");\n }\n\n /// \n /// タッチしているときにポインタが動いたら呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesMoved(float pointX, float pointY)\n {\n var viewX = TransformViewX(_touchManager.GetX());\n var viewY = TransformViewY(_touchManager.GetY());\n\n _touchManager.TouchesMoved(pointX, pointY);\n\n lapp.Live2dManager.OnDrag(viewX, viewY);\n }\n\n /// \n /// タッチが終了したら呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesEnded(float _, float __)\n {\n // タッチ終了\n var live2DManager = lapp.Live2dManager;\n live2DManager.OnDrag(0.0f, 0.0f);\n // シングルタップ\n var x = _deviceToScreen.TransformX(_touchManager.GetX()); // 論理座標変換した座標を取得。\n var y = _deviceToScreen.TransformY(_touchManager.GetY()); // 論理座標変換した座標を取得。\n CubismLog.Debug($\"[Live2D]touchesEnded x:{x:#.##} y:{y:#.##}\");\n live2DManager.OnTap(x, y);\n }\n\n /// \n /// X座標をView座標に変換する。\n /// \n /// デバイスX座標\n public float TransformViewX(float deviceX)\n {\n var screenX = _deviceToScreen.TransformX(deviceX); // 論理座標変換した座標を取得。\n\n return _viewMatrix.InvertTransformX(screenX); // 拡大、縮小、移動後の値。\n }\n\n /// \n /// Y座標をView座標に変換する。\n /// \n /// デバイスY座標\n public float TransformViewY(float deviceY)\n {\n var screenY = _deviceToScreen.TransformY(deviceY); // 論理座標変換した座標を取得。\n\n return _viewMatrix.InvertTransformY(screenY); // 拡大、縮小、移動後の値。\n }\n\n /// \n /// X座標をScreen座標に変換する。\n /// \n /// デバイスX座標\n public float TransformScreenX(float deviceX) { return _deviceToScreen.TransformX(deviceX); }\n\n /// \n /// Y座標をScreen座標に変換する。\n /// \n /// デバイスY座標\n public float TransformScreenY(float deviceY) { return _deviceToScreen.TransformY(deviceY); }\n\n /// \n /// 別レンダリングターゲットにモデルを描画するサンプルで\n /// 描画時のαを決定する\n /// \n public static float GetSpriteAlpha(int assign)\n {\n // assignの数値に応じて適当に決定\n var alpha = 0.25f + assign * 0.5f; // サンプルとしてαに適当な差をつける\n if ( alpha > 1.0f )\n {\n alpha = 1.0f;\n }\n\n if ( alpha < 0.1f )\n {\n alpha = 0.1f;\n }\n\n return alpha;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismModelMatrix.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// モデル座標設定用の4x4行列クラス。\n/// \npublic record CubismModelMatrix : CubismMatrix44\n{\n public const string KeyWidth = \"width\";\n\n public const string KeyHeight = \"height\";\n\n public const string KeyX = \"x\";\n\n public const string KeyY = \"y\";\n\n public const string KeyCenterX = \"center_x\";\n\n public const string KeyCenterY = \"center_y\";\n\n public const string KeyTop = \"top\";\n\n public const string KeyBottom = \"bottom\";\n\n public const string KeyLeft = \"left\";\n\n public const string KeyRight = \"right\";\n\n /// \n /// 縦幅\n /// \n private readonly float _height;\n\n /// \n /// 横幅\n /// \n private readonly float _width;\n\n public CubismModelMatrix(float w, float h)\n {\n _width = w;\n _height = h;\n\n SetHeight(2.0f);\n }\n\n /// \n /// 横幅を設定する。\n /// \n /// 横幅\n public void SetWidth(float w)\n {\n var scaleX = w / _width;\n var scaleY = scaleX;\n Scale(scaleX, scaleY);\n }\n\n /// \n /// 縦幅を設定する。\n /// \n /// 縦幅\n public void SetHeight(float h)\n {\n var scaleX = h / _height;\n var scaleY = scaleX;\n Scale(scaleX, scaleY);\n }\n\n /// \n /// 位置を設定する。\n /// \n /// X軸の位置\n /// Y軸の位置\n public void SetPosition(float x, float y) { Translate(x, y); }\n\n /// \n /// 中心位置を設定する。\n /// \n /// X軸の中心位置\n /// Y軸の中心位置\n public void SetCenterPosition(float x, float y)\n {\n CenterX(x);\n CenterY(y);\n }\n\n /// \n /// 上辺の位置を設定する。\n /// \n /// 上辺のY軸位置\n public void Top(float y) { SetY(y); }\n\n /// \n /// 下辺の位置を設定する。\n /// \n /// 下辺のY軸位置\n public void Bottom(float y)\n {\n var h = _height * GetScaleY();\n TranslateY(y - h);\n }\n\n /// \n /// 左辺の位置を設定する。\n /// \n /// 左辺のX軸位置\n public void Left(float x) { SetX(x); }\n\n /// \n /// 右辺の位置を設定する。\n /// \n /// 右辺のX軸位置\n public void Right(float x)\n {\n var w = _width * GetScaleX();\n TranslateX(x - w);\n }\n\n /// \n /// X軸の中心位置を設定する。\n /// \n /// X軸の中心位置\n public void CenterX(float x)\n {\n var w = _width * GetScaleX();\n TranslateX(x - w / 2.0f);\n }\n\n /// \n /// X軸の位置を設定する。\n /// \n /// X軸の位置\n public void SetX(float x) { TranslateX(x); }\n\n /// \n /// Y軸の中心位置を設定する。\n /// \n /// Y軸の中心位置\n public void CenterY(float y)\n {\n var h = _height * GetScaleY();\n TranslateY(y - h / 2.0f);\n }\n\n /// \n /// Y軸の位置を設定する。\n /// \n /// Y軸の位置\n public void SetY(float y) { TranslateY(y); }\n\n /// \n /// レイアウト情報から位置を設定する。\n /// \n /// レイアウト情報\n public void SetupFromLayout(Dictionary layout)\n {\n foreach ( var item in layout )\n {\n if ( item.Key == KeyWidth )\n {\n SetWidth(item.Value);\n }\n else if ( item.Key == KeyHeight )\n {\n SetHeight(item.Value);\n }\n }\n\n foreach ( var item in layout )\n {\n if ( item.Key == KeyX )\n {\n SetX(item.Value);\n }\n else if ( item.Key == KeyY )\n {\n SetY(item.Value);\n }\n else if ( item.Key == KeyCenterX )\n {\n CenterX(item.Value);\n }\n else if ( item.Key == KeyCenterY )\n {\n CenterY(item.Value);\n }\n else if ( item.Key == KeyTop )\n {\n Top(item.Value);\n }\n else if ( item.Key == KeyBottom )\n {\n Bottom(item.Value);\n }\n else if ( item.Key == KeyLeft )\n {\n Left(item.Value);\n }\n else if ( item.Key == KeyRight )\n {\n Right(item.Value);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Num2Words.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class Num2Words\n{\n private static readonly string[] _units = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n private static readonly string[] _tens = { \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n private static readonly string[] _ordinalUnits = { \"zeroth\", \"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", \"seventh\", \"eighth\", \"ninth\", \"tenth\", \"eleventh\", \"twelfth\", \"thirteenth\", \"fourteenth\", \"fifteenth\", \"sixteenth\", \"seventeenth\", \"eighteenth\", \"nineteenth\" };\n\n private static readonly string[] _ordinalTens = { \"\", \"\", \"twentieth\", \"thirtieth\", \"fortieth\", \"fiftieth\", \"sixtieth\", \"seventieth\", \"eightieth\", \"ninetieth\" };\n\n public static string Convert(int number, string to = \"cardinal\")\n {\n if ( number == 0 )\n {\n return _units[0];\n }\n\n if ( number < 0 )\n {\n return \"negative \" + Convert(-number, to);\n }\n\n return to.ToLower() switch {\n \"ordinal\" => ConvertToOrdinal(number),\n \"year\" => ConvertToYear(number),\n _ => ConvertToCardinal(number)\n };\n }\n\n public static string Convert(double number)\n {\n // Handle integer part\n var intPart = (int)Math.Floor(number);\n var result = ConvertToCardinal(intPart);\n\n // Handle decimal part\n var decimalPart = number - intPart;\n if ( decimalPart > 0 )\n {\n // Get decimal digits as string and remove trailing zeros\n var decimalString = decimalPart.ToString(\"F20\", CultureInfo.InvariantCulture)\n .TrimStart('0', '.')\n .TrimEnd('0');\n\n if ( !string.IsNullOrEmpty(decimalString) )\n {\n result += \" point\";\n foreach ( var digit in decimalString )\n {\n result += \" \" + _units[int.Parse(digit.ToString())];\n }\n }\n }\n\n return result;\n }\n\n private static string ConvertToCardinal(int number)\n {\n if ( number < 20 )\n {\n return _units[number];\n }\n\n if ( number < 100 )\n {\n return _tens[number / 10] + (number % 10 > 0 ? \"-\" + _units[number % 10] : \"\");\n }\n\n if ( number < 1000 )\n {\n return _units[number / 100] + \" hundred\" + (number % 100 > 0 ? \" and \" + ConvertToCardinal(number % 100) : \"\");\n }\n\n if ( number < 1000000 )\n {\n var thousands = number / 1000;\n var remainder = number % 1000;\n\n var result = ConvertToCardinal(thousands) + \" thousand\";\n\n if ( remainder > 0 )\n {\n // If remainder is less than 100, or if it has a tens/units part\n if ( remainder < 100 )\n {\n result += \" and \" + ConvertToCardinal(remainder);\n }\n else\n {\n // For numbers like 1,234 -> \"one thousand two hundred and thirty-four\"\n var hundreds = remainder / 100;\n var tensAndUnits = remainder % 100;\n\n result += \" \" + _units[hundreds] + \" hundred\";\n if ( tensAndUnits > 0 )\n {\n result += \" and \" + ConvertToCardinal(tensAndUnits);\n }\n }\n }\n\n return result;\n }\n\n if ( number < 1000000000 )\n {\n return ConvertToCardinal(number / 1000000) + \" million\" + (number % 1000000 > 0 ? (number % 1000000 < 100 ? \" and \" : \" \") + ConvertToCardinal(number % 1000000) : \"\");\n }\n\n return ConvertToCardinal(number / 1000000000) + \" billion\" + (number % 1000000000 > 0 ? (number % 1000000000 < 100 ? \" and \" : \" \") + ConvertToCardinal(number % 1000000000) : \"\");\n }\n\n private static string ConvertToOrdinal(int number)\n {\n if ( number < 20 )\n {\n return _ordinalUnits[number];\n }\n\n if ( number < 100 )\n {\n if ( number % 10 == 0 )\n {\n return _ordinalTens[number / 10];\n }\n\n return _tens[number / 10] + \"-\" + _ordinalUnits[number % 10];\n }\n\n var cardinal = ConvertToCardinal(number);\n\n // Replace the last word with its ordinal form\n var lastSpace = cardinal.LastIndexOf(' ');\n if ( lastSpace == -1 )\n {\n // Single word\n var lastWord = cardinal;\n if ( lastWord.EndsWith(\"y\") )\n {\n return lastWord.Substring(0, lastWord.Length - 1) + \"ieth\";\n }\n\n if ( lastWord.EndsWith(\"eight\") )\n {\n return lastWord + \"h\";\n }\n\n if ( lastWord.EndsWith(\"nine\") )\n {\n return lastWord + \"th\";\n }\n\n return lastWord + \"th\";\n }\n else\n {\n // Multiple words\n var lastWord = cardinal.Substring(lastSpace + 1);\n var prefix = cardinal.Substring(0, lastSpace + 1);\n\n if ( lastWord.EndsWith(\"y\") )\n {\n return prefix + lastWord.Substring(0, lastWord.Length - 1) + \"ieth\";\n }\n\n if ( lastWord == \"one\" )\n {\n return prefix + \"first\";\n }\n\n if ( lastWord == \"two\" )\n {\n return prefix + \"second\";\n }\n\n if ( lastWord == \"three\" )\n {\n return prefix + \"third\";\n }\n\n if ( lastWord == \"five\" )\n {\n return prefix + \"fifth\";\n }\n\n if ( lastWord == \"eight\" )\n {\n return prefix + \"eighth\";\n }\n\n if ( lastWord == \"nine\" || lastWord == \"twelve\" )\n {\n return prefix + lastWord + \"th\";\n }\n\n return prefix + lastWord + \"th\";\n }\n }\n\n private static string ConvertToYear(int year)\n {\n // Handle years specially\n if ( year >= 2000 )\n {\n // 2xxx is \"two thousand [and] xxx\"\n var remainder = year - 2000;\n if ( remainder == 0 )\n {\n return \"two thousand\";\n }\n\n if ( remainder < 100 )\n {\n return \"two thousand and \" + ConvertToCardinal(remainder);\n }\n\n return \"two thousand \" + ConvertToCardinal(remainder);\n }\n\n if ( year >= 1000 )\n {\n // Years like 1984 are \"nineteen eighty-four\"\n var century = year / 100;\n var remainder = year % 100;\n\n if ( remainder == 0 )\n {\n return ConvertToCardinal(century) + \" hundred\";\n }\n\n return ConvertToCardinal(century) + \" \" + ConvertToCardinal(remainder);\n }\n\n // Years less than 1000\n return ConvertToCardinal(year);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AwaitableAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that can be awaited for audio data.\n/// \n/// \n/// Important: This should be used at most by one writer and one reader.\n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class AwaitableAudioSource(\n IReadOnlyDictionary metadata,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = BufferedMemoryAudioSource.DefaultInitialSize,\n int initialSizeBytes = BufferedMemoryAudioSource.DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : DiscardableMemoryAudioSource(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy), IAwaitableAudioSource\n{\n private readonly TaskCompletionSource initializationTcs = new();\n\n private readonly AsyncAutoResetEvent samplesAvailableEvent = new();\n\n protected readonly Lock syncRoot = new();\n\n /// \n /// Gets a value indicating whether the source is flushed.\n /// \n public bool IsFlushed { get; private set; }\n\n public override Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n lock (syncRoot)\n {\n // Calling the base method with lock is fine here, as the base method will not await anything.\n return base.GetFramesAsync(startFrame, maxFrames, cancellationToken);\n }\n }\n\n public override Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n lock (syncRoot)\n {\n // Calling the base method with lock is fine here, as the base method will not await anything.\n return base.CopyFramesAsync(destination, startFrame, maxFrames, cancellationToken);\n }\n }\n\n public override Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n lock (syncRoot)\n {\n // Calling the base method with lock is fine here, as the base method will not await anything.\n return base.GetSamplesAsync(startFrame, maxFrames, cancellationToken);\n }\n }\n\n /// \n public async Task WaitForNewSamplesAsync(long sampleCount, CancellationToken cancellationToken)\n {\n while ( !IsFlushed && SampleVirtualCount <= sampleCount )\n {\n await samplesAvailableEvent.WaitAsync().WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n }\n\n public async Task WaitForNewSamplesAsync(TimeSpan minimumDuration, CancellationToken cancellationToken)\n {\n while ( !IsFlushed && Duration <= minimumDuration )\n {\n await samplesAvailableEvent.WaitAsync().WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n public async Task WaitForInitializationAsync(CancellationToken cancellationToken)\n {\n if ( IsInitialized )\n {\n return;\n }\n\n await initializationTcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public void Flush()\n {\n lock (syncRoot)\n {\n IsFlushed = true;\n samplesAvailableEvent.Set();\n }\n }\n\n public override void DiscardFrames(int count)\n {\n lock (syncRoot)\n {\n base.DiscardFrames(count);\n }\n }\n\n public override void AddFrame(ReadOnlyMemory frame)\n {\n lock (syncRoot)\n {\n if ( IsFlushed )\n {\n throw new InvalidOperationException(\"The source is flushed and cannot accept new frames.\");\n }\n\n base.AddFrame(frame);\n if ( IsInitialized && !initializationTcs.Task.IsCompleted )\n {\n initializationTcs.SetResult(true);\n }\n }\n }\n\n public override void AddFrame(ReadOnlyMemory frame)\n {\n lock (syncRoot)\n {\n if ( IsFlushed )\n {\n throw new InvalidOperationException(\"The source is flushed and cannot accept new frames.\");\n }\n\n base.AddFrame(frame);\n if ( IsInitialized && !initializationTcs.Task.IsCompleted )\n {\n initializationTcs.SetResult(true);\n }\n }\n }\n\n /// \n /// Notifies that new samples are available.\n /// \n public void NotifyNewSamples() { samplesAvailableEvent.Set(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismOffscreenSurface_OpenGLES2.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\n/// \n/// オフスクリーン描画用構造体\n/// \npublic class CubismOffscreenSurface_OpenGLES2(OpenGLApi gl)\n{\n /// \n /// 引数によって設定されたカラーバッファか?\n /// \n private bool _isColorBufferInherited;\n\n /// \n /// 旧フレームバッファ\n /// \n private int _oldFBO;\n\n /// \n /// レンダリングターゲットとしてのアドレス\n /// \n public int RenderTexture { get; private set; }\n\n /// \n /// 描画の際使用するテクスチャとしてのアドレス\n /// \n public int ColorBuffer { get; private set; }\n\n /// \n /// Create時に指定された幅\n /// \n public int BufferWidth { get; private set; }\n\n /// \n /// Create時に指定された高さ\n /// \n public int BufferHeight { get; private set; }\n\n /// \n /// 指定の描画ターゲットに向けて描画開始\n /// \n /// 0以上の場合、EndDrawでこの値をglBindFramebufferする\n public void BeginDraw(int restoreFBO = -1)\n {\n if ( RenderTexture == 0 )\n {\n return;\n }\n\n // バックバッファのサーフェイスを記憶しておく\n if ( restoreFBO < 0 )\n {\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out _oldFBO);\n }\n else\n {\n _oldFBO = restoreFBO;\n }\n\n //マスク用RenderTextureをactiveにセット\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, RenderTexture);\n }\n\n /// \n /// 描画終了\n /// \n public void EndDraw()\n {\n if ( RenderTexture == 0 )\n {\n return;\n }\n\n // 描画対象を戻す\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, _oldFBO);\n }\n\n /// \n /// レンダリングターゲットのクリア\n /// 呼ぶ場合はBeginDrawの後で呼ぶこと\n /// \n /// 赤(0.0~1.0)\n /// 緑(0.0~1.0)\n /// 青(0.0~1.0)\n /// α(0.0~1.0)\n public void Clear(float r, float g, float b, float a)\n {\n // マスクをクリアする\n gl.ClearColor(r, g, b, a);\n gl.Clear(gl.GL_COLOR_BUFFER_BIT);\n }\n\n /// \n /// CubismOffscreenFrame作成\n /// \n /// 作成するバッファ幅\n /// 作成するバッファ高さ\n /// 0以外の場合、ピクセル格納領域としてcolorBufferを使用する\n public bool CreateOffscreenSurface(int displayBufferWidth, int displayBufferHeight, int colorBuffer = 0)\n {\n // 一旦削除\n DestroyOffscreenSurface();\n\n // 新しく生成する\n if ( colorBuffer == 0 )\n {\n ColorBuffer = gl.GenTexture();\n\n gl.BindTexture(gl.GL_TEXTURE_2D, ColorBuffer);\n gl.TexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, displayBufferWidth, displayBufferHeight, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, 0);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);\n gl.BindTexture(gl.GL_TEXTURE_2D, 0);\n\n _isColorBufferInherited = false;\n }\n else\n {\n // 指定されたものを使用\n ColorBuffer = colorBuffer;\n\n _isColorBufferInherited = true;\n }\n\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out var tmpFramebufferObject);\n\n var ret = gl.GenFramebuffer();\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, ret);\n gl.FramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, ColorBuffer, 0);\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, tmpFramebufferObject);\n\n RenderTexture = ret;\n\n BufferWidth = displayBufferWidth;\n BufferHeight = displayBufferHeight;\n\n // 成功\n return true;\n }\n\n /// \n /// CubismOffscreenFrameの削除\n /// \n public void DestroyOffscreenSurface()\n {\n if ( !_isColorBufferInherited && ColorBuffer != 0 )\n {\n gl.DeleteTexture(ColorBuffer);\n ColorBuffer = 0;\n }\n\n if ( RenderTexture != 0 )\n {\n gl.DeleteFramebuffer(RenderTexture);\n RenderTexture = 0;\n }\n }\n\n /// \n /// 現在有効かどうか\n /// \n public bool IsValid() { return RenderTexture != 0; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Adapters/Audio/Output/AudioProgressNotifier.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Output;\n\npublic class AudioProgressNotifier : IAudioProgressNotifier\n{\n private readonly ILogger _logger;\n\n public AudioProgressNotifier(ILogger logger) { _logger = logger; }\n\n public event EventHandler? ChunkPlaybackStarted;\n\n public event EventHandler? ChunkPlaybackEnded;\n\n public event EventHandler? PlaybackProgress;\n\n public void RaiseChunkStarted(object? sender, AudioChunkPlaybackStartedEvent args)\n {\n _logger.LogTrace(\"Raising ChunkPlaybackStarted event for TurnId: {TurnId}, Chunk Id: {Sequence}\", args.TurnId, args.Chunk.Id);\n SafeInvoke(ChunkPlaybackStarted, sender, args);\n }\n\n public void RaiseChunkEnded(object? sender, AudioChunkPlaybackEndedEvent args)\n {\n _logger.LogTrace(\"Raising ChunkPlaybackEnded event for TurnId: {TurnId}, Chunk Id: {Sequence}\", args.TurnId, args.Chunk.Id);\n SafeInvoke(ChunkPlaybackEnded, sender, args);\n }\n\n public void RaiseProgress(object? sender, AudioPlaybackProgressEvent args)\n {\n SafeInvoke(PlaybackProgress, sender, args);\n }\n \n private void SafeInvoke(EventHandler? eventHandler, object? sender, TEventArgs args)\n {\n if ( eventHandler == null )\n {\n return;\n }\n\n var invocationList = eventHandler.GetInvocationList();\n\n foreach ( var handlerDelegate in invocationList )\n {\n try\n {\n var handler = (EventHandler)handlerDelegate;\n handler(sender, args);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Exception in audio progress event handler ({EventType}).\", typeof(TEventArgs).Name);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/AvatarApp.cs", "using Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.UI;\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.GUI;\nusing PersonaEngine.Lib.UI.Spout;\n\nusing Silk.NET.Input;\nusing Silk.NET.Maths;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.Core;\n\npublic class AvatarApp : IDisposable\n{\n private readonly IOptions _config;\n\n private readonly IConversationOrchestrator _conversationOrchestrator;\n\n private readonly IReadOnlyList _regularComponents;\n\n private readonly Dictionary> _spoutComponents = new();\n\n private readonly IReadOnlyList _startupTasks;\n\n private readonly IWindow _window;\n\n private readonly WindowConfiguration _windowConfig;\n\n private readonly WindowManager _windowManager;\n\n private GL _gl;\n\n private ImGuiController _imGui;\n\n private IInputContext _inputContext;\n \n private SpoutRegistry _spoutRegistry;\n\n public AvatarApp(IOptions config, IEnumerable renderComponents, IEnumerable startupTasks, IConversationOrchestrator conversationOrchestrator)\n {\n _config = config;\n _conversationOrchestrator = conversationOrchestrator;\n\n var allComponents = renderComponents.OrderByDescending(x => x.Priority).ToList();\n\n // Group components by spout target\n _regularComponents = allComponents.Where(x => !x.UseSpout).ToList();\n\n // Group spout components by their target\n foreach ( var component in allComponents.Where(x => x.UseSpout) )\n {\n if ( !_spoutComponents.TryGetValue(component.SpoutTarget, out var componentList) )\n {\n componentList = new List();\n _spoutComponents[component.SpoutTarget] = componentList;\n }\n\n componentList.Add(component);\n }\n\n _windowConfig = _config.Value.Window;\n _windowManager = new WindowManager(new Vector2D(_windowConfig.Width, _windowConfig.Height), _windowConfig.Title);\n _window = _windowManager.MainWindow;\n\n _windowManager.Load += OnLoad;\n _windowManager.Update += OnUpdate;\n _windowManager.RenderFrame += OnRender;\n _windowManager.Resize += OnResize;\n _windowManager.Close += OnClose;\n\n _startupTasks = startupTasks.ToList();\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n\n return;\n\n _spoutRegistry?.Dispose();\n _imGui.Dispose();\n }\n\n private void OnLoad()\n {\n // Set up keyboard input.\n _inputContext = _window.CreateInput();\n foreach ( var keyboard in _inputContext.Keyboards )\n {\n keyboard.KeyDown += OnKeyDown;\n }\n\n _gl = _windowManager.GL;\n\n foreach ( var task in _startupTasks )\n {\n task.Execute(_gl);\n }\n\n _spoutRegistry = new SpoutRegistry(_gl, _config.Value.SpoutConfigs);\n\n _imGui = new ImGuiController(_gl, _window, _inputContext, Path.Combine(@\"Resources\\Fonts\", @\"Montserrat-Medium.ttf\"), Path.Combine(@\"Resources\\Fonts\", @\"seguiemj.ttf\"));\n\n InitializeComponents(_regularComponents);\n\n foreach ( var componentGroup in _spoutComponents.Values )\n {\n InitializeComponents(componentGroup);\n }\n\n _ = _conversationOrchestrator.StartNewSessionAsync();\n }\n\n private void InitializeComponents(IEnumerable components)\n {\n foreach ( var component in components )\n {\n component.Initialize(_gl, _window, _inputContext);\n }\n }\n\n private void OnUpdate(double deltaTime)\n {\n // Update all components\n UpdateComponents(_regularComponents, (float)deltaTime);\n\n foreach ( var componentGroup in _spoutComponents.Values )\n {\n UpdateComponents(componentGroup, (float)deltaTime);\n }\n }\n\n private void UpdateComponents(IEnumerable components, float deltaTime)\n {\n foreach ( var component in components )\n {\n component.Update(deltaTime);\n }\n }\n\n private void OnRender(double deltaTime)\n {\n _imGui.Update((float)deltaTime);\n _gl.Viewport(0, 0, (uint)_windowConfig.Width, (uint)_windowConfig.Height);\n _gl.Clear((uint)ClearBufferMask.ColorBufferBit);\n\n // Render regular components to the screen\n foreach ( var component in _regularComponents )\n {\n component.Render((float)deltaTime);\n }\n\n _imGui.Render();\n\n // Render components to their respective Spout outputs\n foreach ( var spoutGroup in _spoutComponents )\n {\n var spoutTarget = spoutGroup.Key;\n var components = spoutGroup.Value;\n\n // Begin frame for this spout target\n _spoutRegistry.BeginFrame(spoutTarget);\n\n // Render all components for this spout target\n foreach ( var component in components )\n {\n component.Render((float)deltaTime);\n }\n\n _spoutRegistry.SendFrame(spoutTarget);\n }\n }\n\n private void OnResize(Vector2D size)\n {\n // Resize all components\n ResizeComponents(_regularComponents);\n }\n\n private void ResizeComponents(IEnumerable components)\n {\n foreach ( var component in components )\n {\n component.Resize();\n }\n }\n\n private void OnClose() { }\n\n private void OnKeyDown(IKeyboard keyboard, Key key, int scancode)\n {\n switch ( key )\n {\n case Key.Escape:\n _window.Close();\n\n break;\n }\n }\n\n public void Run() { _windowManager.Run(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismViewMatrix.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// カメラの位置変更に使うと便利な4x4行列のクラス。\n/// \npublic record CubismViewMatrix : CubismMatrix44\n{\n /// \n /// デバイスに対応する論理座標上の範囲(左辺X軸位置)\n /// \n public float ScreenLeft { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(右辺X軸位置)\n /// \n public float ScreenRight { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(下辺Y軸位置)\n /// \n public float ScreenTop { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(上辺Y軸位置)\n /// \n public float ScreenBottom { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(左辺X軸位置)\n /// \n public float MaxLeft { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(右辺X軸位置)\n /// \n public float MaxRight { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(下辺Y軸位置)\n /// \n public float MaxTop { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(上辺Y軸位置)\n /// \n public float MaxBottom { get; private set; }\n\n /// \n /// 拡大率の最大値\n /// \n public float MaxScale { get; set; }\n\n /// \n /// 拡大率の最小値\n /// \n public float MinScale { get; set; }\n\n /// \n /// 移動を調整する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void AdjustTranslate(float x, float y)\n {\n if ( _tr[0] * MaxLeft + (_tr[12] + x) > ScreenLeft )\n {\n x = ScreenLeft - _tr[0] * MaxLeft - _tr[12];\n }\n\n if ( _tr[0] * MaxRight + (_tr[12] + x) < ScreenRight )\n {\n x = ScreenRight - _tr[0] * MaxRight - _tr[12];\n }\n\n if ( _tr[5] * MaxTop + (_tr[13] + y) < ScreenTop )\n {\n y = ScreenTop - _tr[5] * MaxTop - _tr[13];\n }\n\n if ( _tr[5] * MaxBottom + (_tr[13] + y) > ScreenBottom )\n {\n y = ScreenBottom - _tr[5] * MaxBottom - _tr[13];\n }\n\n float[] tr1 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n x, y, 0.0f, 1.0f\n ];\n\n MultiplyByMatrix(tr1);\n }\n\n /// \n /// 拡大率を調整する。\n /// \n /// 拡大を行うX軸の中心位置\n /// 拡大を行うY軸の中心位置\n /// 拡大率\n public void AdjustScale(float cx, float cy, float scale)\n {\n var maxScale = MaxScale;\n var minScale = MinScale;\n\n var targetScale = scale * _tr[0]; //\n\n if ( targetScale < minScale )\n {\n if ( _tr[0] > 0.0f )\n {\n scale = minScale / _tr[0];\n }\n }\n else if ( targetScale > maxScale )\n {\n if ( _tr[0] > 0.0f )\n {\n scale = maxScale / _tr[0];\n }\n }\n\n MultiplyByMatrix([\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n -cx, -cy, 0.0f, 1.0f\n ]);\n\n MultiplyByMatrix([\n scale, 0.0f, 0.0f, 0.0f,\n 0.0f, scale, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ]);\n\n MultiplyByMatrix([\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n cx, cy, 0.0f, 1.0f\n ]);\n }\n\n /// \n /// デバイスに対応する論理座標上の範囲の設定を行う。\n /// \n /// 左辺のX軸の位置\n /// 右辺のX軸の位置\n /// 下辺のY軸の位置\n /// 上辺のY軸の位置\n public void SetScreenRect(float left, float right, float bottom, float top)\n {\n ScreenLeft = left;\n ScreenRight = right;\n ScreenTop = top;\n ScreenBottom = bottom;\n }\n\n /// \n /// デバイスに対応する論理座標上の移動可能範囲の設定を行う。\n /// \n /// 左辺のX軸の位置\n /// 右辺のX軸の位置\n /// 下辺のY軸の位置\n /// 上辺のY軸の位置\n public void SetMaxScreenRect(float left, float right, float bottom, float top)\n {\n MaxLeft = left;\n MaxRight = right;\n MaxTop = top;\n MaxBottom = bottom;\n }\n\n /// \n /// 拡大率が最大になっているかどうかを確認する。\n /// \n /// \n /// true 拡大率は最大になっている\n /// false 拡大率は最大になっていない\n /// \n public bool IsMaxScale() { return GetScaleX() >= MaxScale; }\n\n /// \n /// 拡大率が最小になっているかどうかを確認する。\n /// \n /// \n /// true 拡大率は最小になっている\n /// false 拡大率は最小になっていない\n /// \n public bool IsMinScale() { return GetScaleX() <= MinScale; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/TextExtensions.cs", "using System.Text;\n\nnamespace PersonaEngine.Lib.Utils;\n\npublic static class TextExtensions\n{\n public static string SafeNormalizeUnicode(this string input)\n {\n if ( string.IsNullOrEmpty(input) )\n {\n return input;\n }\n\n try\n {\n return input.Normalize(NormalizationForm.FormKC);\n }\n catch (ArgumentException)\n {\n // Failed,try to remove invalid unicode chars\n }\n\n // Remove invalid characters\n var result = new StringBuilder(input.Length);\n var currentPos = 0;\n\n while ( currentPos < input.Length )\n {\n var invalidPos = FindInvalidCharIndex(input[currentPos..]);\n if ( invalidPos == -1 )\n {\n // No more invalid characters found, add the rest\n result.Append(input.AsSpan(currentPos));\n\n break;\n }\n\n // Add the valid portion before the invalid character\n if ( invalidPos > 0 )\n {\n result.Append(input.AsSpan(currentPos, invalidPos));\n }\n\n // Skip the invalid character (or pair)\n if ( input[currentPos + invalidPos] >= 0xD800 && input[currentPos + invalidPos] <= 0xDBFF )\n {\n // Skip surrogate pair\n currentPos += invalidPos + 2;\n }\n else\n {\n // Skip single character\n currentPos += invalidPos + 1;\n }\n }\n\n // Now normalize the cleaned string\n return result.ToString().Normalize(NormalizationForm.FormKC);\n }\n\n /// \n /// Searches invalid charachters (non-chars defined in Unicode standard and invalid surrogate pairs) in a string\n /// \n /// the string to search for invalid chars \n /// the index of the first bad char or -1 if no bad char is found\n private static int FindInvalidCharIndex(string aString)\n {\n for ( var i = 0; i < aString.Length; i++ )\n {\n int ch = aString[i];\n if ( ch < 0xD800 ) // char is up to first high surrogate\n {\n continue;\n }\n\n if ( ch is >= 0xD800 and <= 0xDBFF )\n {\n // found high surrogate -> check surrogate pair\n i++;\n if ( i == aString.Length )\n {\n // last char is high surrogate, so it is missing its pair\n return i - 1;\n }\n\n int chlow = aString[i];\n if ( chlow is < 0xDC00 or > 0xDFFF )\n {\n // did not found a low surrogate after the high surrogate\n return i - 1;\n }\n\n // convert to UTF32 - like in Char.ConvertToUtf32(highSurrogate, lowSurrogate)\n ch = (ch - 0xD800) * 0x400 + (chlow - 0xDC00) + 0x10000;\n if ( ch > 0x10FFFF )\n {\n // invalid Unicode code point - maximum excedeed\n return i;\n }\n\n if ( (ch & 0xFFFE) == 0xFFFE )\n {\n // other non-char found\n return i;\n }\n\n // found a good surrogate pair\n continue;\n }\n\n if ( ch is >= 0xDC00 and <= 0xDFFF )\n {\n // unexpected low surrogate\n return i;\n }\n\n if ( ch is >= 0xFDD0 and <= 0xFDEF )\n {\n // non-chars are considered invalid by System.Text.Encoding.GetBytes() and String.Normalize()\n return i;\n }\n\n if ( (ch & 0xFFFE) == 0xFFFE )\n {\n // other non-char found\n return i;\n }\n }\n\n return -1;\n }\n\n public static int GetWordCount(this string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n return 0;\n }\n\n var wordCount = 0;\n var inWord = false;\n\n foreach ( var c in text )\n {\n if ( char.IsWhiteSpace(c) )\n {\n inWord = false;\n }\n else\n {\n if ( inWord )\n {\n continue;\n }\n\n wordCount++;\n inWord = true;\n }\n }\n\n return wordCount;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/Texture.cs", "using System.Drawing;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\npublic enum TextureCoordinate\n{\n S = TextureParameterName.TextureWrapS,\n\n T = TextureParameterName.TextureWrapT,\n\n R = TextureParameterName.TextureWrapR\n}\n\npublic unsafe class Texture : IDisposable\n{\n public const SizedInternalFormat Srgb8Alpha8 = (SizedInternalFormat)GLEnum.Srgb8Alpha8;\n\n public const SizedInternalFormat Rgb32F = (SizedInternalFormat)GLEnum.Rgb32f;\n\n public const GLEnum MaxTextureMaxAnisotropy = (GLEnum)0x84FF;\n\n public static float? MaxAniso;\n\n private readonly GL _gl;\n\n public readonly uint GlTexture;\n\n public readonly SizedInternalFormat InternalFormat;\n\n public readonly uint MipmapLevels;\n\n public readonly uint Width,\n Height;\n\n public Texture(GL gl, int width, int height, IntPtr data, bool generateMipmaps = false, bool srgb = false)\n {\n _gl = gl;\n MaxAniso ??= gl.GetFloat(MaxTextureMaxAnisotropy);\n Width = (uint)width;\n Height = (uint)height;\n InternalFormat = srgb ? Srgb8Alpha8 : SizedInternalFormat.Rgba8;\n MipmapLevels = (uint)(generateMipmaps == false ? 1 : (int)Math.Floor(Math.Log(Math.Max(Width, Height), 2)));\n\n GlTexture = _gl.GenTexture();\n Bind();\n\n _gl.TexStorage2D(GLEnum.Texture2D, MipmapLevels, InternalFormat, Width, Height);\n _gl.TexSubImage2D(GLEnum.Texture2D, 0, 0, 0, Width, Height, PixelFormat.Bgra, PixelType.UnsignedByte, (void*)data);\n\n if ( generateMipmaps )\n {\n _gl.GenerateTextureMipmap(GlTexture);\n }\n\n SetWrap(TextureCoordinate.S, TextureWrapMode.Repeat);\n SetWrap(TextureCoordinate.T, TextureWrapMode.Repeat);\n\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMaxLevel, MipmapLevels - 1);\n }\n\n public void Dispose()\n {\n _gl.DeleteTexture(GlTexture);\n _gl.CheckError();\n }\n\n public void Bind()\n {\n _gl.BindTexture(GLEnum.Texture2D, GlTexture);\n _gl.CheckError();\n }\n\n public void SetMinFilter(TextureMinFilter filter) { _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMinFilter, (int)filter); }\n\n public void SetMagFilter(TextureMagFilter filter) { _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMagFilter, (int)filter); }\n\n public void SetAnisotropy(float level)\n {\n const TextureParameterName textureMaxAnisotropy = (TextureParameterName)0x84FE;\n _gl.TexParameter(GLEnum.Texture2D, (GLEnum)textureMaxAnisotropy, GlUtility.Clamp(level, 1, MaxAniso.GetValueOrDefault()));\n }\n\n public void SetLod(int @base, int min, int max)\n {\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureLodBias, @base);\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMinLod, min);\n _gl.TexParameterI(GLEnum.Texture2D, TextureParameterName.TextureMaxLod, max);\n }\n\n public void SetWrap(TextureCoordinate coord, TextureWrapMode mode) { _gl.TexParameterI(GLEnum.Texture2D, (TextureParameterName)coord, (int)mode); }\n\n public void SetData(Rectangle bounds, byte[] data)\n {\n Bind();\n fixed (byte* ptr = data)\n {\n _gl.TexSubImage2D(\n TextureTarget.Texture2D,\n 0,\n bounds.Left,\n bounds.Top,\n (uint)bounds.Width,\n (uint)bounds.Height,\n PixelFormat.Rgba,\n PixelType.UnsignedByte,\n ptr\n );\n\n _gl.CheckError();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/TouchManager.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\npublic class TouchManager\n{\n /// \n /// 前回の値から今回の値へのxの移動距離。\n /// \n private float _deltaX;\n\n /// \n /// 前回の値から今回の値へのyの移動距離。\n /// \n private float _deltaY;\n\n /// \n /// フリップが有効かどうか\n /// \n private bool _flipAvailable;\n\n /// \n /// 2本以上でタッチしたときの指の距離\n /// \n private float _lastTouchDistance;\n\n /// \n /// シングルタッチ時のxの値\n /// \n private float _lastX;\n\n /// \n /// ダブルタッチ時の一つ目のxの値\n /// \n private float _lastX1;\n\n /// \n /// ダブルタッチ時の二つ目のxの値\n /// \n private float _lastX2;\n\n /// \n /// シングルタッチ時のyの値\n /// \n private float _lastY;\n\n /// \n /// ダブルタッチ時の一つ目のyの値\n /// \n private float _lastY1;\n\n /// \n /// ダブルタッチ時の二つ目のyの値\n /// \n private float _lastY2;\n\n /// \n /// このフレームで掛け合わせる拡大率。拡大操作中以外は1。\n /// \n private float _scale;\n\n /// \n /// タッチを開始した時のyの値\n /// \n private float _startX;\n\n /// \n /// タッチを開始した時のxの値\n /// \n private float _startY;\n\n /// \n /// シングルタッチ時はtrue\n /// \n private bool _touchSingle;\n\n public TouchManager() { _scale = 1.0f; }\n\n public float GetCenterX() { return _lastX; }\n\n public float GetCenterY() { return _lastY; }\n\n public float GetDeltaX() { return _deltaX; }\n\n public float GetDeltaY() { return _deltaY; }\n\n public float GetStartX() { return _startX; }\n\n public float GetStartY() { return _startY; }\n\n public float GetScale() { return _scale; }\n\n public float GetX() { return _lastX; }\n\n public float GetY() { return _lastY; }\n\n public float GetX1() { return _lastX1; }\n\n public float GetY1() { return _lastY1; }\n\n public float GetX2() { return _lastX2; }\n\n public float GetY2() { return _lastY2; }\n\n public bool IsSingleTouch() { return _touchSingle; }\n\n public bool IsFlickAvailable() { return _flipAvailable; }\n\n public void DisableFlick() { _flipAvailable = false; }\n\n /// \n /// タッチ開始時イベント\n /// \n /// タッチした画面のyの値\n /// タッチした画面のxの値\n public void TouchesBegan(float deviceX, float deviceY)\n {\n _lastX = deviceX;\n _lastY = deviceY;\n _startX = deviceX;\n _startY = deviceY;\n _lastTouchDistance = -1.0f;\n _flipAvailable = true;\n _touchSingle = true;\n }\n\n /// \n /// ドラッグ時のイベント\n /// \n /// タッチした画面のxの値\n /// タッチした画面のyの値\n public void TouchesMoved(float deviceX, float deviceY)\n {\n _lastX = deviceX;\n _lastY = deviceY;\n _lastTouchDistance = -1.0f;\n _touchSingle = true;\n }\n\n /// \n /// ドラッグ時のイベント\n /// \n /// 1つめのタッチした画面のxの値\n /// 1つめのタッチした画面のyの値\n /// 2つめのタッチした画面のxの値\n /// 2つめのタッチした画面のyの値\n public void TouchesMoved(float deviceX1, float deviceY1, float deviceX2, float deviceY2)\n {\n var distance = CalculateDistance(deviceX1, deviceY1, deviceX2, deviceY2);\n var centerX = (deviceX1 + deviceX2) * 0.5f;\n var centerY = (deviceY1 + deviceY2) * 0.5f;\n\n if ( _lastTouchDistance > 0.0f )\n {\n _scale = MathF.Pow(distance / _lastTouchDistance, 0.75f);\n _deltaX = CalculateMovingAmount(deviceX1 - _lastX1, deviceX2 - _lastX2);\n _deltaY = CalculateMovingAmount(deviceY1 - _lastY1, deviceY2 - _lastY2);\n }\n else\n {\n _scale = 1.0f;\n _deltaX = 0.0f;\n _deltaY = 0.0f;\n }\n\n _lastX = centerX;\n _lastY = centerY;\n _lastX1 = deviceX1;\n _lastY1 = deviceY1;\n _lastX2 = deviceX2;\n _lastY2 = deviceY2;\n _lastTouchDistance = distance;\n _touchSingle = false;\n }\n\n /// \n /// フリックの距離測定\n /// \n /// フリック距離\n public float GetFlickDistance() { return CalculateDistance(_startX, _startY, _lastX, _lastY); }\n\n /// \n /// 点1から点2への距離を求める\n /// \n /// 1つめのタッチした画面のxの値\n /// 1つめのタッチした画面のyの値\n /// 2つめのタッチした画面のxの値\n /// 2つめのタッチした画面のyの値\n /// 2点の距離\n public static float CalculateDistance(float x1, float y1, float x2, float y2) { return MathF.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); }\n\n /// \n /// 二つの値から、移動量を求める。\n /// 違う方向の場合は移動量0。同じ方向の場合は、絶対値が小さい方の値を参照する\n /// \n /// 1つめの移動量\n /// 2つめの移動量\n /// 小さい方の移動量\n public static float CalculateMovingAmount(float v1, float v2)\n {\n if ( v1 > 0.0f != v2 > 0.0f )\n {\n return 0.0f;\n }\n\n var sign = v1 > 0.0f ? 1.0f : -1.0f;\n var absoluteValue1 = MathF.Abs(v1);\n var absoluteValue2 = MathF.Abs(v2);\n\n return sign * (absoluteValue1 < absoluteValue2 ? absoluteValue1 : absoluteValue2);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/TextRenderer.cs", "using System.Numerics;\n\nusing FontStashSharp.Interfaces;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\ninternal class TextRenderer : IFontStashRenderer2, IDisposable\n{\n private const int MAX_SPRITES = 2048;\n\n private const int MAX_VERTICES = MAX_SPRITES * 4;\n\n private const int MAX_INDICES = MAX_SPRITES * 6;\n\n private static readonly short[] indexData = GenerateIndexArray();\n\n private readonly GL _gl;\n\n private readonly BufferObject _indexBuffer;\n\n private readonly Shader _shader;\n\n private readonly Texture2DManager _textureManager;\n\n private readonly VertexArrayObject _vao;\n\n private readonly BufferObject _vertexBuffer;\n\n private readonly VertexPositionColorTexture[] _vertexData = new VertexPositionColorTexture[MAX_VERTICES];\n\n private object _lastTexture;\n\n private int _vertexIndex = 0;\n\n private int _viewportHeight = 800;\n\n private int _viewportWidth = 1200;\n\n public unsafe TextRenderer(GL glApi)\n {\n _gl = glApi;\n\n _textureManager = new Texture2DManager(_gl);\n\n _vertexBuffer = new BufferObject(_gl, MAX_VERTICES, BufferTargetARB.ArrayBuffer, true);\n _indexBuffer = new BufferObject(_gl, indexData.Length, BufferTargetARB.ElementArrayBuffer, false);\n _indexBuffer.SetData(indexData, 0, indexData.Length);\n\n var vertSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"t_shader.vert\"));\n var fragSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"t_shader.frag\"));\n _shader = new Shader(_gl, vertSrc, fragSrc);\n _shader.Use();\n\n _vao = new VertexArrayObject(_gl, sizeof(VertexPositionColorTexture));\n _vao.Bind();\n\n var location = _shader.GetAttribLocation(\"a_position\");\n _vao.VertexAttribPointer(location, 3, VertexAttribPointerType.Float, false, 0);\n\n location = _shader.GetAttribLocation(\"a_color\");\n _vao.VertexAttribPointer(location, 4, VertexAttribPointerType.UnsignedByte, true, 12);\n\n location = _shader.GetAttribLocation(\"a_texCoords0\");\n _vao.VertexAttribPointer(location, 2, VertexAttribPointerType.Float, false, 16);\n }\n\n public void Dispose() { Dispose(true); }\n\n public ITexture2DManager TextureManager => _textureManager;\n\n public void DrawQuad(object texture, ref VertexPositionColorTexture topLeft, ref VertexPositionColorTexture topRight, ref VertexPositionColorTexture bottomLeft, ref VertexPositionColorTexture bottomRight)\n {\n if ( _lastTexture != texture )\n {\n FlushBuffer();\n }\n\n _vertexData[_vertexIndex++] = topLeft;\n _vertexData[_vertexIndex++] = topRight;\n _vertexData[_vertexIndex++] = bottomLeft;\n _vertexData[_vertexIndex++] = bottomRight;\n\n _lastTexture = texture;\n }\n\n ~TextRenderer() { Dispose(false); }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( !disposing )\n {\n return;\n }\n\n _vao.Dispose();\n _vertexBuffer.Dispose();\n _indexBuffer.Dispose();\n _shader.Dispose();\n }\n\n public void Begin()\n {\n _gl.Disable(EnableCap.DepthTest);\n _gl.CheckError();\n _gl.Enable(EnableCap.Blend);\n _gl.CheckError();\n _gl.BlendFunc(BlendingFactor.One, BlendingFactor.OneMinusSrcAlpha);\n _gl.CheckError();\n\n _shader.Use();\n _shader.SetUniform(\"TextureSampler\", 0);\n\n var transform = Matrix4x4.CreateOrthographicOffCenter(0, _viewportWidth, _viewportHeight, 0, 0, -1);\n _shader.SetUniform(\"MatrixTransform\", transform);\n\n _vao.Bind();\n _indexBuffer.Bind();\n _vertexBuffer.Bind();\n }\n\n public void End() { FlushBuffer(); }\n\n private void FlushBuffer()\n {\n unsafe\n {\n if ( _vertexIndex == 0 || _lastTexture == null )\n {\n return;\n }\n\n _vertexBuffer.SetData(_vertexData, 0, _vertexIndex);\n\n var texture = (Texture)_lastTexture;\n texture.Bind();\n\n _gl.DrawElements(PrimitiveType.Triangles, (uint)(_vertexIndex * 6 / 4), DrawElementsType.UnsignedShort, null);\n _vertexIndex = 0;\n }\n }\n\n private static short[] GenerateIndexArray()\n {\n var result = new short[MAX_INDICES];\n for ( int i = 0,\n j = 0; i < MAX_INDICES; i += 6, j += 4 )\n {\n result[i] = (short)j;\n result[i + 1] = (short)(j + 1);\n result[i + 2] = (short)(j + 2);\n result[i + 3] = (short)(j + 3);\n result[i + 4] = (short)(j + 2);\n result[i + 5] = (short)(j + 1);\n }\n\n return result;\n }\n\n public void OnViewportChanged(int width, int height)\n {\n _viewportWidth = width;\n _viewportHeight = height;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションの管理を行うクラス。\n/// \npublic class CubismMotionManager : CubismMotionQueueManager\n{\n /// \n /// 現在再生中のモーションの優先度\n /// \n public MotionPriority CurrentPriority { get; private set; }\n\n /// \n /// 再生予定のモーションの優先度。再生中は0になる。モーションファイルを別スレッドで読み込むときの機能。\n /// \n public MotionPriority ReservePriority { get; set; }\n\n /// \n /// 優先度を設定してモーションを開始する。\n /// \n /// モーション\n /// 再生が終了したモーションのインスタンスを削除するならtrue\n /// 優先度\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotionPriority(ACubismMotion motion, MotionPriority priority)\n {\n if ( priority == ReservePriority )\n {\n ReservePriority = 0; // 予約を解除\n }\n\n CurrentPriority = priority; // 再生中モーションの優先度を設定\n\n return StartMotion(motion);\n }\n\n /// \n /// モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// \n /// true 更新されている\n /// false 更新されていない\n /// \n public bool UpdateMotion(CubismModel model, float deltaTimeSeconds)\n {\n UserTimeSeconds += deltaTimeSeconds;\n\n var updated = DoUpdateMotion(model, UserTimeSeconds);\n\n if ( IsFinished() )\n {\n CurrentPriority = 0; // 再生中モーションの優先度を解除\n }\n\n return updated;\n }\n\n /// \n /// モーションを予約する。\n /// \n /// 優先度\n /// \n /// true 予約できた\n /// false 予約できなかった\n /// \n public bool ReserveMotion(MotionPriority priority)\n {\n if ( priority <= ReservePriority || priority <= CurrentPriority )\n {\n return false;\n }\n\n ReservePriority = priority;\n\n return true;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/WavUtils.cs", "namespace PersonaEngine.Lib.Utils;\n\npublic class WavUtils\n{\n private const int RIFF_CHUNK_ID = 0x46464952; // \"RIFF\" in ASCII\n\n private const int WAVE_FORMAT = 0x45564157; // \"WAVE\" in ASCII\n\n private const int FMT_CHUNK_ID = 0x20746D66; // \"fmt \" in ASCII\n\n private const int DATA_CHUNK_ID = 0x61746164; // \"data\" in ASCII\n\n private const int PCM_FORMAT = 1; // PCM audio format\n\n public static void SaveToWav(Memory samples, string filePath, int sampleRate = 44100, int channels = 1)\n {\n using (var writer = new BinaryWriter(File.OpenWrite(filePath)))\n {\n WriteWavFile(writer, samples, sampleRate, channels);\n }\n }\n\n public static void AppendToWav(Memory samples, string filePath)\n {\n // First, read the existing WAV file header\n WavHeader header;\n long dataPosition;\n using (var reader = new BinaryReader(File.OpenRead(filePath)))\n {\n header = ReadWavHeader(reader);\n dataPosition = reader.BaseStream.Position;\n }\n\n // Open file for writing and seek to end of data\n using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))\n using (var writer = new BinaryWriter(stream))\n {\n stream.Seek(0, SeekOrigin.End);\n\n // Write new samples\n var span = samples.Span;\n for ( var i = 0; i < span.Length; i++ )\n {\n var pcm = (short)(span[i] * short.MaxValue);\n writer.Write(pcm);\n }\n\n // Update file size in header\n var newDataSize = header.DataSize + samples.Length * sizeof(short);\n var newFileSize = newDataSize + 44 - 8; // 44 is header size, subtract 8 for RIFF header\n\n stream.Seek(4, SeekOrigin.Begin);\n writer.Write(newFileSize);\n\n // Update data chunk size\n stream.Seek(dataPosition - 4, SeekOrigin.Begin);\n writer.Write(newDataSize);\n }\n }\n\n private static void WriteWavFile(BinaryWriter writer, Memory samples, int sampleRate, int channels)\n {\n var bytesPerSample = sizeof(short); // We'll convert float to 16-bit PCM\n var dataSize = samples.Length * bytesPerSample;\n var headerSize = 44; // Standard WAV header size\n var fileSize = headerSize + dataSize - 8; // Total file size - 8 bytes\n\n // Write WAV header\n writer.Write(RIFF_CHUNK_ID); // \"RIFF\" chunk\n writer.Write(fileSize); // File size - 8\n writer.Write(WAVE_FORMAT); // \"WAVE\" format\n\n // Write format chunk\n writer.Write(FMT_CHUNK_ID); // \"fmt \" chunk\n writer.Write(16); // Format chunk size (16 for PCM)\n writer.Write((short)PCM_FORMAT); // Audio format (1 for PCM)\n writer.Write((short)channels); // Number of channels\n writer.Write(sampleRate); // Sample rate\n writer.Write(sampleRate * channels * bytesPerSample); // Byte rate\n writer.Write((short)(channels * bytesPerSample)); // Block align\n writer.Write((short)(bytesPerSample * 8)); // Bits per sample\n\n // Write data chunk\n writer.Write(DATA_CHUNK_ID); // \"data\" chunk\n writer.Write(dataSize); // Data size\n\n // Write audio samples\n var span = samples.Span;\n for ( var i = 0; i < span.Length; i++ )\n {\n var pcm = (short)(span[i] * short.MaxValue);\n writer.Write(pcm);\n }\n }\n\n private static WavHeader ReadWavHeader(BinaryReader reader)\n {\n // Verify RIFF header\n if ( reader.ReadInt32() != RIFF_CHUNK_ID )\n {\n throw new InvalidDataException(\"Not a valid RIFF file\");\n }\n\n var header = new WavHeader { FileSize = reader.ReadInt32() };\n\n // Verify WAVE format\n if ( reader.ReadInt32() != WAVE_FORMAT )\n {\n throw new InvalidDataException(\"Not a valid WAVE file\");\n }\n\n // Read format chunk\n if ( reader.ReadInt32() != FMT_CHUNK_ID )\n {\n throw new InvalidDataException(\"Missing format chunk\");\n }\n\n var fmtSize = reader.ReadInt32();\n if ( reader.ReadInt16() != PCM_FORMAT )\n {\n throw new InvalidDataException(\"Unsupported audio format (must be PCM)\");\n }\n\n header.Channels = reader.ReadInt16();\n header.SampleRate = reader.ReadInt32();\n header.ByteRate = reader.ReadInt32();\n header.BlockAlign = reader.ReadInt16();\n header.BitsPerSample = reader.ReadInt16();\n\n // Skip any extra format bytes\n if ( fmtSize > 16 )\n {\n reader.BaseStream.Seek(fmtSize - 16, SeekOrigin.Current);\n }\n\n // Find data chunk\n while ( true )\n {\n var chunkId = reader.ReadInt32();\n var chunkSize = reader.ReadInt32();\n\n if ( chunkId == DATA_CHUNK_ID )\n {\n header.DataSize = chunkSize;\n\n break;\n }\n\n reader.BaseStream.Seek(chunkSize, SeekOrigin.Current);\n\n if ( reader.BaseStream.Position >= reader.BaseStream.Length )\n {\n throw new InvalidDataException(\"Missing data chunk\");\n }\n }\n\n return header;\n }\n\n public static bool ValidateWavFile(string filePath)\n {\n try\n {\n using (var reader = new BinaryReader(File.OpenRead(filePath)))\n {\n ReadWavHeader(reader);\n\n return true;\n }\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n private struct WavHeader\n {\n public int FileSize;\n\n public int Channels;\n\n public int SampleRate;\n\n public int ByteRate;\n\n public short BlockAlign;\n\n public short BitsPerSample;\n\n public int DataSize;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismFramework.cs", "using PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Id;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// Live2D Cubism Original Workflow SDKのエントリポイント\n/// 利用開始時はCubismFramework.Initialize()を呼び、CubismFramework.Dispose()で終了する。\n/// \npublic static class CubismFramework\n{\n /// \n /// メッシュ頂点のオフセット値\n /// \n public const int VertexOffset = 0;\n\n /// \n /// メッシュ頂点のステップ値\n /// \n public const int VertexStep = 2;\n\n private static ICubismAllocator? s_allocator;\n\n private static Option? s_option;\n\n /// \n /// IDマネージャのインスタンスを取得する。\n /// \n public static CubismIdManager CubismIdManager { get; private set; } = new();\n\n public static bool IsInitialized { get; private set; }\n\n public static bool IsStarted { get; private set; }\n\n /// \n /// Cubism FrameworkのAPIを使用可能にする。\n /// APIを実行する前に必ずこの関数を実行すること。\n /// 引数に必ずメモリアロケータを渡してください。\n /// 一度準備が完了して以降は、再び実行しても内部処理がスキップされます。\n /// \n /// ICubismAllocatorクラスのインスタンス\n /// Optionクラスのインスタンス\n /// 準備処理が完了したらtrueが返ります。\n public static bool StartUp(ICubismAllocator allocator, Option option)\n {\n if ( IsStarted )\n {\n CubismLog.Info(\"[Live2D SDK]CubismFramework.StartUp() is already done.\");\n\n return IsStarted;\n }\n\n s_option = option;\n if ( s_option != null )\n {\n CubismCore.SetLogFunction(s_option.LogFunction);\n }\n\n if ( allocator == null )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.StartUp() failed, need allocator instance.\");\n IsStarted = false;\n }\n else\n {\n s_allocator = allocator;\n IsStarted = true;\n }\n\n //Live2D Cubism Coreバージョン情報を表示\n if ( IsStarted )\n {\n var version = CubismCore.GetVersion();\n\n var major = (version & 0xFF000000) >> 24;\n var minor = (version & 0x00FF0000) >> 16;\n var patch = version & 0x0000FFFF;\n var versionNumber = version;\n\n CubismLog.Info($\"[Live2D SDK]Cubism Core version: {major:#0}.{minor:0}.{patch:0000} ({versionNumber})\");\n }\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.StartUp() is complete.\");\n\n return IsStarted;\n }\n\n /// \n /// StartUp()で初期化したCubismFrameworkの各パラメータをクリアします。\n /// Dispose()したCubismFrameworkを再利用する際に利用してください。\n /// \n public static void CleanUp()\n {\n IsStarted = false;\n IsInitialized = false;\n }\n\n /// \n /// Cubism Framework内のリソースを初期化してモデルを表示可能な状態にします。\n /// 再度Initialize()するには先にDispose()を実行する必要があります。\n /// \n public static void Initialize()\n {\n if ( !IsStarted )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework is not started.\");\n\n return;\n }\n\n // --- s_isInitializedによる連続初期化ガード ---\n // 連続してリソース確保が行われないようにする。\n // 再度Initialize()するには先にDispose()を実行する必要がある。\n if ( IsInitialized )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.Initialize() skipped, already initialized.\");\n\n return;\n }\n\n IsInitialized = true;\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.Initialize() is complete.\");\n }\n\n /// \n /// Cubism Framework内の全てのリソースを解放します。\n /// ただし、外部で確保されたリソースについては解放しません。\n /// 外部で適切に破棄する必要があります。\n /// \n public static void Dispose()\n {\n if ( !IsStarted )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework is not started.\");\n\n return;\n }\n\n // --- s_isInitializedによる未初期化解放ガード ---\n // Dispose()するには先にInitialize()を実行する必要がある。\n if ( !IsInitialized ) // false...リソース未確保の場合\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.Dispose() skipped, not initialized.\");\n\n return;\n }\n\n IsInitialized = false;\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.Dispose() is complete.\");\n }\n\n /// \n /// Core APIにバインドしたログ関数を実行する\n /// \n /// ログメッセージ\n public static void CoreLogFunction(string data) { CubismCore.GetLogFunction()?.Invoke(data); }\n\n /// \n /// 現在のログ出力レベル設定の値を返す。\n /// \n /// 現在のログ出力レベル設定の値\n public static LogLevel GetLoggingLevel()\n {\n if ( s_option != null )\n {\n return s_option.LoggingLevel;\n }\n\n return LogLevel.Off;\n }\n\n public static IntPtr Allocate(int size) { return s_allocator!.Allocate(size); }\n\n public static IntPtr AllocateAligned(int size, int alignment) { return s_allocator!.AllocateAligned(size, alignment); }\n\n public static void Deallocate(IntPtr address) { s_allocator!.Deallocate(address); }\n\n public static void DeallocateAligned(IntPtr address) { s_allocator!.DeallocateAligned(address); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/EditorStateManager.cs", "using System.Collections.Immutable;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements editor state management\n/// \npublic class EditorStateManager : IEditorStateManager\n{\n private readonly Dictionary _activeOperations = new();\n\n private readonly Dictionary _stateValues = new();\n\n public event EventHandler StateChanged;\n\n public bool HasUnsavedChanges { get; private set; } = false;\n\n public void MarkAsChanged(string? sectionKey = null)\n {\n SetStateValue(\"HasUnsavedChanges\", false, true);\n HasUnsavedChanges = true;\n }\n\n public void MarkAsSaved()\n {\n SetStateValue(\"HasUnsavedChanges\", true, false);\n HasUnsavedChanges = false;\n }\n\n public ActiveOperation? GetActiveOperation() { return _activeOperations.Values.FirstOrDefault(); }\n\n public void RegisterActiveOperation(ActiveOperation operation)\n {\n _activeOperations[operation.Id] = operation;\n FireStateChanged(\"ActiveOperations\", null, _activeOperations.Values.ToImmutableList());\n }\n\n public void ClearActiveOperation(string operationId)\n {\n if ( _activeOperations.TryGetValue(operationId, out var operation) )\n {\n _activeOperations.Remove(operationId);\n operation.CancellationSource.Dispose();\n FireStateChanged(\"ActiveOperations\", null, _activeOperations.Values.ToImmutableList());\n }\n }\n\n private void SetStateValue(string key, T? oldValue, T newValue) where T : struct\n {\n _stateValues[key] = newValue;\n FireStateChanged(key, oldValue, newValue);\n }\n\n private void FireStateChanged(string key, T? oldValue, T newValue) where T : struct { StateChanged?.Invoke(this, new EditorStateChangedEventArgs(key, oldValue, newValue)); }\n\n private void FireStateChanged(string key, T? oldValue, T newValue) { StateChanged?.Invoke(this, new EditorStateChangedEventArgs(key, oldValue, newValue)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/ChannelAggregationStrategy.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// A strategy for aggregating multiple audio channels into a single channel.\n/// \npublic interface IChannelAggregationStrategy\n{\n /// \n /// Aggregates the specified frame of audio samples.\n /// \n void Aggregate(ReadOnlyMemory frame, Memory destination);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n}\n\n/// \n/// Provides predefined strategies for aggregating float audio channels.\n/// \npublic static class DefaultChannelAggregationStrategies\n{\n /// \n /// Gets the average aggregation strategy for float audio channels.\n /// \n public static IChannelAggregationStrategy Average { get; } = new AverageChannelAggregationStrategy();\n\n /// \n /// Gets the max aggregation strategy for float audio channels.\n /// \n public static IChannelAggregationStrategy Sum { get; } = new SumChannelAggregationStrategy();\n\n /// \n /// Gets the channel selection strategy for float audio channels.\n /// \n /// The index of the channel to use for aggregation.\n /// The channel selection strategy.\n public static IChannelAggregationStrategy SelectChannel(int channelIndex) { return new SelectChannelAggregationStrategy(channelIndex); }\n}\n\n/// \n/// Aggregates audio channels by computing the average of the samples.\n/// \ninternal class AverageChannelAggregationStrategy : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetAverageFloat(frame); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetAverageFloat(frame, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetAverageFloat(frame, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetAverageFloat(frame);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetAverageFloat(ReadOnlyMemory frame)\n {\n var span = frame.Span;\n var sum = 0.0f;\n for ( var i = 0; i < span.Length; i++ )\n {\n sum += span[i];\n }\n\n return sum / span.Length;\n }\n\n private static float GetAverageFloat(ReadOnlyMemory frame, ushort bitsPerSample)\n {\n var index = 0;\n var sum = 0f;\n var span = frame.Span;\n while ( index < frame.Length )\n {\n sum += SampleSerializer.ReadSample(span, ref index, bitsPerSample);\n }\n\n // We multiply by 8 first to avoid integer division\n return sum / (frame.Length * 8 / bitsPerSample);\n }\n}\n\n/// \n/// Aggregates float audio channels by selecting the maximum sample.\n/// \ninternal class SumChannelAggregationStrategy : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetSumFloat(frame); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetSumFloat(frame, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetSumFloat(frame, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetSumFloat(frame);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetSumFloat(ReadOnlyMemory frame)\n {\n var span = frame.Span;\n var sum = 0.0f;\n for ( var i = 0; i < span.Length; i++ )\n {\n sum += span[i];\n }\n\n // Ensure the float value is within the range (-1, 1)\n if ( sum > 1 )\n {\n sum = 1;\n }\n else if ( sum < -1 )\n {\n sum = -1;\n }\n\n return sum;\n }\n\n private static float GetSumFloat(ReadOnlyMemory frame, ushort bitsPerSample)\n {\n var index = 0;\n var sum = 0f;\n var span = frame.Span;\n while ( index < frame.Length )\n {\n sum += SampleSerializer.ReadSample(span, ref index, bitsPerSample);\n }\n\n // Ensure the float value is within the range (-1, 1)\n if ( sum > 1 )\n {\n sum = 1;\n }\n else if ( sum < -1 )\n {\n sum = -1;\n }\n\n return sum;\n }\n}\n\n/// \n/// Aggregates float audio channels by selecting a specific channel.\n/// \n/// The index of the channel to use for aggregation.\ninternal class SelectChannelAggregationStrategy(int channelIndex) : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetChannelFloat(frame, channelIndex); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetChannelFloat(frame, channelIndex, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetChannelFloat(frame, channelIndex, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetChannelFloat(frame, channelIndex);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetChannelFloat(ReadOnlyMemory frame, int channelIndex) { return frame.Span[channelIndex]; }\n\n private static float GetChannelFloat(ReadOnlyMemory frame, int channelIndex, ushort bitsPerSample)\n {\n var byteIndex = channelIndex * bitsPerSample / 8;\n\n return SampleSerializer.ReadSample(frame.Span, ref byteIndex, bitsPerSample);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/NotificationService.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements notification service\n/// \npublic class NotificationService : INotificationService\n{\n private readonly List _activeNotifications = new();\n\n public void ShowInfo(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Info, message, 5f, action, actionLabel)); }\n\n public void ShowSuccess(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Success, message, 5f, action, actionLabel)); }\n\n public void ShowWarning(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Warning, message, 8f, action, actionLabel)); }\n\n public void ShowError(string message, Action? action = null, string actionLabel = \"OK\") { AddNotification(new Notification(Notification.NotificationType.Error, message, 10f, action, actionLabel)); }\n\n public IReadOnlyList GetActiveNotifications() { return _activeNotifications.AsReadOnly(); }\n\n public void Update(float deltaTime)\n {\n // Update remaining time for each notification\n for ( var i = _activeNotifications.Count - 1; i >= 0; i-- )\n {\n var notification = _activeNotifications[i];\n notification.RemainingTime -= deltaTime;\n\n // Remove expired notifications\n if ( notification.RemainingTime <= 0 )\n {\n _activeNotifications.RemoveAt(i);\n }\n }\n }\n\n private void AddNotification(Notification notification)\n {\n // Limit the number of active notifications\n if ( _activeNotifications.Count >= 5 )\n {\n _activeNotifications.RemoveAt(0);\n }\n\n _activeNotifications.Add(notification);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismMath.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 数値計算などに使用するユーティリティクラス\n/// \npublic static class CubismMath\n{\n public const float Pi = 3.1415926535897932384626433832795f;\n\n public const float Epsilon = 0.00001f;\n\n /// \n /// 第一引数の値を最小値と最大値の範囲に収めた値を返す\n /// \n /// 収められる値\n /// 範囲の最小値\n /// 範囲の最大値\n /// 最小値と最大値の範囲に収めた値\n public static float RangeF(float value, float min, float max)\n {\n if ( value < min )\n {\n value = min;\n }\n else if ( value > max )\n {\n value = max;\n }\n\n return value;\n }\n\n /// \n /// イージング処理されたサインを求める\n /// フェードイン・アウト時のイージングに利用できる\n /// \n /// イージングを行う値\n /// イージング処理されたサイン値\n public static float GetEasingSine(float value)\n {\n if ( value < 0.0f )\n {\n return 0.0f;\n }\n\n if ( value > 1.0f )\n {\n return 1.0f;\n }\n\n return 0.5f - 0.5f * MathF.Cos(value * Pi);\n }\n\n /// \n /// 大きい方の値を返す。\n /// \n /// 左辺の値\n /// 右辺の値\n /// 大きい方の値\n public static float Max(float l, float r) { return l > r ? l : r; }\n\n /// \n /// 小さい方の値を返す。\n /// \n /// 左辺の値\n /// 右辺の値\n /// 小さい方の値\n public static float Min(float l, float r) { return l > r ? r : l; }\n\n /// \n /// 角度値をラジアン値に変換します。\n /// \n /// 角度値\n /// 角度値から変換したラジアン値\n public static float DegreesToRadian(float degrees) { return degrees / 180.0f * Pi; }\n\n /// \n /// ラジアン値を角度値に変換します。\n /// \n /// ラジアン値\n /// ラジアン値から変換した角度値\n public static float RadianToDegrees(float radian) { return radian * 180.0f / Pi; }\n\n /// \n /// 2つのベクトルからラジアン値を求めます。\n /// \n /// 始点ベクトル\n /// 終点ベクトル\n /// ラジアン値から求めた方向ベクトル\n public static float DirectionToRadian(Vector2 from, Vector2 to)\n {\n float q1;\n float q2;\n float ret;\n\n q1 = MathF.Atan2(to.Y, to.X);\n q2 = MathF.Atan2(from.Y, from.X);\n\n ret = q1 - q2;\n\n while ( ret < -Pi )\n {\n ret += Pi * 2.0f;\n }\n\n while ( ret > Pi )\n {\n ret -= Pi * 2.0f;\n }\n\n return ret;\n }\n\n /// \n /// 2つのベクトルから角度値を求めます。\n /// \n /// 始点ベクトル\n /// 終点ベクトル\n /// 角度値から求めた方向ベクトル\n public static float DirectionToDegrees(Vector2 from, Vector2 to)\n {\n float radian;\n float degree;\n\n radian = DirectionToRadian(from, to);\n degree = RadianToDegrees(radian);\n\n if ( to.X - from.X > 0.0f )\n {\n degree = -degree;\n }\n\n return degree;\n }\n\n /// \n /// ラジアン値を方向ベクトルに変換します。\n /// \n /// ラジアン値\n /// ラジアン値から変換した方向ベクトル\n public static Vector2 RadianToDirection(float totalAngle) { return new Vector2(MathF.Sin(totalAngle), MathF.Cos(totalAngle)); }\n\n /// \n /// 三次方程式の三次項の係数が0になったときに補欠的に二次方程式の解をもとめる。\n /// a * x^2 + b * x + c = 0\n /// \n /// 二次項の係数値\n /// 一次項の係数値\n /// 定数項の値\n /// 二次方程式の解\n public static float QuadraticEquation(float a, float b, float c)\n {\n if ( MathF.Abs(a) < Epsilon )\n {\n if ( MathF.Abs(b) < Epsilon )\n {\n return -c;\n }\n\n return -c / b;\n }\n\n return -(b + MathF.Sqrt(b * b - 4.0f * a * c)) / (2.0f * a);\n }\n\n /// \n /// カルダノの公式によってベジェのt値に該当する3次方程式の解を求める。\n /// 重解になったときには0.0~1.0の値になる解を返す。\n /// a * x^3 + b * x^2 + c * x + d = 0\n /// \n /// 三次項の係数値\n /// 二次項の係数値\n /// 一次項の係数値\n /// 定数項の値\n /// 0.0~1.0の間にある解\n public static float CardanoAlgorithmForBezier(float a, float b, float c, float d)\n {\n if ( MathF.Abs(a) < Epsilon )\n {\n return RangeF(QuadraticEquation(b, c, d), 0.0f, 1.0f);\n }\n\n var ba = b / a;\n var ca = c / a;\n var da = d / a;\n\n var p = (3.0f * ca - ba * ba) / 3.0f;\n var p3 = p / 3.0f;\n var q = (2.0f * ba * ba * ba - 9.0f * ba * ca + 27.0f * da) / 27.0f;\n var q2 = q / 2.0f;\n var discriminant = q2 * q2 + p3 * p3 * p3;\n\n var center = 0.5f;\n var threshold = center + 0.01f;\n\n float root1;\n float u1;\n\n if ( discriminant < 0.0f )\n {\n var mp3 = -p / 3.0f;\n var mp33 = mp3 * mp3 * mp3;\n var r = MathF.Sqrt(mp33);\n var t = -q / (2.0f * r);\n var cosphi = RangeF(t, -1.0f, 1.0f);\n var phi = MathF.Acos(cosphi);\n var crtr = MathF.Cbrt(r);\n var t1 = 2.0f * crtr;\n\n root1 = t1 * MathF.Cos(phi / 3.0f) - ba / 3.0f;\n if ( MathF.Abs(root1 - center) < threshold )\n {\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n var root2 = t1 * MathF.Cos((phi + 2.0f * Pi) / 3.0f) - ba / 3.0f;\n if ( MathF.Abs(root2 - center) < threshold )\n {\n return RangeF(root2, 0.0f, 1.0f);\n }\n\n var root3 = t1 * MathF.Cos((phi + 4.0f * Pi) / 3.0f) - ba / 3.0f;\n\n return RangeF(root3, 0.0f, 1.0f);\n }\n\n if ( discriminant == 0.0f )\n {\n if ( q2 < 0.0f )\n {\n u1 = MathF.Cbrt(-q2);\n }\n else\n {\n u1 = -MathF.Cbrt(q2);\n }\n\n root1 = 2.0f * u1 - ba / 3.0f;\n if ( MathF.Abs(root1 - center) < threshold )\n {\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n var root2 = -u1 - ba / 3.0f;\n\n return RangeF(root2, 0.0f, 1.0f);\n }\n\n var sd = MathF.Sqrt(discriminant);\n u1 = MathF.Cbrt(sd - q2);\n var v1 = MathF.Cbrt(sd + q2);\n root1 = u1 - v1 - ba / 3.0f;\n\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n /// \n /// 値を範囲内に納めて返す\n /// \n /// 範囲内か確認する値\n /// 最小値\n /// 最大値\n /// 範囲内に収まった値\n public static int Clamp(int val, int min, int max)\n {\n if ( val < min )\n {\n return min;\n }\n\n if ( max < val )\n {\n return max;\n }\n\n return val;\n }\n\n /// \n /// 値を範囲内に納めて返す\n /// \n /// 範囲内か確認する値\n /// 最小値\n /// 最大値\n /// 範囲内に収まった値\n public static float ClampF(float val, float min, float max)\n {\n if ( val < min )\n {\n return min;\n }\n\n if ( max < val )\n {\n return max;\n }\n\n return val;\n }\n\n /// \n /// 浮動小数点の余りを求める。\n /// \n /// 被除数(割られる値)\n /// 除数(割る値)\n /// 余り\n public static float ModF(float dividend, float divisor)\n {\n if ( !float.IsFinite(dividend) || divisor == 0 || float.IsNaN(dividend) || float.IsNaN(divisor) )\n {\n CubismLog.Warning(\"dividend: %f, divisor: %f ModF() returns 'NaN'.\", dividend, divisor);\n\n return float.NaN;\n }\n\n // 絶対値に変換する。\n var absDividend = MathF.Abs(dividend);\n var absDivisor = MathF.Abs(divisor);\n\n // 絶対値で割り算する。\n var result = absDividend - MathF.Floor(absDividend / absDivisor) * absDivisor;\n\n // 符号を被除数のものに指定する。\n return MathF.CopySign(result, dividend);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismMatrix44.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 4x4行列の便利クラス。\n/// \npublic record CubismMatrix44\n{\n private readonly float[] _mpt1 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n private readonly float[] _mpt2 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n private readonly float[] Ident = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n public float[] _mpt = new float[16];\n\n /// \n /// 4x4行列データ\n /// \n protected float[] _tr = new float[16];\n\n /// \n /// コンストラクタ。\n /// \n public CubismMatrix44() { LoadIdentity(); }\n\n public float[] Tr => _tr;\n\n /// \n /// 単位行列に初期化する。\n /// \n public void LoadIdentity() { SetMatrix(Ident); }\n\n /// \n /// 行列を設定する。\n /// \n /// 16個の浮動小数点数で表される4x4の行列\n public void SetMatrix(float[] tr) { Array.Copy(tr, _tr, 16); }\n\n public void SetMatrix(CubismMatrix44 tr) { SetMatrix(tr.Tr); }\n\n /// \n /// X軸の拡大率を取得する。\n /// \n /// X軸の拡大率\n public float GetScaleX() { return _tr[0]; }\n\n /// \n /// Y軸の拡大率を取得する。\n /// \n /// Y軸の拡大率\n public float GetScaleY() { return _tr[5]; }\n\n /// \n /// X軸の移動量を取得する。\n /// \n /// X軸の移動量\n public float GetTranslateX() { return _tr[12]; }\n\n /// \n /// Y軸の移動量を取得する。\n /// \n /// Y軸の移動量\n public float GetTranslateY() { return _tr[13]; }\n\n /// \n /// X軸の値を現在の行列で計算する。\n /// \n /// X軸の値\n /// 現在の行列で計算されたX軸の値\n public float TransformX(float src) { return _tr[0] * src + _tr[12]; }\n\n /// \n /// Y軸の値を現在の行列で計算する。\n /// \n /// Y軸の値\n /// 現在の行列で計算されたY軸の値\n public float TransformY(float src) { return _tr[5] * src + _tr[13]; }\n\n /// \n /// X軸の値を現在の行列で逆計算する。\n /// \n /// X軸の値\n /// 現在の行列で逆計算されたX軸の値\n public float InvertTransformX(float src) { return (src - _tr[12]) / _tr[0]; }\n\n /// \n /// Y軸の値を現在の行列で逆計算する。\n /// \n /// Y軸の値\n /// 現在の行列で逆計算されたY軸の値\n public float InvertTransformY(float src) { return (src - _tr[13]) / _tr[5]; }\n\n /// \n /// 現在の行列の位置を起点にして相対的に移動する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void TranslateRelative(float x, float y)\n {\n _mpt1[12] = x;\n _mpt1[13] = y;\n MultiplyByMatrix(_mpt1);\n }\n\n /// \n /// 現在の行列の位置を指定した位置へ移動する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void Translate(float x, float y)\n {\n _tr[12] = x;\n _tr[13] = y;\n }\n\n /// \n /// 現在の行列のX軸の位置を指定した位置へ移動する。\n /// \n /// X軸の移動量\n public void TranslateX(float x) { _tr[12] = x; }\n\n /// \n /// 現在の行列のY軸の位置を指定した位置へ移動する。\n /// \n /// Y軸の移動量\n public void TranslateY(float y) { _tr[13] = y; }\n\n /// \n /// 現在の行列の拡大率を相対的に設定する。\n /// \n /// X軸の拡大率\n /// Y軸の拡大率\n public void ScaleRelative(float x, float y)\n {\n _mpt2[0] = x;\n _mpt2[5] = y;\n MultiplyByMatrix(_mpt2);\n }\n\n /// \n /// 現在の行列の拡大率を指定した倍率に設定する。\n /// \n /// X軸の拡大率\n /// Y軸の拡大率\n public void Scale(float x, float y)\n {\n _tr[0] = x;\n _tr[5] = y;\n }\n\n public void MultiplyByMatrix(float[] a)\n {\n Array.Fill(_mpt, 0);\n\n var n = 4;\n\n for ( var i = 0; i < n; ++i )\n {\n for ( var j = 0; j < n; ++j )\n {\n for ( var k = 0; k < n; ++k )\n {\n _mpt[j + i * 4] += a[k + i * 4] * _tr[j + k * 4];\n }\n }\n }\n\n Array.Copy(_mpt, _tr, 16);\n }\n\n /// \n /// 現在の行列に行列を乗算する。\n /// \n /// 行列\n public void MultiplyByMatrix(CubismMatrix44 m) { MultiplyByMatrix(m.Tr); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismClippingManager_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic class CubismClippingManager_OpenGLES2(OpenGLApi gl) : CubismClippingManager(RenderType.OpenGL)\n{\n /// \n /// クリッピングコンテキストを作成する。モデル描画時に実行する。\n /// \n /// モデルのインスタンス\n /// レンダラのインスタンス\n /// フレームバッファ\n /// ビューポート\n internal unsafe void SetupClippingContext(CubismModel model, CubismRenderer_OpenGLES2 renderer, int lastFBO, int[] lastViewport)\n {\n // 全てのクリッピングを用意する\n // 同じクリップ(複数の場合はまとめて1つのクリップ)を使う場合は1度だけ設定する\n var usingClipCount = 0;\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // 1つのクリッピングマスクに関して\n var cc = ClippingContextListForMask[clipIndex];\n\n // このクリップを利用する描画オブジェクト群全体を囲む矩形を計算\n CalcClippedDrawTotalBounds(model, cc!);\n\n if ( cc!.IsUsing )\n {\n usingClipCount++; //使用中としてカウント\n }\n }\n\n if ( usingClipCount <= 0 )\n {\n return;\n }\n\n // マスク作成処理\n // 生成したOffscreenSurfaceと同じサイズでビューポートを設定\n gl.Viewport(0, 0, (int)ClippingMaskBufferSize.X, (int)ClippingMaskBufferSize.Y);\n\n // 後の計算のためにインデックスの最初をセット\n CurrentMaskBuffer = renderer.GetMaskBuffer(0);\n // ----- マスク描画処理 -----\n CurrentMaskBuffer.BeginDraw(lastFBO);\n\n renderer.PreDraw(); // バッファをクリアする\n\n // 各マスクのレイアウトを決定していく\n SetupLayoutBounds(usingClipCount);\n\n // サイズがレンダーテクスチャの枚数と合わない場合は合わせる\n if ( ClearedMaskBufferFlags.Count != RenderTextureCount )\n {\n ClearedMaskBufferFlags.Clear();\n\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n }\n else\n {\n // マスクのクリアフラグを毎フレーム開始時に初期化\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags[i] = false;\n }\n }\n\n // 実際にマスクを生成する\n // 全てのマスクをどの様にレイアウトして描くかを決定し、ClipContext , ClippedDrawContext に記憶する\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // --- 実際に1つのマスクを描く ---\n var clipContext = ClippingContextListForMask[clipIndex];\n var allClippedDrawRect = clipContext!.AllClippedDrawRect; //このマスクを使う、全ての描画オブジェクトの論理座標上の囲み矩形\n var layoutBoundsOnTex01 = clipContext.LayoutBounds; //この中にマスクを収める\n var MARGIN = 0.05f;\n\n // clipContextに設定したオフスクリーンサーフェイスをインデックスで取得\n var clipContextOffscreenSurface = renderer.GetMaskBuffer(clipContext.BufferIndex);\n\n // 現在のオフスクリーンサーフェイスがclipContextのものと異なる場合\n if ( CurrentMaskBuffer != clipContextOffscreenSurface )\n {\n CurrentMaskBuffer.EndDraw();\n CurrentMaskBuffer = clipContextOffscreenSurface;\n // マスク用RenderTextureをactiveにセット\n CurrentMaskBuffer.BeginDraw(lastFBO);\n\n // バッファをクリアする。\n renderer.PreDraw();\n }\n\n // モデル座標上の矩形を、適宜マージンを付けて使う\n TmpBoundsOnModel.SetRect(allClippedDrawRect);\n TmpBoundsOnModel.Expand(allClippedDrawRect.Width * MARGIN, allClippedDrawRect.Height * MARGIN);\n //########## 本来は割り当てられた領域の全体を使わず必要最低限のサイズがよい\n // シェーダ用の計算式を求める。回転を考慮しない場合は以下のとおり\n // movePeriod' = movePeriod * scaleX + offX [[ movePeriod' = (movePeriod - tmpBoundsOnModel.movePeriod)*scale + layoutBoundsOnTex01.movePeriod ]]\n var scaleX = layoutBoundsOnTex01.Width / TmpBoundsOnModel.Width;\n var scaleY = layoutBoundsOnTex01.Height / TmpBoundsOnModel.Height;\n\n // マスク生成時に使う行列を求める\n CreateMatrixForMask(false, layoutBoundsOnTex01, scaleX, scaleY);\n\n clipContext.MatrixForMask.SetMatrix(TmpMatrixForMask.Tr);\n clipContext.MatrixForDraw.SetMatrix(TmpMatrixForDraw.Tr);\n\n // 実際の描画を行う\n var clipDrawCount = clipContext.ClippingIdCount;\n for ( var i = 0; i < clipDrawCount; i++ )\n {\n var clipDrawIndex = clipContext.ClippingIdList[i];\n\n // 頂点情報が更新されておらず、信頼性がない場合は描画をパスする\n if ( !model.GetDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex) )\n {\n continue;\n }\n\n renderer.IsCulling = model.GetDrawableCulling(clipDrawIndex);\n\n // マスクがクリアされていないなら処理する\n if ( !ClearedMaskBufferFlags[clipContext.BufferIndex] )\n {\n // マスクをクリアする\n // 1が無効(描かれない)領域、0が有効(描かれる)領域。(シェーダーCd*Csで0に近い値をかけてマスクを作る。1をかけると何も起こらない)\n gl.ClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n gl.Clear(gl.GL_COLOR_BUFFER_BIT);\n ClearedMaskBufferFlags[clipContext.BufferIndex] = true;\n }\n\n // 今回専用の変換を適用して描く\n // チャンネルも切り替える必要がある(A,R,G,B)\n renderer.ClippingContextBufferForMask = clipContext;\n\n renderer.DrawMeshOpenGL(model, clipDrawIndex);\n }\n }\n\n // --- 後処理 ---\n CurrentMaskBuffer.EndDraw();\n renderer.ClippingContextBufferForMask = null;\n gl.Viewport(lastViewport[0], lastViewport[1], lastViewport[2], lastViewport[3]);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/DiscardableMemoryAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that can be discard samples at the beginning of the stream if not needed.\n/// \n/// \n/// It can store samples as floats or as bytes, or both. By default, it stores samples as floats.\n/// Based on your usage, you can choose to store samples as bytes, floats, or both.\n/// If storing them as floats, they will be deserialized from bytes when they are added and returned directly when\n/// requested.\n/// If storing them as bytes, they will be serialized from floats when they are added and returned directly when\n/// requested.\n/// If you want to optimize your memory usage, you can store them in the same format as they are added.\n/// If you want to optimize your CPU usage, you can store them in the format you want to use them in.\n/// \npublic class DiscardableMemoryAudioSource(\n IReadOnlyDictionary metadata,\n bool storeSamples = true,\n bool storeBytes = false,\n int initialSizeFloats = BufferedMemoryAudioSource.DefaultInitialSize,\n int initialSizeBytes = BufferedMemoryAudioSource.DefaultInitialSize,\n IChannelAggregationStrategy? aggregationStrategy = null)\n : BufferedMemoryAudioSource(metadata, storeSamples, storeBytes, initialSizeFloats, initialSizeBytes, aggregationStrategy), IDiscardableAudioSource\n{\n private long framesDiscarded;\n\n public long SampleVirtualCount => base.FramesCount;\n\n public override long FramesCount => base.FramesCount - framesDiscarded;\n\n public override TimeSpan Duration => TimeSpan.FromMilliseconds(SampleVirtualCount * 1000d / SampleRate);\n\n /// \n public virtual void DiscardFrames(int count)\n {\n ThrowIfNotInitialized();\n\n if ( count <= 0 )\n {\n throw new ArgumentOutOfRangeException(nameof(count), \"Count must be positive.\");\n }\n\n if ( count > FramesCount )\n {\n throw new ArgumentOutOfRangeException(nameof(count), \"Cannot discard more samples than available.\");\n }\n\n var framesToKeep = FramesCount - count;\n if ( FloatFrames != null )\n {\n var samplesToDiscard = count * ChannelCount;\n var samplesToKeep = framesToKeep * ChannelCount;\n Array.Copy(FloatFrames, samplesToDiscard, FloatFrames, 0, samplesToKeep);\n }\n\n if ( ByteFrames != null )\n {\n var bytesToDiscard = count * FrameSize;\n var bytesToKeep = framesToKeep * FrameSize;\n Array.Copy(ByteFrames, bytesToDiscard, ByteFrames, 0, bytesToKeep);\n }\n\n framesDiscarded += count;\n }\n\n /// \n public override Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(startFrame, framesDiscarded, nameof(startFrame));\n\n return base.GetSamplesAsync(startFrame - framesDiscarded, maxFrames, cancellationToken);\n }\n\n /// \n public override Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(startFrame, framesDiscarded, nameof(startFrame));\n\n return base.GetFramesAsync(startFrame - framesDiscarded, maxFrames, cancellationToken);\n }\n\n public override Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(startFrame, framesDiscarded, nameof(startFrame));\n\n return base.CopyFramesAsync(destination, startFrame - framesDiscarded, maxFrames, cancellationToken);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/ContentVec.cs", "using Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class ContentVec : IDisposable\n{\n private readonly InferenceSession _model;\n\n public ContentVec(string modelPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL,\n };\n\n options.AppendExecutionProvider_CPU();\n\n _model = new InferenceSession(modelPath, options);\n }\n\n public void Dispose() { _model?.Dispose(); }\n\n public DenseTensor Forward(ReadOnlyMemory wav)\n {\n // Create input tensor without unnecessary copying\n var tensor = new DenseTensor(new[] { 1, 1, wav.Length });\n var wavSpan = wav.Span;\n\n if ( wav.Length == 2 )\n {\n // Handle division by 2 for each element\n tensor[0, 0, 0] = wavSpan[0] / 2;\n tensor[0, 0, 1] = wavSpan[1] / 2;\n }\n else\n {\n // Process normally for all other lengths\n for ( var i = 0; i < wav.Length; i++ )\n {\n tensor[0, 0, i] = wavSpan[i];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.First(), tensor) };\n\n using var results = _model.Run(inputs);\n var output = results[0].AsTensor();\n\n // Process the output tensor\n return RVCUtils.Transpose(output, 0, 2, 1);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCUtils.cs", "using Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\ninternal static class RVCUtils\n{\n public static DenseTensor RepeatTensor(DenseTensor tensor, int times)\n {\n // Create output tensor with expanded dimensions\n var inputDims = tensor.Dimensions;\n var outputDims = inputDims.ToArray();\n outputDims[2] *= times;\n var result = new DenseTensor(outputDims);\n\n // Cache dimensions for faster access\n var dim0 = inputDims[0];\n var dim1 = inputDims[1];\n var dim2 = inputDims[2];\n var newDim2 = dim2 * times;\n\n // Compute strides for efficient indexing\n var inputStride1 = dim2;\n var inputStride0 = dim1 * inputStride1;\n\n var outputStride1 = newDim2;\n var outputStride0 = dim1 * outputStride1;\n\n // Use regular for-loop with thread partitioning instead of Parallel.For with lambda\n var totalBatches = dim0;\n var numThreads = Environment.ProcessorCount;\n var batchesPerThread = (totalBatches + numThreads - 1) / numThreads;\n\n Parallel.For(0, numThreads, threadIndex =>\n {\n // Calculate the range for this thread\n var startBatch = threadIndex * batchesPerThread;\n var endBatch = Math.Min(startBatch + batchesPerThread, totalBatches);\n\n // Process assigned batches without capturing Span\n for ( var i = startBatch; i < endBatch; i++ )\n {\n // Calculate base offsets for each dimension\n var inputBaseI = i * inputStride0;\n var outputBaseI = i * outputStride0;\n\n for ( var j = 0; j < dim1; j++ )\n {\n var inputBaseJ = inputBaseI + j * inputStride1;\n var outputBaseJ = outputBaseI + j * outputStride1;\n\n for ( var k = 0; k < dim2; k++ )\n {\n // Get input value using direct indexers\n var value = tensor.GetValue(inputBaseJ + k);\n var outputStartIdx = outputBaseJ + k * times;\n\n // Set output values in a loop\n for ( var t = 0; t < times; t++ )\n {\n result.SetValue(outputStartIdx + t, value);\n }\n }\n }\n }\n });\n\n return result;\n }\n\n public static DenseTensor Transpose(Tensor tensor, params int[] perm)\n {\n // Create output tensor with transposed dimensions\n var outputDims = new int[perm.Length];\n for ( var i = 0; i < perm.Length; i++ )\n {\n outputDims[i] = tensor.Dimensions[perm[i]];\n }\n\n var result = new DenseTensor(outputDims);\n\n // Optimize for the specific (0,2,1) permutation used in the codebase\n if ( tensor.Dimensions.Length == 3 && perm.Length == 3 &&\n perm[0] == 0 && perm[1] == 2 && perm[2] == 1 )\n {\n TransposeOptimized021(tensor, result);\n\n return result;\n }\n\n var rank = tensor.Dimensions.Length;\n\n // Precompute input strides for faster coordinate calculation\n var inputStrides = new int[rank];\n inputStrides[rank - 1] = 1;\n for ( var i = rank - 2; i >= 0; i-- )\n {\n inputStrides[i] = inputStrides[i + 1] * tensor.Dimensions[i + 1];\n }\n\n // Precompute output strides\n var outputStrides = new int[rank];\n outputStrides[rank - 1] = 1;\n for ( var i = rank - 2; i >= 0; i-- )\n {\n outputStrides[i] = outputStrides[i + 1] * outputDims[i + 1];\n }\n\n // Process in chunks for better parallelization\n const int chunkSize = 4096;\n var totalChunks = (tensor.Length + chunkSize - 1) / chunkSize;\n\n Parallel.For(0, totalChunks, chunkIdx =>\n {\n var startIdx = (int)chunkIdx * chunkSize;\n var endIdx = Math.Min(startIdx + chunkSize, tensor.Length);\n\n // Allocate coordinate array for this thread\n var coords = new int[rank];\n\n // Process this chunk\n for ( var flatIdx = startIdx; flatIdx < endIdx; flatIdx++ )\n {\n // Convert flat index to coordinates\n var remaining = flatIdx;\n for ( var dim = 0; dim < rank; dim++ )\n {\n coords[dim] = remaining / inputStrides[dim];\n remaining %= inputStrides[dim];\n }\n\n // Compute output index\n var outputIdx = 0;\n for ( var dim = 0; dim < rank; dim++ )\n {\n outputIdx += coords[perm[dim]] * outputStrides[dim];\n }\n\n // Transfer the value\n result.SetValue(outputIdx, tensor.GetValue(flatIdx));\n }\n });\n\n return result;\n }\n\n // Highly optimized method for the specific (0,2,1) permutation\n private static void TransposeOptimized021(Tensor input, DenseTensor output)\n {\n var dim0 = input.Dimensions[0];\n var dim1 = input.Dimensions[1];\n var dim2 = input.Dimensions[2];\n\n // Partitioning for parallel processing\n var numThreads = Environment.ProcessorCount;\n var batchesPerThread = (dim0 + numThreads - 1) / numThreads;\n\n Parallel.For(0, numThreads, threadIndex =>\n {\n var startBatch = threadIndex * batchesPerThread;\n var endBatch = Math.Min(startBatch + batchesPerThread, dim0);\n\n // Process batches assigned to this thread\n for ( var i = startBatch; i < endBatch; i++ )\n {\n // Compute base offsets for this batch\n var inputBatchOffset = i * dim1 * dim2;\n var outputBatchOffset = i * dim2 * dim1;\n\n // Cache-friendly block processing\n const int blockSize = 16; // Tuned for typical CPU cache line size\n\n // Process the 2D slice in blocks for better cache locality\n for ( var jBlock = 0; jBlock < dim1; jBlock += blockSize )\n {\n for ( var kBlock = 0; kBlock < dim2; kBlock += blockSize )\n {\n // Determine actual block boundaries\n var jEnd = Math.Min(jBlock + blockSize, dim1);\n var kEnd = Math.Min(kBlock + blockSize, dim2);\n\n // Process the block\n for ( var j = jBlock; j < jEnd; j++ )\n {\n var inputRowOffset = inputBatchOffset + j * dim2;\n\n for ( var k = kBlock; k < kEnd; k++ )\n {\n var inputIdx = inputRowOffset + k;\n var outputIdx = outputBatchOffset + k * dim1 + j;\n\n // Use element access methods instead of Span\n output.SetValue(outputIdx, input.GetValue(inputIdx));\n }\n }\n }\n }\n }\n });\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismBreath.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 呼吸機能を提供する。\n/// \npublic class CubismBreath\n{\n /// \n /// 積算時間[秒]\n /// \n private float _currentTime;\n\n /// \n /// 呼吸にひもづいているパラメータのリスト\n /// \n public required List Parameters { get; init; }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n _currentTime += deltaTimeSeconds;\n\n var t = _currentTime * 2.0f * 3.14159f;\n\n foreach ( var item in Parameters )\n {\n model.AddParameterValue(item.ParameterId, item.Offset +\n item.Peak * MathF.Sin(t / item.Cycle), item.Weight);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Core/CubismCore.cs", "using System.Numerics;\nusing System.Runtime.InteropServices;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Core;\n\npublic static class CsmEnum\n{\n //Alignment constraints.\n\n /// \n /// Necessary alignment for mocs (in bytes).\n /// \n public const int csmAlignofMoc = 64;\n\n /// \n /// Necessary alignment for models (in bytes).\n /// \n public const int CsmAlignofModel = 16;\n\n //Bit masks for non-dynamic drawable flags.\n\n /// \n /// Additive blend mode mask.\n /// \n public const byte CsmBlendAdditive = 1 << 0;\n\n /// \n /// Multiplicative blend mode mask.\n /// \n public const byte CsmBlendMultiplicative = 1 << 1;\n\n /// \n /// Double-sidedness mask.\n /// \n public const byte CsmIsDoubleSided = 1 << 2;\n\n /// \n /// Clipping mask inversion mode mask.\n /// \n public const byte CsmIsInvertedMask = 1 << 3;\n\n //Bit masks for dynamic drawable flags.\n\n /// \n /// Flag set when visible.\n /// \n public const byte CsmIsVisible = 1 << 0;\n\n /// \n /// Flag set when visibility did change.\n /// \n public const byte CsmVisibilityDidChange = 1 << 1;\n\n /// \n /// Flag set when opacity did change.\n /// \n public const byte CsmOpacityDidChange = 1 << 2;\n\n /// \n /// Flag set when draw order did change.\n /// \n public const byte CsmDrawOrderDidChange = 1 << 3;\n\n /// \n /// Flag set when render order did change.\n /// \n public const byte CsmRenderOrderDidChange = 1 << 4;\n\n /// \n /// Flag set when vertex positions did change.\n /// \n public const byte CsmVertexPositionsDidChange = 1 << 5;\n\n /// \n /// Flag set when blend color did change.\n /// \n public const byte CsmBlendColorDidChange = 1 << 6;\n\n //moc3 file format version.\n\n /// \n /// unknown\n /// \n public const int CsmMocVersion_Unknown = 0;\n\n /// \n /// moc3 file version 3.0.00 - 3.2.07\n /// \n public const int CsmMocVersion_30 = 1;\n\n /// \n /// moc3 file version 3.3.00 - 3.3.03\n /// \n public const int CsmMocVersion_33 = 2;\n\n /// \n /// moc3 file version 4.0.00 - 4.1.05\n /// \n public const int CsmMocVersion_40 = 3;\n\n /// \n /// moc3 file version 4.2.00 -\n /// \n public const int CsmMocVersion_42 = 4;\n\n //Parameter types.\n\n /// \n /// Normal parameter.\n /// \n public const int CsmParameterType_Normal = 0;\n\n /// \n /// Parameter for blend shape.\n /// \n public const int CsmParameterType_BlendShape = 1;\n}\n\n/// \n/// Log handler.\n/// \n/// Null-terminated string message to log.\npublic delegate void LogFunction(string message);\n\npublic static partial class CubismCore\n{\n //VERSION\n\n public static uint Version() { return GetVersion(); }\n\n /// \n /// Queries Core version.\n /// \n /// Core version.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetVersion\")]\n internal static partial uint GetVersion();\n\n /// \n /// Gets Moc file supported latest version.\n /// \n /// csmMocVersion (Moc file latest format version).\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetLatestMocVersion\")]\n internal static partial uint GetLatestMocVersion();\n\n /// \n /// Gets Moc file format version.\n /// \n /// Address of moc.\n /// Size of moc (in bytes).\n /// csmMocVersion\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetMocVersion\")]\n internal static partial uint GetMocVersion(IntPtr address, int size);\n\n //CONSISTENCY\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// '1' if Moc is valid; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmHasMocConsistency\")]\n [return: MarshalAs(UnmanagedType.I4)]\n internal static partial bool HasMocConsistency(IntPtr address, int size);\n\n //LOGGING\n\n /// \n /// Queries log handler.\n /// \n /// Log handler.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetLogFunction\")]\n internal static partial LogFunction GetLogFunction();\n\n /// \n /// Sets log handler.\n /// \n /// Handler to use.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmSetLogFunction\")]\n internal static partial void SetLogFunction(LogFunction handler);\n\n //MOC\n\n /// \n /// Tries to revive a moc from bytes in place.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmReviveMocInPlace\")]\n internal static partial IntPtr ReviveMocInPlace(IntPtr address, int size);\n\n //MODEL\n\n /// \n /// Queries size of a model in bytes.\n /// \n /// Moc to query.\n /// Valid size on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetSizeofModel\")]\n internal static partial int GetSizeofModel(IntPtr moc);\n\n /// \n /// Tries to instantiate a model in place.\n /// \n /// Source moc.\n /// Address to place instance at. Address must be aligned to 'csmAlignofModel'.\n /// Size of memory block for instance (in bytes).\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmInitializeModelInPlace\")]\n internal static partial IntPtr InitializeModelInPlace(IntPtr moc, IntPtr address, int size);\n\n /// \n /// Updates a model.\n /// \n /// Model to update.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmUpdateModel\")]\n internal static partial void UpdateModel(IntPtr model);\n\n //CANVAS\n\n /// \n /// Reads info on a model canvas.\n /// \n /// Model query.\n /// Canvas dimensions.\n /// Origin of model on canvas.\n /// Aspect used for scaling pixels to units.\n [DllImport(\"Live2DCubismCore\", EntryPoint = \"csmReadCanvasInfo\")]\n#pragma warning disable SYSLIB1054 // 使用 “LibraryImportAttribute” 而不是 “DllImportAttribute” 在编译时生成 P/Invoke 封送代码\n internal static extern void ReadCanvasInfo(IntPtr model, out Vector2 outSizeInPixels,\n#pragma warning restore SYSLIB1054 // 使用 “LibraryImportAttribute” 而不是 “DllImportAttribute” 在编译时生成 P/Invoke 封送代码\n out Vector2 outOriginInPixels, out float outPixelsPerUnit);\n\n //PARAMETERS\n\n /// \n /// Gets number of parameters.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterCount\")]\n internal static partial int GetParameterCount(IntPtr model);\n\n /// \n /// Gets parameter IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterIds\")]\n internal static unsafe partial sbyte** GetParameterIds(IntPtr model);\n\n /// \n /// Gets parameter types.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterTypes\")]\n internal static unsafe partial int* GetParameterTypes(IntPtr model);\n\n /// \n /// Gets minimum parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterMinimumValues\")]\n internal static unsafe partial float* GetParameterMinimumValues(IntPtr model);\n\n /// \n /// Gets maximum parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterMaximumValues\")]\n internal static unsafe partial float* GetParameterMaximumValues(IntPtr model);\n\n /// \n /// Gets default parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterDefaultValues\")]\n internal static unsafe partial float* GetParameterDefaultValues(IntPtr model);\n\n /// \n /// Gets read/write parameter values buffer.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterValues\")]\n internal static unsafe partial float* GetParameterValues(IntPtr model);\n\n /// \n /// Gets number of key values of each parameter.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterKeyCounts\")]\n internal static unsafe partial int* GetParameterKeyCounts(IntPtr model);\n\n /// \n /// Gets key values of each parameter.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterKeyValues\")]\n internal static unsafe partial float** GetParameterKeyValues(IntPtr model);\n\n //PARTS\n\n /// \n /// Gets number of parts.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartCount\")]\n internal static partial int GetPartCount(IntPtr model);\n\n /// \n /// Gets parts IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartIds\")]\n internal static unsafe partial sbyte** GetPartIds(IntPtr model);\n\n /// \n /// Gets read/write part opacities buffer.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartOpacities\")]\n internal static unsafe partial float* GetPartOpacities(IntPtr model);\n\n /// \n /// Gets part's parent part indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartParentPartIndices\")]\n internal static unsafe partial int* GetPartParentPartIndices(IntPtr model);\n\n //DRAWABLES\n\n /// \n /// Gets number of drawables.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableCount\")]\n internal static partial int GetDrawableCount(IntPtr model);\n\n /// \n /// Gets drawable IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIds\")]\n internal static unsafe partial sbyte** GetDrawableIds(IntPtr model);\n\n /// \n /// Gets constant drawable flags.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableConstantFlags\")]\n internal static unsafe partial byte* GetDrawableConstantFlags(IntPtr model);\n\n /// \n /// Gets dynamic drawable flags.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableDynamicFlags\")]\n internal static unsafe partial byte* GetDrawableDynamicFlags(IntPtr model);\n\n /// \n /// Gets drawable texture indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableTextureIndices\")]\n internal static unsafe partial int* GetDrawableTextureIndices(IntPtr model);\n\n /// \n /// Gets drawable draw orders.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableDrawOrders\")]\n internal static unsafe partial int* GetDrawableDrawOrders(IntPtr model);\n\n /// \n /// Gets drawable render orders.\n /// The higher the order, the more up front a drawable is.\n /// \n /// Model to query.\n /// Valid pointer on success; '0'otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableRenderOrders\")]\n internal static unsafe partial int* GetDrawableRenderOrders(IntPtr model);\n\n /// \n /// Gets drawable opacities.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableOpacities\")]\n internal static unsafe partial float* GetDrawableOpacities(IntPtr model);\n\n /// \n /// Gets numbers of masks of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMaskCounts\")]\n internal static unsafe partial int* GetDrawableMaskCounts(IntPtr model);\n\n /// \n /// Gets number of vertices of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMasks\")]\n internal static unsafe partial int** GetDrawableMasks(IntPtr model);\n\n /// \n /// Gets number of vertices of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexCounts\")]\n internal static unsafe partial int* GetDrawableVertexCounts(IntPtr model);\n\n /// \n /// Gets vertex position data of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; a null pointer otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexPositions\")]\n internal static unsafe partial Vector2** GetDrawableVertexPositions(IntPtr model);\n\n /// \n /// Gets texture coordinate data of each drawables.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexUvs\")]\n internal static unsafe partial Vector2** GetDrawableVertexUvs(IntPtr model);\n\n /// \n /// Gets number of triangle indices for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIndexCounts\")]\n internal static unsafe partial int* GetDrawableIndexCounts(IntPtr model);\n\n /// \n /// Gets triangle index data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIndices\")]\n internal static unsafe partial ushort** GetDrawableIndices(IntPtr model);\n\n /// \n /// Gets multiply color data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMultiplyColors\")]\n internal static unsafe partial Vector4* GetDrawableMultiplyColors(IntPtr model);\n\n /// \n /// Gets screen color data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableScreenColors\")]\n internal static unsafe partial Vector4* GetDrawableScreenColors(IntPtr model);\n\n /// \n /// Gets drawable's parent part indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableParentPartIndices\")]\n internal static unsafe partial int* GetDrawableParentPartIndices(IntPtr model);\n\n /// \n /// Resets all dynamic drawable flags.\n /// \n /// Model containing flags.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmResetDrawableDynamicFlags\")]\n internal static unsafe partial void ResetDrawableDynamicFlags(IntPtr model);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiThemeManager.cs", "using Hexa.NET.ImGui;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements UI theming management\n/// \npublic class UiThemeManager : IUiThemeManager\n{\n private UiTheme _currentTheme = new();\n\n public void ApplyTheme()\n {\n var style = ImGui.GetStyle();\n\n style.Colors[(int)ImGuiCol.Text] = _currentTheme.TextColor;\n style.Colors[(int)ImGuiCol.TextDisabled] = _currentTheme.TextDisabledColor;\n style.Colors[(int)ImGuiCol.WindowBg] = _currentTheme.WindowBgColor;\n style.Colors[(int)ImGuiCol.ChildBg] = _currentTheme.ChildBgColor;\n style.Colors[(int)ImGuiCol.PopupBg] = _currentTheme.PopupBgColor;\n style.Colors[(int)ImGuiCol.Border] = _currentTheme.BorderColor;\n style.Colors[(int)ImGuiCol.BorderShadow] = _currentTheme.BorderShadowColor;\n style.Colors[(int)ImGuiCol.FrameBg] = _currentTheme.FrameBgColor;\n style.Colors[(int)ImGuiCol.FrameBgHovered] = _currentTheme.FrameBgHoveredColor;\n style.Colors[(int)ImGuiCol.FrameBgActive] = _currentTheme.FrameBgActiveColor;\n style.Colors[(int)ImGuiCol.TitleBg] = _currentTheme.TitleBgColor;\n style.Colors[(int)ImGuiCol.TitleBgActive] = _currentTheme.TitleBgActiveColor;\n style.Colors[(int)ImGuiCol.TitleBgCollapsed] = _currentTheme.TitleBgCollapsedColor;\n style.Colors[(int)ImGuiCol.MenuBarBg] = _currentTheme.MenuBarBgColor;\n style.Colors[(int)ImGuiCol.ScrollbarBg] = _currentTheme.ScrollbarBgColor;\n style.Colors[(int)ImGuiCol.ScrollbarGrab] = _currentTheme.ScrollbarGrabColor;\n style.Colors[(int)ImGuiCol.ScrollbarGrabHovered] = _currentTheme.ScrollbarGrabHoveredColor;\n style.Colors[(int)ImGuiCol.ScrollbarGrabActive] = _currentTheme.ScrollbarGrabActiveColor;\n style.Colors[(int)ImGuiCol.CheckMark] = _currentTheme.CheckMarkColor;\n style.Colors[(int)ImGuiCol.SliderGrab] = _currentTheme.SliderGrabColor;\n style.Colors[(int)ImGuiCol.SliderGrabActive] = _currentTheme.SliderGrabActiveColor;\n style.Colors[(int)ImGuiCol.Button] = _currentTheme.ButtonColor;\n style.Colors[(int)ImGuiCol.ButtonHovered] = _currentTheme.ButtonHoveredColor;\n style.Colors[(int)ImGuiCol.ButtonActive] = _currentTheme.ButtonActiveColor;\n style.Colors[(int)ImGuiCol.Header] = _currentTheme.HeaderColor;\n style.Colors[(int)ImGuiCol.HeaderHovered] = _currentTheme.HeaderHoveredColor;\n style.Colors[(int)ImGuiCol.HeaderActive] = _currentTheme.HeaderActiveColor;\n style.Colors[(int)ImGuiCol.Separator] = _currentTheme.SeparatorColor;\n style.Colors[(int)ImGuiCol.SeparatorHovered] = _currentTheme.SeparatorHoveredColor;\n style.Colors[(int)ImGuiCol.SeparatorActive] = _currentTheme.SeparatorActiveColor;\n style.Colors[(int)ImGuiCol.ResizeGrip] = _currentTheme.ResizeGripColor;\n style.Colors[(int)ImGuiCol.ResizeGripHovered] = _currentTheme.ResizeGripHoveredColor;\n style.Colors[(int)ImGuiCol.ResizeGripActive] = _currentTheme.ResizeGripActiveColor;\n style.Colors[(int)ImGuiCol.Tab] = _currentTheme.TabColor;\n style.Colors[(int)ImGuiCol.TabHovered] = _currentTheme.TabHoveredColor;\n style.Colors[(int)ImGuiCol.TabSelected] = _currentTheme.TabActiveColor;\n style.Colors[(int)ImGuiCol.TabDimmed] = _currentTheme.TabUnfocusedColor;\n style.Colors[(int)ImGuiCol.TabDimmedSelected] = _currentTheme.TabUnfocusedActiveColor;\n style.Colors[(int)ImGuiCol.PlotLines] = _currentTheme.PlotLinesColor;\n style.Colors[(int)ImGuiCol.PlotLinesHovered] = _currentTheme.PlotLinesHoveredColor;\n style.Colors[(int)ImGuiCol.PlotHistogram] = _currentTheme.PlotHistogramColor;\n style.Colors[(int)ImGuiCol.PlotHistogramHovered] = _currentTheme.PlotHistogramHoveredColor;\n style.Colors[(int)ImGuiCol.TableHeaderBg] = _currentTheme.TableHeaderBgColor;\n style.Colors[(int)ImGuiCol.TableBorderStrong] = _currentTheme.TableBorderStrongColor;\n style.Colors[(int)ImGuiCol.TableBorderLight] = _currentTheme.TableBorderLightColor;\n style.Colors[(int)ImGuiCol.TableRowBg] = _currentTheme.TableRowBgColor;\n style.Colors[(int)ImGuiCol.TableRowBgAlt] = _currentTheme.TableRowBgAltColor;\n style.Colors[(int)ImGuiCol.TextSelectedBg] = _currentTheme.TextSelectedBgColor;\n style.Colors[(int)ImGuiCol.DragDropTarget] = _currentTheme.DragDropTargetColor;\n style.Colors[(int)ImGuiCol.NavWindowingHighlight] = _currentTheme.NavWindowingHighlightColor;\n style.Colors[(int)ImGuiCol.NavWindowingDimBg] = _currentTheme.NavWindowingDimBgColor;\n style.Colors[(int)ImGuiCol.ModalWindowDimBg] = _currentTheme.ModalWindowDimBgColor;\n\n // Set style properties\n style.Alpha = _currentTheme.Alpha;\n style.DisabledAlpha = _currentTheme.DisabledAlpha;\n style.WindowRounding = _currentTheme.WindowRounding;\n style.WindowBorderSize = _currentTheme.WindowBorderSize;\n style.WindowMinSize = _currentTheme.WindowMinSize;\n style.WindowTitleAlign = _currentTheme.WindowTitleAlign;\n\n // Handle WindowMenuButtonPosition\n if ( _currentTheme.WindowMenuButtonPosition == \"Left\" )\n {\n style.WindowMenuButtonPosition = ImGuiDir.Left;\n }\n else if ( _currentTheme.WindowMenuButtonPosition == \"Right\" )\n {\n style.WindowMenuButtonPosition = ImGuiDir.Right;\n }\n\n style.ChildRounding = _currentTheme.ChildRounding;\n style.ChildBorderSize = _currentTheme.ChildBorderSize;\n style.PopupRounding = _currentTheme.PopupRounding;\n style.PopupBorderSize = _currentTheme.PopupBorderSize;\n style.FrameRounding = _currentTheme.FrameRounding;\n style.FrameBorderSize = _currentTheme.FrameBorderSize;\n style.ItemSpacing = _currentTheme.ItemSpacing;\n style.ItemInnerSpacing = _currentTheme.ItemInnerSpacing;\n style.CellPadding = _currentTheme.CellPadding;\n style.IndentSpacing = _currentTheme.IndentSpacing;\n style.ColumnsMinSpacing = _currentTheme.ColumnsMinSpacing;\n style.ScrollbarSize = _currentTheme.ScrollbarSize;\n style.ScrollbarRounding = _currentTheme.ScrollbarRounding;\n style.GrabMinSize = _currentTheme.GrabMinSize;\n style.GrabRounding = _currentTheme.GrabRounding;\n style.TabRounding = _currentTheme.TabRounding;\n style.TabBorderSize = _currentTheme.TabBorderSize;\n style.TabCloseButtonMinWidthSelected = _currentTheme.TabCloseButtonMinWidthSelected;\n style.TabCloseButtonMinWidthUnselected = _currentTheme.TabCloseButtonMinWidthUnselected;\n\n // Handle ColorButtonPosition\n if ( _currentTheme.ColorButtonPosition == \"Left\" )\n {\n style.ColorButtonPosition = ImGuiDir.Left;\n }\n else if ( _currentTheme.ColorButtonPosition == \"Right\" )\n {\n style.ColorButtonPosition = ImGuiDir.Right;\n }\n\n style.ButtonTextAlign = _currentTheme.ButtonTextAlign;\n style.SelectableTextAlign = _currentTheme.SelectableTextAlign;\n style.WindowPadding = _currentTheme.WindowPadding;\n style.FramePadding = _currentTheme.FramePadding;\n }\n\n public void SetTheme(UiTheme theme)\n {\n _currentTheme = theme;\n ApplyTheme();\n }\n\n public UiTheme GetCurrentTheme() { return _currentTheme; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/TextMeasurer.cs", "using System.Collections.Concurrent;\nusing System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Measures text dimensions using a specific font and caches the results.\n/// Provides information about available rendering width and line height.\n/// Thread-safe for use in concurrent processing.\n/// \npublic class TextMeasurer\n{\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly float _sideMargin;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n public TextMeasurer(DynamicSpriteFont font, float sideMargin, int initialWidth, int initialHeight)\n {\n Font = font;\n _sideMargin = sideMargin;\n UpdateViewport(initialWidth, initialHeight);\n LineHeight = Font.MeasureString(\"Ay\").Y;\n if ( LineHeight <= 0 )\n {\n LineHeight = Font.FontSize;\n }\n }\n\n public float AvailableWidth { get; private set; }\n\n public float LineHeight { get; private set; }\n\n public DynamicSpriteFont Font { get; }\n\n public void UpdateViewport(int width, int height)\n {\n _viewportWidth = width;\n _viewportHeight = height;\n AvailableWidth = Math.Max(1, _viewportWidth - 2 * _sideMargin);\n _cache.Clear();\n }\n\n public Vector2 MeasureText(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Vector2.Zero;\n }\n\n return _cache.GetOrAdd(text, t => Font.MeasureString(t));\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/LexiconUtils.cs", "using System.Collections.Concurrent;\nusing System.Runtime.CompilerServices;\nusing System.Text;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class LexiconUtils\n{\n private static readonly ConcurrentDictionary _parentTagCache = new(StringComparer.Ordinal);\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static string? GetParentTag(string? tag)\n {\n if ( tag == null )\n {\n return null;\n }\n\n if ( _parentTagCache.TryGetValue(tag, out var cachedParent) )\n {\n return cachedParent;\n }\n\n string parent;\n if ( tag.StartsWith(\"VB\") )\n {\n parent = \"VERB\";\n }\n else if ( tag.StartsWith(\"NN\") )\n {\n parent = \"NOUN\";\n }\n else if ( tag.StartsWith(\"ADV\") || tag.StartsWith(\"RB\") )\n {\n parent = \"ADV\";\n }\n else if ( tag.StartsWith(\"ADJ\") || tag.StartsWith(\"JJ\") )\n {\n parent = \"ADJ\";\n }\n else\n {\n parent = tag;\n }\n\n _parentTagCache[tag] = parent;\n\n return parent;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static string Capitalize(ReadOnlySpan str)\n {\n if ( str.IsEmpty )\n {\n return string.Empty;\n }\n\n // Fast path for single-character strings\n if ( str.Length == 1 )\n {\n return char.ToUpper(str[0]).ToString();\n }\n\n // Avoid allocation if already capitalized\n if ( char.IsUpper(str[0]) )\n {\n return str.ToString();\n }\n\n var result = new StringBuilder(str.Length);\n result.Append(char.ToUpper(str[0]));\n result.Append(str.Slice(1));\n\n return result.ToString();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanityDetectorOnnx.cs", "using Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\nusing Microsoft.ML.Tokenizers;\n\nnamespace PersonaEngine.Lib.TTS.Profanity;\n\npublic class ProfanityDetectorOnnx : IDisposable\n{\n private readonly InferenceSession _session;\n\n private readonly Tokenizer _tokenizer;\n\n public ProfanityDetectorOnnx(string? modelPath = null, string? vocabPath = null)\n {\n if ( modelPath == null )\n {\n modelPath = ModelUtils.GetModelPath(ModelType.TinyToxic);\n }\n\n if ( vocabPath == null )\n {\n vocabPath = ModelUtils.GetModelPath(ModelType.TinyToxicVocab);\n }\n\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n using Stream vocabStream = File.OpenRead(vocabPath);\n _tokenizer = BertTokenizer.Create(vocabStream);\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n private IEnumerable Tokenize(string sentence) { return _tokenizer.EncodeToIds(sentence).Select(x => (long)x); }\n\n public float Run(string sentence)\n {\n var inputIds = Tokenize(sentence).ToArray();\n var inputIdsTensor = new DenseTensor(inputIds, new[] { 1, inputIds.Length });\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input_ids\", inputIdsTensor) };\n\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray().Single();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/ILive2DAnimationService.cs", "using PersonaEngine.Lib.Audio.Player;\nusing PersonaEngine.Lib.Live2D.App;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour;\n\n/// \n/// Generic interface for services that animate Live2D model parameters\n/// based on various input sources (audio, text content, emotions, etc.).\n/// \npublic interface ILive2DAnimationService : IDisposable\n{\n /// \n /// Starts the animation processing. This activates the service to\n /// begin listening for events and modifying parameters.\n /// \n void Start(LAppModel model);\n\n /// \n /// Stops the animation processing. Parameter values might be reset to neutral\n /// or held, depending on the implementation.\n /// \n void Stop();\n\n /// \n /// Updates the animation state, typically called once per frame.\n /// This method calculates and applies parameter values to the Live2D model\n /// based on the current input data and timing.\n /// \n /// The time elapsed since the last frame/update, in seconds.\n void Update(float deltaTime);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserData.cs", "using System.Text.Json;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// ユーザデータをロード、管理、検索インターフェイス、解放までを行う。\n/// \npublic class CubismModelUserData\n{\n public const string ArtMesh = \"ArtMesh\";\n\n public const string Meta = \"Meta\";\n\n public const string UserDataCount = \"UserDataCount\";\n\n public const string TotalUserDataSize = \"TotalUserDataSize\";\n\n public const string UserData = \"UserData\";\n\n public const string Target = \"Target\";\n\n public const string Id = \"Id\";\n\n public const string Value = \"Value\";\n\n /// \n /// ユーザデータ構造体配列\n /// \n private readonly List _userDataNodes = [];\n\n /// \n /// 閲覧リスト保持\n /// \n public readonly List ArtMeshUserDataNodes = [];\n\n /// \n /// userdata3.jsonをパースする。\n /// \n /// userdata3.jsonが読み込まれいるバッファ\n public CubismModelUserData(string data)\n {\n using var stream = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismModelUserDataObjContext.Default.CubismModelUserDataObj)\n ?? throw new Exception(\"Load UserData error\");\n\n var typeOfArtMesh = CubismFramework.CubismIdManager.GetId(ArtMesh);\n\n var nodeCount = obj.Meta.UserDataCount;\n\n for ( var i = 0; i < nodeCount; i++ )\n {\n var node = obj.UserData[i];\n CubismModelUserDataNode addNode = new() { TargetId = CubismFramework.CubismIdManager.GetId(node.Id), TargetType = CubismFramework.CubismIdManager.GetId(node.Target), Value = CubismFramework.CubismIdManager.GetId(node.Value) };\n _userDataNodes.Add(addNode);\n\n if ( addNode.TargetType == typeOfArtMesh )\n {\n ArtMeshUserDataNodes.Add(addNode);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Metrics/ConversationMetrics.cs", "using System.Diagnostics;\nusing System.Diagnostics.Metrics;\n\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Metrics;\n\npublic sealed class ConversationMetrics : IDisposable\n{\n public const string MeterName = \"PersonaEngine.Conversation\";\n\n private readonly Histogram _audioPlaybackDurationMs;\n\n private readonly Histogram _endToEndTurnDurationMs;\n\n private readonly Counter _errorsCounter;\n\n private readonly Histogram _firstAudioLatencyMs;\n\n private readonly Histogram _llmResponseDurationMs;\n\n private readonly Meter _meter;\n\n private readonly Histogram _sttSegmentDurationMs;\n\n private readonly Histogram _ttsSynthesisDurationMs;\n\n private readonly Counter _turnsInterruptedCounter;\n\n private readonly Counter _turnsStartedCounter;\n\n public ConversationMetrics(IMeterFactory meterFactory)\n {\n _meter = meterFactory.Create(MeterName);\n\n _endToEndTurnDurationMs = _meter.CreateHistogram(\n \"personaengine.conversation.turn.duration\",\n \"ms\",\n \"End-to-end duration of a conversation turn (Input Finalized to Audio End).\");\n\n _llmResponseDurationMs = _meter.CreateHistogram(\n \"personaengine.conversation.llm.duration\",\n \"ms\",\n \"Duration of LLM response generation (Request Sent to Stream End).\");\n\n _ttsSynthesisDurationMs = _meter.CreateHistogram(\n \"personaengine.conversation.tts.duration\",\n \"ms\",\n \"Duration of TTS synthesis (First Input Chunk to Stream End).\");\n\n _firstAudioLatencyMs = _meter.CreateHistogram(\n \"personaengine.conversation.turn.first_audio_latency\",\n \"ms\",\n \"Latency from user input finalization to the start of the assistant's audio playback.\");\n\n _audioPlaybackDurationMs = _meter.CreateHistogram(\n \"personaengine.conversation.audio.playback.duration\",\n \"ms\",\n \"Duration of audio playback for the assistant's response.\");\n\n _sttSegmentDurationMs = _meter.CreateHistogram(\n \"personaengine.conversation.stt.segment.duration\",\n \"ms\",\n \"Duration of STT processing for a single recognized segment.\");\n\n _turnsStartedCounter = _meter.CreateCounter(\n \"personaengine.conversation.turns.started.count\",\n \"{turn}\",\n \"Number of conversation turns started.\");\n\n _turnsInterruptedCounter = _meter.CreateCounter(\n \"personaengine.conversation.turns.interrupted.count\",\n \"{turn}\",\n \"Number of conversation turns interrupted by barge-in.\");\n\n _errorsCounter = _meter.CreateCounter(\n \"personaengine.conversation.errors.count\",\n \"{error}\",\n \"Number of errors encountered during conversation processing.\");\n }\n\n public void Dispose() { _meter.Dispose(); }\n\n public void RecordTurnDuration(double durationMs, Guid sessionId, Guid turnId, CompletionReason reason)\n {\n if ( !_endToEndTurnDurationMs.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"TurnId\", turnId.ToString() }, { \"FinishReason\", reason.ToString() } };\n\n _endToEndTurnDurationMs.Record(durationMs, tags);\n }\n\n public void RecordLlmDuration(double durationMs, Guid sessionId, Guid turnId, CompletionReason reason)\n {\n if ( !_llmResponseDurationMs.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"TurnId\", turnId.ToString() }, { \"FinishReason\", reason.ToString() } };\n\n _llmResponseDurationMs.Record(durationMs, tags);\n }\n\n public void RecordTtsDuration(double durationMs, Guid sessionId, Guid turnId, CompletionReason reason)\n {\n if ( !_ttsSynthesisDurationMs.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"TurnId\", turnId.ToString() }, { \"FinishReason\", reason.ToString() } };\n\n _ttsSynthesisDurationMs.Record(durationMs, tags);\n }\n\n public void RecordAudioPlaybackDuration(double durationMs, Guid sessionId, Guid turnId, CompletionReason reason)\n {\n if ( !_audioPlaybackDurationMs.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"TurnId\", turnId.ToString() }, { \"FinishReason\", reason.ToString() } };\n\n _audioPlaybackDurationMs.Record(durationMs, tags);\n }\n\n public void RecordSttSegmentDuration(double durationMs, Guid sessionId, string participantId)\n {\n if ( !_sttSegmentDurationMs.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"ParticipantId\", participantId } };\n\n _sttSegmentDurationMs.Record(durationMs, tags);\n }\n\n public void IncrementTurnsStarted(Guid sessionId)\n {\n if ( !_turnsStartedCounter.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() } };\n _turnsStartedCounter.Add(1, tags);\n }\n\n public void IncrementTurnsInterrupted(Guid sessionId, Guid turnId)\n {\n if ( !_turnsInterruptedCounter.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"TurnId\", turnId.ToString() } };\n _turnsInterruptedCounter.Add(1, tags);\n }\n\n public void IncrementErrors(Guid sessionId, Guid? turnId, Exception exception)\n {\n if ( !_errorsCounter.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"ErrorType\", exception.GetType().Name } };\n\n if ( turnId.HasValue )\n {\n tags.Add(new KeyValuePair(\"TurnId\", turnId.Value.ToString()));\n }\n\n _errorsCounter.Add(1, tags);\n }\n\n public void RecordFirstAudioLatency(double durationMs, Guid sessionId, Guid turnId)\n {\n if ( !_firstAudioLatencyMs.Enabled )\n {\n return;\n }\n\n var tags = new TagList { { \"SessionId\", sessionId.ToString() }, { \"TurnId\", turnId.ToString() } };\n\n _firstAudioLatencyMs.Record(durationMs, tags);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SilenceAudioSource.cs", "using System.Buffers;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that stores a continuous memory with only silence and returns it when needed.\n/// \npublic sealed class SilenceAudioSource : IAudioSource\n{\n private readonly Lazy byteSilence;\n\n private readonly Lazy floatSilence;\n\n private readonly bool useMemoryPool;\n\n public SilenceAudioSource(TimeSpan duration, uint sampleRate, IReadOnlyDictionary metadata, ushort channelCount = 1, ushort bitsPerSample = 16, bool useMemoryPool = true)\n {\n SampleRate = sampleRate;\n Metadata = metadata;\n ChannelCount = channelCount;\n BitsPerSample = bitsPerSample;\n this.useMemoryPool = useMemoryPool;\n Duration = duration;\n FramesCount = (long)(duration.TotalSeconds * sampleRate);\n\n byteSilence = new Lazy(GenerateByteSilence);\n floatSilence = new Lazy(GenerateFloatSilence);\n }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration { get; }\n\n public TimeSpan TotalDuration => Duration;\n\n public uint SampleRate { get; }\n\n public long FramesCount { get; }\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public void Dispose()\n {\n if ( useMemoryPool )\n {\n // We don't want to clear this as it is silence anyway (no user data to clear)\n if ( byteSilence.IsValueCreated )\n {\n ArrayPool.Shared.Return(byteSilence.Value);\n }\n\n if ( floatSilence.IsValueCreated )\n {\n ArrayPool.Shared.Return(floatSilence.Value, true);\n }\n }\n }\n\n public Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var startIndex = (int)(startFrame * frameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * frameSize);\n\n var slice = byteSilence.Value.AsMemory(startIndex, lengthBytes);\n\n return Task.FromResult(slice);\n }\n\n public Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var startIndex = (int)(startFrame * ChannelCount);\n var lengthSamples = (int)(Math.Min(maxFrames, FramesCount - startFrame) * ChannelCount);\n\n var slice = floatSilence.Value.AsMemory(startIndex, lengthSamples);\n\n return Task.FromResult(slice);\n }\n\n public Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var startIndex = (int)(startFrame * frameSize);\n var lengthBytes = (int)(Math.Min(maxFrames, FramesCount - startFrame) * frameSize);\n\n var slice = byteSilence.Value.AsMemory(startIndex, lengthBytes);\n slice.CopyTo(destination);\n var frames = lengthBytes / frameSize;\n\n return Task.FromResult(frames);\n }\n\n private byte[] GenerateByteSilence()\n {\n var frameSize = ChannelCount * BitsPerSample / 8;\n var totalBytes = FramesCount * frameSize;\n\n var silence = useMemoryPool ? ArrayPool.Shared.Rent((int)totalBytes) : new byte[totalBytes];\n\n // 8-bit PCM silence is centered at 128, not 0\n if ( BitsPerSample == 8 )\n {\n Array.Fill(silence, 128, 0, (int)totalBytes);\n }\n else\n {\n Array.Clear(silence, 0, (int)totalBytes); // Zero out for non-8-bit audio\n }\n\n return silence;\n }\n\n private float[] GenerateFloatSilence()\n {\n var totalSamples = FramesCount * ChannelCount;\n var silence = useMemoryPool ? ArrayPool.Shared.Rent((int)totalSamples) : new float[totalSamples];\n\n Array.Clear(silence, 0, (int)totalSamples); // Silence is zeroed-out memory\n\n return silence;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/ConcatAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that concatenates multiple audio sources\n/// \npublic sealed class ConcatAudioSource : IAudioSource\n{\n private readonly IAudioSource[] sources;\n\n public ConcatAudioSource(IAudioSource[] sources, IReadOnlyDictionary metadata)\n {\n this.sources = sources;\n Metadata = metadata;\n if ( sources.Length == 0 )\n {\n throw new ArgumentException(\"At least one source must be provided.\", nameof(sources));\n }\n\n var duration = TimeSpan.Zero;\n var sampleRate = sources[0].SampleRate;\n var framesCount = 0L;\n var channelCount = sources[0].ChannelCount;\n var bitsPerSample = sources[0].BitsPerSample;\n var totalDuration = TimeSpan.Zero;\n\n for ( var i = 0; i < sources.Length; i++ )\n {\n duration += sources[i].Duration;\n totalDuration += sources[i].TotalDuration;\n framesCount += sources[i].FramesCount;\n if ( channelCount != sources[i].ChannelCount )\n {\n throw new ArgumentException(\"All sources must have the same channel count.\", nameof(sources));\n }\n\n if ( sampleRate != sources[i].SampleRate )\n {\n throw new ArgumentException(\"All sources must have the same sample rate.\", nameof(sources));\n }\n\n if ( bitsPerSample != sources[i].BitsPerSample )\n {\n throw new ArgumentException(\"All sources must have the same bits per sample.\", nameof(sources));\n }\n }\n\n Duration = duration;\n SampleRate = sampleRate;\n FramesCount = framesCount;\n ChannelCount = channelCount;\n BitsPerSample = bitsPerSample;\n TotalDuration = totalDuration;\n }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration { get; }\n\n public TimeSpan TotalDuration { get; }\n\n public uint SampleRate { get; }\n\n public long FramesCount { get; }\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public void Dispose()\n {\n foreach ( var source in sources )\n {\n source.Dispose();\n }\n }\n\n public async Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var slices = await GetMemorySlicesAsync(\n (source, offset, frames, token) => source.GetFramesAsync(offset, frames, token),\n startFrame,\n maxFrames,\n cancellationToken);\n\n return MergeMemorySlices(slices);\n }\n\n public async Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var slices = await GetMemorySlicesAsync(\n (source, offset, frames, token) => source.GetSamplesAsync(offset, frames, token),\n startFrame,\n maxFrames,\n cancellationToken);\n\n return MergeMemorySlices(slices);\n }\n\n public async Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var slices = await GetMemorySlicesAsync(\n (source, offset, frames, token) => source.GetFramesAsync(offset, frames, token),\n startFrame,\n maxFrames,\n cancellationToken);\n\n CopySlices(slices, destination);\n long length = slices.Sum(slice => slice.Length);\n\n return (int)(length / BitsPerSample * 8 / ChannelCount);\n }\n\n private async Task>> GetMemorySlicesAsync(Func>> getMemoryFunc,\n long startFrame,\n int maxFrames,\n CancellationToken cancellationToken)\n {\n var result = new List>();\n var framesToRead = maxFrames;\n var offset = startFrame;\n\n foreach ( var source in sources )\n {\n if ( offset >= source.FramesCount )\n {\n offset -= source.FramesCount;\n\n continue;\n }\n\n var framesFromThisSource = Math.Min(framesToRead, (int)(source.FramesCount - offset));\n var memory = await getMemoryFunc(source, offset, framesFromThisSource, cancellationToken);\n\n result.Add(memory);\n\n framesToRead -= framesFromThisSource;\n offset = 0;\n\n if ( framesToRead <= 0 )\n {\n break;\n }\n }\n\n return result;\n }\n\n private static Memory MergeMemorySlices(List> slices)\n {\n if ( slices.Count == 1 )\n {\n return slices[0]; // If all frames/samples are from a single source, return directly\n }\n\n var totalSize = slices.Sum(slice => slice.Length);\n var merged = new T[totalSize];\n CopySlices(slices, merged);\n\n return merged.AsMemory();\n }\n\n private static void CopySlices(List> slices, Memory destination)\n {\n var position = 0;\n\n foreach ( var slice in slices )\n {\n slice.CopyTo(destination.Slice(position));\n position += slice.Length;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Token.cs", "using System.Runtime.CompilerServices;\nusing System.Text;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record Token\n{\n public string Text { get; set; } = string.Empty;\n\n public string Tag { get; set; } = string.Empty;\n\n public string Whitespace { get; set; } = string.Empty;\n\n public bool IsHead { get; set; } = true;\n\n public string? Alias { get; set; }\n\n public string? Phonemes { get; set; }\n\n public double? Stress { get; set; }\n\n public string? Currency { get; set; }\n\n public string NumFlags { get; set; } = string.Empty;\n\n public bool Prespace { get; set; }\n\n public int? Rating { get; set; }\n\n public double? StartTs { get; set; }\n\n public double? EndTs { get; set; }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static Token MergeTokens(List tokens, string? unk = null)\n {\n if ( tokens.Count == 0 )\n {\n throw new ArgumentException(\"Cannot merge empty token list\", nameof(tokens));\n }\n\n if ( tokens.Count == 1 )\n {\n return tokens[0];\n }\n\n var stressValues = new HashSet();\n var currencyValues = new HashSet();\n var ratingValues = new HashSet();\n string? phonemes;\n\n foreach ( var t in tokens )\n {\n if ( t.Stress.HasValue )\n {\n stressValues.Add(t.Stress);\n }\n\n if ( t.Currency != null )\n {\n currencyValues.Add(t.Currency);\n }\n\n ratingValues.Add(t.Rating);\n }\n\n if ( unk == null )\n {\n phonemes = null;\n }\n else\n {\n var sb = new StringBuilder();\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var t = tokens[i];\n if ( t.Prespace && sb.Length > 0 &&\n sb[sb.Length - 1] != ' ' &&\n !string.IsNullOrEmpty(t.Phonemes) )\n {\n sb.Append(' ');\n }\n\n sb.Append(t.Phonemes == null ? unk : t.Phonemes);\n }\n\n phonemes = sb.ToString();\n }\n\n // Get tag from token with highest \"weight\"\n var tag = tokens[0].Tag;\n var maxWeight = GetTagWeight(tokens[0]);\n\n for ( var i = 1; i < tokens.Count; i++ )\n {\n var weight = GetTagWeight(tokens[i]);\n if ( weight > maxWeight )\n {\n maxWeight = weight;\n tag = tokens[i].Tag;\n }\n }\n\n // Concatenate text and whitespace\n var textBuilder = new StringBuilder();\n for ( var i = 0; i < tokens.Count - 1; i++ )\n {\n textBuilder.Append(tokens[i].Text);\n textBuilder.Append(tokens[i].Whitespace);\n }\n\n textBuilder.Append(tokens[tokens.Count - 1].Text);\n\n // Build num flags\n var numFlagsBuilder = new StringBuilder();\n var flagsSet = new HashSet();\n\n foreach ( var t in tokens )\n {\n foreach ( var c in t.NumFlags )\n {\n flagsSet.Add(c);\n }\n }\n\n foreach ( var c in flagsSet.OrderBy(c => c) )\n {\n numFlagsBuilder.Append(c);\n }\n\n return new Token {\n Text = textBuilder.ToString(),\n Tag = tag,\n Whitespace = tokens[tokens.Count - 1].Whitespace,\n IsHead = tokens[0].IsHead,\n Alias = null,\n Phonemes = phonemes,\n Stress = stressValues.Count == 1 ? stressValues.First() : null,\n Currency = currencyValues.Any() ? currencyValues.OrderByDescending(c => c).First() : null,\n NumFlags = numFlagsBuilder.ToString(),\n Prespace = tokens[0].Prespace,\n Rating = ratingValues.Contains(null) ? null : ratingValues.Min(),\n StartTs = tokens[0].StartTs,\n EndTs = tokens[tokens.Count - 1].EndTs\n };\n }\n\n private static int GetTagWeight(Token token)\n {\n var weight = 0;\n foreach ( var c in token.Text )\n {\n weight += char.IsLower(c) ? 1 : 2;\n }\n\n return weight;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public bool IsTo()\n {\n return Text == \"to\" || Text == \"To\" ||\n (Text == \"TO\" && (Tag == \"TO\" || Tag == \"IN\"));\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public int StressWeight()\n {\n if ( string.IsNullOrEmpty(Phonemes) )\n {\n return 0;\n }\n\n var weight = 0;\n foreach ( var c in Phonemes )\n {\n if ( PhonemizerConstants.Diphthongs.Contains(c) )\n {\n weight += 2;\n }\n else\n {\n weight += 1;\n }\n }\n\n return weight;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ModelResource.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Model resource wrapper\n/// \npublic class ModelResource : IDisposable\n{\n private byte[]? _modelData;\n\n public ModelResource(string path) { Path = path; }\n\n /// \n /// Path to the model\n /// \n public string Path { get; }\n\n /// \n /// Whether the model is loaded\n /// \n public bool IsLoaded => _modelData != null;\n\n public void Dispose() { _modelData = null; }\n\n /// \n /// Gets the model data, loading it if necessary\n /// \n public async Task GetDataAsync()\n {\n if ( _modelData == null )\n {\n _modelData = await File.ReadAllBytesAsync(Path);\n }\n\n return _modelData;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigSectionEditorBase.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Base implementation for configuration section editors\n/// \npublic abstract class ConfigSectionEditorBase : IConfigSectionEditor, IDisposable\n{\n protected readonly IUiConfigurationManager ConfigManager;\n\n protected readonly IEditorStateManager StateManager;\n\n protected internal bool _hasUnsavedChanges = false;\n\n protected ConfigSectionEditorBase(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager)\n {\n ConfigManager = configManager ?? throw new ArgumentNullException(nameof(configManager));\n StateManager = stateManager ?? throw new ArgumentNullException(nameof(stateManager));\n }\n\n public abstract string SectionKey { get; }\n\n public abstract string DisplayName { get; }\n\n public bool HasUnsavedChanges => _hasUnsavedChanges;\n\n public virtual void Initialize() { }\n\n public abstract void Render();\n\n public virtual void RenderMenuItems() { }\n\n public virtual void Update(float deltaTime) { }\n\n public virtual void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n if ( args.Type is ConfigurationChangedEventArgs.ChangeType.Saved or ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n _hasUnsavedChanges = false;\n }\n }\n\n public virtual void Dispose()\n {\n // Base implementation does nothing\n GC.SuppressFinalize(this);\n }\n\n protected void MarkAsChanged()\n {\n if ( !_hasUnsavedChanges )\n {\n _hasUnsavedChanges = true;\n StateManager.MarkAsChanged(SectionKey);\n }\n }\n\n protected void MarkAsSaved()\n {\n _hasUnsavedChanges = false;\n StateManager.MarkAsSaved();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SliceAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\npublic readonly struct SliceAudioSource : IAudioSource\n{\n private readonly long frameStart;\n\n private readonly int maxSliceFrames;\n\n private readonly IAudioSource audioSource;\n\n private readonly TimeSpan startTime;\n\n private readonly TimeSpan maxDuration;\n\n public uint SampleRate { get; }\n\n /// \n /// Gets the total number of frames in the stream\n /// \n /// \n /// This can be more than actual number of frames in the source if the source is not big enough.\n /// \n public long FramesCount => (long)(Duration.TotalMilliseconds * SampleRate / 1000);\n\n public ushort ChannelCount { get; }\n\n public bool IsInitialized => true;\n\n public ushort BitsPerSample { get; }\n\n public IReadOnlyDictionary Metadata { get; }\n\n public TimeSpan Duration\n {\n get\n {\n var maxSourceDuration = audioSource.TotalDuration - startTime;\n\n return maxSourceDuration > maxDuration ? maxDuration : maxSourceDuration;\n }\n }\n\n public TimeSpan TotalDuration => Duration;\n\n /// \n /// Creates a slice of an audio source (without copying the audio data).\n /// \n public SliceAudioSource(IAudioSource audioSource, TimeSpan startTime, TimeSpan maxDuration)\n {\n frameStart = (long)(startTime.TotalMilliseconds * audioSource.SampleRate / 1000);\n maxSliceFrames = (int)(maxDuration.TotalMilliseconds * audioSource.SampleRate / 1000);\n SampleRate = audioSource.SampleRate;\n\n if ( startTime >= audioSource.Duration )\n {\n throw new ArgumentOutOfRangeException(nameof(startTime), $\"The start time is beyond the end of the audio source. Start time: {startTime}, Source Duration: {audioSource.Duration}\");\n }\n\n ChannelCount = audioSource.ChannelCount;\n BitsPerSample = audioSource.BitsPerSample;\n this.audioSource = audioSource;\n this.maxDuration = maxDuration;\n Metadata = audioSource.Metadata;\n this.startTime = startTime;\n }\n\n public void Dispose() { }\n\n public Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var adjustedMax = (int)Math.Min(maxFrames, maxSliceFrames - startFrame);\n\n return audioSource.GetFramesAsync(startFrame + frameStart, adjustedMax, cancellationToken);\n }\n\n public Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var adjustedMax = (int)Math.Min(maxFrames, maxSliceFrames - startFrame);\n\n return audioSource.GetSamplesAsync(startFrame + frameStart, adjustedMax, cancellationToken);\n }\n\n public Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default)\n {\n var adjustedMax = (int)Math.Min(maxFrames, maxSliceFrames - startFrame);\n\n return audioSource.CopyFramesAsync(destination, startFrame + frameStart, adjustedMax, cancellationToken);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/VoiceData.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Voice data for synthesis\n/// \npublic class VoiceData\n{\n private const int StyleDim = 256;\n\n private readonly ReadOnlyMemory _rawEmbedding;\n\n public VoiceData(string id, ReadOnlyMemory rawEmbedding)\n {\n Id = id;\n _rawEmbedding = rawEmbedding;\n }\n\n /// \n /// Voice ID\n /// \n public string Id { get; }\n\n public ReadOnlyMemory GetEmbedding(ReadOnlySpan inputDimensions)\n {\n var numTokens = GetNumTokens(inputDimensions);\n var offset = numTokens * StyleDim;\n\n // Check bounds to prevent access violations\n return offset + StyleDim > _rawEmbedding.Length\n ?\n // Return empty vector if out of bounds\n new float[StyleDim]\n :\n // Return the slice of memory at the specified offset\n _rawEmbedding.Slice(offset, StyleDim);\n }\n\n private int GetNumTokens(ReadOnlySpan inputDimensions)\n {\n var lastDim = inputDimensions[^1];\n\n return Math.Min(Math.Max(lastDim - 2, 0), 509);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadOnnxModel.cs", "using Microsoft.ML.OnnxRuntime;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroVadOnnxModel : IDisposable\n{\n private static readonly long[] sampleRateInput = [SileroConstants.SampleRate];\n\n private readonly long[] runningInputShape = [1, SileroConstants.BatchSize + SileroConstants.ContextSize];\n\n private readonly RunOptions runOptions;\n\n private readonly InferenceSession session;\n\n private readonly long[] stateShape = [2, 1, 128];\n\n public SileroVadOnnxModel(string modelPath)\n {\n var sessionOptions = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = 1,\n IntraOpNumThreads = 1,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR\n };\n \n sessionOptions.AppendExecutionProvider_CUDA();\n\n session = new InferenceSession(modelPath, sessionOptions);\n runOptions = new RunOptions();\n }\n\n public void Dispose() { session?.Dispose(); }\n\n public SileroInferenceState CreateInferenceState()\n {\n var state = new SileroInferenceState(session.CreateIoBinding());\n\n state.Binding.BindInput(\"state\", OrtValue.CreateTensorValueFromMemory(state.State, stateShape));\n state.Binding.BindInput(\"sr\", OrtValue.CreateTensorValueFromMemory(sampleRateInput, [1]));\n\n state.Binding.BindOutput(\"output\", OrtValue.CreateTensorValueFromMemory(state.Output, [1, SileroConstants.OutputSize]));\n state.Binding.BindOutput(\"stateN\", OrtValue.CreateTensorValueFromMemory(state.PendingState, stateShape));\n\n return state;\n }\n\n public float Call(Memory input, SileroInferenceState state)\n {\n state.Binding.BindInput(\"input\", OrtValue.CreateTensorValueFromMemory(OrtMemoryInfo.DefaultInstance, input, runningInputShape));\n // We need to swap the state and pending state to keep the state for the next inference\n // Zero allocation swap\n (state.State, state.PendingState) = (state.PendingState, state.State);\n\n session.RunWithBinding(runOptions, state.Binding);\n\n return state.Output[0];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/EmbeddedResource.cs", "using System.Collections.Concurrent;\nusing System.ComponentModel;\n\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib;\n\ninternal static class ModelUtils\n{\n public static string GetModelPath(ModelType modelType)\n {\n var enumDescription = modelType.GetDescription();\n var fullPath = Path.Combine(Directory.GetCurrentDirectory(), \"Resources\", \"Models\", $\"{enumDescription}\");\n\n // Check file or dir exists\n if ( !Path.Exists(fullPath) )\n {\n throw new ApplicationException($\"For {modelType} path {fullPath} doesn't exist\");\n }\n\n return fullPath;\n }\n}\n\ninternal static class PromptUtils\n{\n private static readonly ConcurrentDictionary PromptCache = new();\n\n private static string GetModelPath(string filename)\n {\n var fullPath = Path.Combine(Directory.GetCurrentDirectory(), \"Resources\", \"Prompts\", filename);\n\n if ( !File.Exists(fullPath) )\n {\n throw new ApplicationException($\"Prompt file '{filename}' not found at path: {fullPath}\");\n }\n\n return fullPath;\n }\n\n public static bool TryGetPrompt(string filename, out string? prompt)\n {\n if ( PromptCache.TryGetValue(filename, out prompt) )\n {\n return true;\n }\n\n try\n {\n var fullPath = GetModelPath(filename);\n var promptContent = File.ReadAllText(fullPath);\n PromptCache.AddOrUpdate(filename, promptContent, (_, _) => promptContent);\n prompt = promptContent;\n\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n public static void ClearCache() { PromptCache.Clear(); }\n}\n\npublic enum ModelType\n{\n [Description(\"silero_vad_v5.onnx\")] Silero,\n\n [Description(\"ggml-large-v3-turbo.bin\")]\n WhisperGgmlTurbov3,\n\n [Description(\"ggml-tiny.en.bin\")] WhisperGgmlTiny,\n\n [Description(\"badwords.txt\")] BadWords,\n\n [Description(\"tiny_toxic_detector.onnx\")]\n TinyToxic,\n\n [Description(\"tiny_toxic_detector_vocab.txt\")]\n TinyToxicVocab\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/EnumExtensions.cs", "using System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Reflection;\n\nnamespace PersonaEngine.Lib.Utils;\n\npublic static class EnumExtensions\n{\n // Thread-safe cache for storing descriptions\n private static readonly ConcurrentDictionary<(Type Type, string Name), string> DescriptionCache = new();\n\n /// \n /// Gets the description of an enum value.\n /// If the enum value has a , returns its value.\n /// Otherwise, returns the string representation of the enum value.\n /// \n /// The enum value.\n /// The description or the string representation if no description is found.\n public static string GetDescription(this Enum value)\n {\n var type = value.GetType();\n var name = Enum.GetName(type, value);\n\n if ( name == null )\n {\n return value.ToString();\n }\n\n var cacheKey = (type, name);\n\n return DescriptionCache.GetOrAdd(cacheKey, key =>\n {\n var field = key.Type.GetField(key.Name);\n\n if ( field == null )\n {\n return key.Name;\n }\n\n var attribute = field.GetCustomAttribute(false);\n\n return attribute?.Description ?? key.Name;\n });\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/AsrConfiguration.cs", "using Whisper.net;\n\nnamespace PersonaEngine.Lib.Configuration;\n\npublic record AsrConfiguration\n{\n public WhisperConfigTemplate TtsMode { get; init; } = WhisperConfigTemplate.Performant;\n\n public string TtsPrompt { get; init; } = string.Empty;\n\n public float VadThreshold { get; init; } = 0.5f;\n\n public float VadThresholdGap { get; init; } = 0.15f;\n\n public float VadMinSpeechDuration { get; init; } = 250f;\n\n public float VadMinSilenceDuration { get; init; } = 200f;\n}\n\npublic enum WhisperConfigTemplate\n{\n Performant,\n\n Balanced,\n\n Precise\n}\n\npublic static class WhisperConfigTemplateExtensions\n{\n public static WhisperProcessorBuilder ApplyTemplate(this WhisperProcessorBuilder builder, WhisperConfigTemplate template)\n {\n switch ( template )\n {\n case WhisperConfigTemplate.Performant:\n var sampleBuilderA = (GreedySamplingStrategyBuilder)builder.WithGreedySamplingStrategy();\n sampleBuilderA.WithBestOf(1);\n\n builder = sampleBuilderA.ParentBuilder;\n builder.WithStringPool();\n\n break;\n case WhisperConfigTemplate.Balanced:\n var sampleBuilderB = (BeamSearchSamplingStrategyBuilder)builder.WithBeamSearchSamplingStrategy();\n sampleBuilderB.WithBeamSize(2);\n sampleBuilderB.WithPatience(1f);\n\n builder = sampleBuilderB.ParentBuilder;\n builder.WithStringPool();\n builder.WithTemperature(0.0f);\n\n break;\n case WhisperConfigTemplate.Precise:\n var sampleBuilderC = (BeamSearchSamplingStrategyBuilder)builder.WithBeamSearchSamplingStrategy();\n sampleBuilderC.WithBeamSize(5);\n sampleBuilderC.WithPatience(1f);\n\n builder = sampleBuilderC.ParentBuilder;\n builder.WithStringPool();\n builder.WithTemperature(0.0f);\n\n break;\n default:\n throw new ArgumentOutOfRangeException(nameof(template), template, null);\n }\n\n return builder;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/Texture2DManager.cs", "using System.Drawing;\nusing System.Runtime.InteropServices;\n\nusing FontStashSharp.Interfaces;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\ninternal class Texture2DManager(GL gl) : ITexture2DManager\n{\n public object CreateTexture(int width, int height)\n {\n // Create an empty texture of the specified size\n // Allocate empty memory for the texture (4 bytes per pixel for RGBA format)\n var data = IntPtr.Zero;\n\n try\n {\n // Allocate unmanaged memory for the texture data\n var size = width * height * 4;\n data = Marshal.AllocHGlobal(size);\n\n // Initialize with transparent pixels (optional)\n unsafe\n {\n var ptr = (byte*)data.ToPointer();\n for ( var i = 0; i < size; i++ )\n {\n ptr[i] = 0;\n }\n }\n\n // Create the texture with the empty data\n // generateMipmaps is set to false as this is for UI/text rendering\n return new Texture(gl, width, height, data);\n }\n finally\n {\n // Free the unmanaged memory after the texture is created\n if ( data != IntPtr.Zero )\n {\n Marshal.FreeHGlobal(data);\n }\n }\n }\n\n public Point GetTextureSize(object texture)\n {\n var t = (Texture)texture;\n\n return new Point((int)t.Width, (int)t.Height);\n }\n\n public void SetTextureData(object texture, Rectangle bounds, byte[] data)\n {\n var t = (Texture)texture;\n t.Bind();\n\n unsafe\n {\n fixed (byte* ptr = data)\n {\n gl.TexSubImage2D(\n GLEnum.Texture2D,\n 0, // mipmap level\n bounds.Left, // x offset\n bounds.Top, // y offset\n (uint)bounds.Width, // width\n (uint)bounds.Height, // height\n PixelFormat.Bgra, // format matching the Texture class\n PixelType.UnsignedByte, // data type\n ptr // data pointer\n );\n\n gl.CheckError();\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.App/GuidToEmojiEnricher.cs", "using System.Collections.Concurrent;\n\nusing Serilog.Core;\nusing Serilog.Events;\n\nnamespace PersonaEngine.App;\n\npublic class GuidToEmojiEnricher : ILogEventEnricher\n{\n private readonly GuidEmojiMapper _mapper;\n\n public GuidToEmojiEnricher() { _mapper = new GuidEmojiMapper(); }\n\n public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)\n {\n var guidProperties = logEvent.Properties\n .Where(kvp => kvp.Value is ScalarValue { Value: Guid })\n .Select(kvp => new { kvp.Key, Value = (Guid)(((ScalarValue)kvp.Value).Value ?? Guid.Empty) })\n .ToList();\n\n foreach ( var propInfo in guidProperties )\n {\n var emoji = _mapper.GetEmojiForGuid(propInfo.Value);\n\n logEvent.RemovePropertyIfPresent(propInfo.Key);\n\n var emojiProperty = propertyFactory.CreateProperty(propInfo.Key, emoji);\n logEvent.AddOrUpdateProperty(emojiProperty);\n }\n }\n}\n\npublic class GuidEmojiMapper\n{\n private static readonly IReadOnlyList Emojis = new List {\n \"🚀\",\n \"🌟\",\n \"💡\",\n \"🔧\",\n \"🐞\",\n \"🔗\",\n \"💾\",\n \"🔑\",\n \"🎉\",\n \"🎯\",\n \"📁\",\n \"📄\",\n \"📦\",\n \"🧭\",\n \"📡\",\n \"🧪\",\n \"🧬\",\n \"⚙️\",\n \"💎\",\n \"🧩\",\n \"🐙\",\n \"🦄\",\n \"🐘\",\n \"🦋\",\n \"🐌\",\n \"🐬\",\n \"🐿️\",\n \"🍄\",\n \"🌵\",\n \"🍀\"\n }.AsReadOnly();\n\n private readonly ConcurrentDictionary _guidEmojiMap = new();\n\n private int _emojiIndex = -1;\n\n public string GetEmojiForGuid(Guid guid)\n {\n if ( guid == Guid.Empty )\n {\n return \"\\u2796\";\n }\n \n return _guidEmojiMap.GetOrAdd(guid, _ =>\n {\n var nextIndex = Interlocked.Increment(ref _emojiIndex);\n var emojiListIndex = (nextIndex & int.MaxValue) % Emojis.Count;\n\n return Emojis[emojiListIndex];\n });\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Context/MaxTurnsCleanupStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Context;\n\npublic class MaxTurnsCleanupStrategy : IConversationCleanupStrategy\n{\n private readonly int _maxTurns;\n\n public MaxTurnsCleanupStrategy(int maxTurns)\n {\n if ( maxTurns < 0 )\n {\n throw new ArgumentOutOfRangeException(nameof(maxTurns), \"Max turns cannot be negative.\");\n }\n\n _maxTurns = maxTurns;\n }\n\n public bool Cleanup(List history, ConversationContextOptions options, IReadOnlyDictionary participants)\n {\n if ( _maxTurns == 0 || history.Count <= _maxTurns )\n {\n return false;\n }\n\n var turnsToRemove = history.Count - _maxTurns;\n if ( turnsToRemove > 0 )\n {\n history.RemoveRange(0, turnsToRemove);\n \n return true;\n }\n \n return false;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/AsyncQueue.cs", "namespace PersonaEngine.Lib.Utils;\n\npublic sealed class AsyncQueue : IDisposable\n{\n private readonly Queue _queue = new();\n\n private readonly SemaphoreSlim _semaphore = new(0);\n\n private bool _isDisposed;\n\n public void Dispose()\n {\n if ( _isDisposed )\n {\n return;\n }\n\n _semaphore.Dispose();\n _isDisposed = true;\n }\n\n public void Enqueue(T item)\n {\n lock (_queue)\n {\n _queue.Enqueue(item);\n _semaphore.Release();\n }\n }\n\n public async Task DequeueAsync(CancellationToken ct = default)\n {\n await _semaphore.WaitAsync(ct);\n\n lock (_queue)\n {\n return _queue.Dequeue();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/PopAnimator.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Implements a \"pop\" animation effect using an overshoot easing function.\n/// \npublic class PopAnimator : IWordAnimator\n{\n private readonly float _overshoot;\n\n public PopAnimator(float overshoot = 1.70158f) { _overshoot = overshoot; }\n\n public Vector2 CalculateScale(float progress)\n {\n progress = Math.Clamp(progress, 0.0f, 1.0f);\n\n var scale = 1.0f + (_overshoot + 1.0f) * MathF.Pow(progress - 1.0f, 3) + _overshoot * MathF.Pow(progress - 1.0f, 2);\n\n scale = Math.Max(0.0f, scale);\n\n return new Vector2(scale, scale);\n }\n\n public FSColor CalculateColor(FSColor startColor, FSColor endColor, float progress)\n {\n progress = Math.Clamp(progress, 0.0f, 1.0f);\n\n var r = (byte)(startColor.R + (endColor.R - startColor.R) * progress);\n var g = (byte)(startColor.G + (endColor.G - startColor.G) * progress);\n var b = (byte)(startColor.B + (endColor.B - startColor.B) * progress);\n var a = (byte)(startColor.A + (endColor.A - startColor.A) * progress);\n\n return new FSColor(r, g, b, a);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/ACFMethod.cs", "namespace PersonaEngine.Lib.TTS.RVC;\n\npublic class ACFMethod : IF0Predictor\n{\n private readonly int SampleRate;\n\n private int HopLength;\n\n public ACFMethod(int hopLength, int samplingRate)\n {\n HopLength = hopLength;\n SampleRate = samplingRate;\n }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n HopLength = (int)Math.Floor(wav.Length / (double)length);\n\n var wavSpan = wav.Span;\n var f0Span = f0Output.Span;\n var frameLength = HopLength;\n\n for ( var i = 0; i < length; i++ )\n {\n // Create a window for this frame without allocations\n var startIdx = i * frameLength;\n var endIdx = Math.Min(startIdx + (int)(frameLength * 1.5), wav.Length);\n var frameSize = endIdx - startIdx;\n\n f0Span[i] = ComputeF0ForFrame(wavSpan.Slice(startIdx, frameSize));\n }\n }\n\n public void Dispose() { }\n\n private float ComputeF0ForFrame(ReadOnlySpan frame)\n {\n var n = frame.Length;\n Span autocorrelation = stackalloc float[n]; // Use stack allocation to avoid heap allocations\n\n // Calculate autocorrelation function\n for ( var lag = 0; lag < n; lag++ )\n {\n float sum = 0;\n for ( var i = 0; i < n - lag; i++ )\n {\n sum += frame[i] * frame[i + lag];\n }\n\n autocorrelation[lag] = sum;\n }\n\n // Ignore zero-delay peak, find first non-zero delay peak\n var peakIndex = 1;\n var maxVal = autocorrelation[1];\n for ( ; peakIndex < autocorrelation.Length && (maxVal = autocorrelation[peakIndex]) > 0; peakIndex++ )\n {\n ;\n }\n\n for ( var lag = peakIndex; lag < n; lag++ )\n {\n if ( autocorrelation[lag] > maxVal )\n {\n maxVal = autocorrelation[lag];\n peakIndex = lag;\n }\n }\n\n // Calculate fundamental frequency\n var f0 = SampleRate / (float)peakIndex;\n\n return f0;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Id/CubismIdManager.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Id;\n\n/// \n/// ID名を管理する。\n/// \npublic class CubismIdManager\n{\n /// \n /// 登録されているIDのリスト\n /// \n private readonly List _ids = [];\n\n /// \n /// ID名をリストから登録する。\n /// \n /// ID名リスト\n public void RegisterIds(List list) { list.ForEach(item => { GetId(item); }); }\n\n /// \n /// ID名からIDを取得する。\n /// 未登録のID名の場合、登録も行う。\n /// \n /// ID名\n public string GetId(string item)\n {\n if ( _ids.Contains(item) )\n {\n return item;\n }\n\n _ids.Add(item);\n\n return item;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/Notification.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Notification data structure\n/// \npublic class Notification\n{\n public enum NotificationType\n {\n Info,\n\n Success,\n\n Warning,\n\n Error\n }\n\n public Notification(NotificationType type, string message, float duration = 5f, Action? action = null, string actionLabel = \"OK\")\n {\n Type = type;\n Message = message;\n RemainingTime = duration;\n Action = action;\n ActionLabel = actionLabel;\n }\n\n public string Id { get; } = Guid.NewGuid().ToString();\n\n public NotificationType Type { get; }\n\n public string Message { get; }\n\n public float RemainingTime { get; set; }\n\n public Action? Action { get; }\n\n public string ActionLabel { get; }\n\n public bool HasAction => Action != null;\n\n public void InvokeAction() { Action?.Invoke(); }\n\n public Vector4 GetBackgroundColor()\n {\n return Type switch {\n NotificationType.Info => new Vector4(0.2f, 0.4f, 0.8f, 0.2f),\n NotificationType.Success => new Vector4(0.2f, 0.8f, 0.2f, 0.2f),\n NotificationType.Warning => new Vector4(0.9f, 0.7f, 0.0f, 0.2f),\n NotificationType.Error => new Vector4(0.8f, 0.2f, 0.2f, 0.25f),\n _ => new Vector4(0.3f, 0.3f, 0.3f, 0.2f)\n };\n }\n\n public Vector4 GetTextColor()\n {\n return Type switch {\n NotificationType.Info => new Vector4(0.3f, 0.6f, 1.0f, 1.0f),\n NotificationType.Success => new Vector4(0.0f, 0.8f, 0.0f, 1.0f),\n NotificationType.Warning => new Vector4(1.0f, 0.7f, 0.0f, 1.0f),\n NotificationType.Error => new Vector4(1.0f, 0.3f, 0.3f, 1.0f),\n _ => new Vector4(0.9f, 0.9f, 0.9f, 1.0f)\n };\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Strategies/MinWordsNoSpeakingStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Input;\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Strategies;\n\npublic class MinWordsNoSpeakingStrategy : IBargeInStrategy\n{\n public bool ShouldAllowBargeIn(BargeInContext context)\n {\n if ( context.CurrentState == ConversationState.Speaking )\n {\n return false;\n }\n\n switch ( context.InputEvent )\n {\n case SttSegmentRecognizing segmentRecognizing:\n {\n var wordCount = segmentRecognizing.PartialTranscript.GetWordCount();\n\n return wordCount >= context.ConversationOptions.BargeInMinWords;\n }\n case SttSegmentRecognized segmentRecognized:\n {\n var wordCount = segmentRecognized.FinalTranscript.GetWordCount();\n\n return wordCount >= context.ConversationOptions.BargeInMinWords;\n }\n default:\n return false;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/BufferObject.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\npublic class BufferObject : IDisposable where T : unmanaged\n{\n private readonly BufferTargetARB _bufferType;\n\n private readonly GL _gl;\n\n private readonly uint _handle;\n\n private readonly int _size;\n\n public unsafe BufferObject(GL glApi, int size, BufferTargetARB bufferType, bool isDynamic)\n {\n _gl = glApi;\n\n _bufferType = bufferType;\n _size = size;\n\n _handle = _gl.GenBuffer();\n _gl.CheckError();\n\n Bind();\n\n var elementSizeInBytes = Marshal.SizeOf();\n _gl.BufferData(bufferType, (nuint)(size * elementSizeInBytes), null, isDynamic ? BufferUsageARB.StreamDraw : BufferUsageARB.StaticDraw);\n _gl.CheckError();\n }\n\n public void Dispose()\n {\n _gl.DeleteBuffer(_handle);\n _gl.CheckError();\n }\n\n public void Bind()\n {\n _gl.BindBuffer(_bufferType, _handle);\n _gl.CheckError();\n }\n\n public unsafe void SetData(T[] data, int startIndex, int elementCount)\n {\n Bind();\n\n fixed (T* dataPtr = &data[startIndex])\n {\n var elementSizeInBytes = sizeof(T);\n\n _gl.BufferSubData(_bufferType, 0, (nuint)(elementCount * elementSizeInBytes), dataPtr);\n _gl.CheckError();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemizerConstants.cs", "using System.Collections.Frozen;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class PhonemizerConstants\n{\n public static readonly HashSet Diphthongs = new(\"AIOQWYʤʧ\");\n\n public static readonly HashSet Vowels = new(\"AIOQWYaiuæɑɒɔəɛɜɪʊʌᵻ\");\n\n public static readonly HashSet Consonants = new(\"bdfhjklmnpstvwzðŋɡɹɾʃʒʤʧθ\");\n\n public static readonly char PrimaryStress = 'ˈ';\n\n public static readonly char SecondaryStress = 'ˌ';\n\n public static readonly char[] Stresses = ['ˌ', 'ˈ'];\n\n public static readonly HashSet UsTaus = new(\"AIOWYiuæɑəɛɪɹʊʌ\");\n\n public static readonly HashSet UsVocab = new(\"AIOWYbdfhijklmnpstuvwzæðŋɑɔəɛɜɡɪɹɾʃʊʌʒʤʧˈˌθᵊᵻ\");\n\n public static readonly HashSet GbVocab = new(\"AIQWYabdfhijklmnpstuvwzðŋɑɒɔəɛɜɡɪɹʃʊʌʒʤʧˈˌːθᵊ\");\n\n public static readonly IReadOnlyDictionary Currencies = new Dictionary { [\"$\"] = (\"dollar\", \"cent\"), [\"£\"] = (\"pound\", \"pence\"), [\"€\"] = (\"euro\", \"cent\") }.ToFrozenDictionary();\n\n public static readonly Dictionary AddSymbols = new() { [\".\"] = \"dot\", [\"/\"] = \"slash\" };\n\n public static readonly Dictionary Symbols = new() { [\"%\"] = \"percent\", [\"&\"] = \"and\", [\"+\"] = \"plus\", [\"@\"] = \"at\" };\n\n public static readonly HashSet Ordinals = [\"st\", \"nd\", \"rd\", \"th\"];\n\n public static readonly HashSet PunctTags = [\n \".\",\n \",\",\n \"-LRB-\",\n \"-RRB-\",\n \"``\",\n \"\\\"\\\"\",\n \"''\",\n \":\",\n \"$\",\n \"#\",\n \"NFP\"\n ];\n\n public static readonly Dictionary PunctTagPhonemes = new() {\n [\"-LRB-\"] = \"(\",\n [\"-RRB-\"] = \")\",\n [\"``\"] = \"\\u2014\", // em dash\n [\"\\\"\\\"\"] = \"\\u201D\", // right double quote\n [\"''\"] = \"\\u201D\" // right double quote\n };\n\n public static readonly HashSet SubtokenJunks = new(\"',-._''/\");\n\n public static readonly HashSet Puncts = new(\";:,.!?—…\\\"\\\"\\\"\");\n\n public static readonly HashSet NonQuotePuncts = [];\n\n static PhonemizerConstants()\n {\n // Initialize NonQuotePuncts\n foreach ( var c in Puncts )\n {\n if ( c != '\"' && c != '\"' && c != '\"' )\n {\n NonQuotePuncts.Add(c);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Spout/SpoutRegistry.cs", "using PersonaEngine.Lib.Configuration;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Spout;\n\npublic class SpoutRegistry : IDisposable\n{\n private readonly SpoutConfiguration[] _configs;\n\n private readonly GL _gl;\n\n private readonly Dictionary _spoutManagers = new();\n\n public SpoutRegistry(GL gl, SpoutConfiguration[] configs)\n {\n _gl = gl;\n _configs = configs;\n\n foreach ( var config in _configs )\n {\n GetOrCreateManager(config);\n }\n }\n\n public void Dispose()\n {\n foreach ( var manager in _spoutManagers.Values )\n {\n manager.Dispose();\n }\n\n _spoutManagers.Clear();\n }\n\n public SpoutManager GetOrCreateManager(SpoutConfiguration config)\n {\n if ( !_spoutManagers.TryGetValue(config.OutputName, out var manager) )\n {\n manager = new SpoutManager(_gl, config);\n _spoutManagers.Add(config.OutputName, manager);\n }\n\n return manager;\n }\n\n public void BeginFrame(string spoutName)\n {\n if ( string.IsNullOrEmpty(spoutName) || !_spoutManagers.TryGetValue(spoutName, out var manager) )\n {\n return;\n }\n\n manager.BeginFrame();\n }\n\n public void SendFrame(string spoutName)\n {\n if ( string.IsNullOrEmpty(spoutName) || !_spoutManagers.TryGetValue(spoutName, out var manager) )\n {\n return;\n }\n\n manager.SendFrame();\n }\n\n public void ResizeAll(int width, int height)\n {\n foreach ( var manager in _spoutManagers.Values )\n {\n manager.ResizeFramebuffer(width, height);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AsyncAutoResetEvent.cs", "namespace PersonaEngine.Lib.Audio;\n\ninternal class AsyncAutoResetEvent\n{\n private static readonly Task Completed = Task.CompletedTask;\n\n private int isSignaled; // 0 for false, 1 for true\n\n private TaskCompletionSource? waitTcs;\n\n public Task WaitAsync()\n {\n if ( Interlocked.CompareExchange(ref isSignaled, 0, 1) == 1 )\n {\n return Completed;\n }\n\n var tcs = new TaskCompletionSource();\n var oldTcs = Interlocked.Exchange(ref waitTcs, tcs);\n oldTcs?.TrySetCanceled();\n\n return tcs.Task;\n }\n\n public void Set()\n {\n var toRelease = Interlocked.Exchange(ref waitTcs, null);\n if ( toRelease != null )\n {\n toRelease.SetResult(true);\n }\n else\n {\n Interlocked.Exchange(ref isSignaled, 1);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Session/ConversationSessionFactory.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Context;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Metrics;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Strategies;\nusing PersonaEngine.Lib.LLM;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Session;\n\npublic class ConversationSessionFactory(\n ILoggerFactory loggerFactory,\n IChatEngine chatEngine,\n ITtsEngine ttsEngine,\n IEnumerable inputAdapters,\n IOutputAdapter outputAdapter,\n ConversationMetrics metrics)\n : IConversationSessionFactory\n{\n public IConversationSession CreateSession(ConversationContext context, ConversationOptions? options = null, Guid? sessionId = null)\n {\n var logger = loggerFactory.CreateLogger();\n options ??= new ConversationOptions();\n\n return new ConversationSession(\n logger,\n chatEngine,\n ttsEngine,\n inputAdapters,\n outputAdapter,\n metrics,\n sessionId ?? Guid.NewGuid(),\n options,\n context,\n GetBargeInStrategy(options!)\n );\n }\n\n private IBargeInStrategy GetBargeInStrategy(ConversationOptions options)\n {\n return options.BargeInType switch {\n BargeInType.Ignore => new IgnoreBargeInStrategy(),\n BargeInType.Allow => new AllowBargeInStrategy(),\n BargeInType.NoSpeaking => new NoSpeakingBargeInStrategy(),\n BargeInType.MinWordsNoSpeaking => new MinWordsNoSpeakingStrategy(),\n BargeInType.MinWords => new MinWordsBargeInStrategy(),\n _ => throw new ArgumentOutOfRangeException(nameof(options.BargeInType), \"Invalid BargeInType\")\n };\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigSectionRegistry.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Implements configuration section registry\n/// \npublic class ConfigSectionRegistry : IConfigSectionRegistry\n{\n private readonly Dictionary _sections = new();\n\n public void RegisterSection(IConfigSectionEditor section)\n {\n if ( section == null )\n {\n throw new ArgumentNullException(nameof(section));\n }\n\n _sections[section.SectionKey] = section;\n }\n\n public void UnregisterSection(string sectionKey) { _sections.Remove(sectionKey); }\n\n public IConfigSectionEditor GetSection(string sectionKey) { return _sections.TryGetValue(sectionKey, out var section) ? section : null; }\n\n public IReadOnlyList GetSections() { return _sections.Values.ToList().AsReadOnly(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Rendering/VertexArrayObject.cs", "using PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Text.Rendering;\n\npublic class VertexArrayObject : IDisposable\n{\n private readonly GL _gl;\n\n private readonly uint _handle;\n\n private readonly int _stride;\n\n public VertexArrayObject(GL glApi, int stride)\n {\n _gl = glApi;\n\n if ( stride <= 0 )\n {\n throw new ArgumentOutOfRangeException(nameof(stride));\n }\n\n _stride = stride;\n\n _gl.GenVertexArrays(1, out _handle);\n _gl.CheckError();\n }\n\n public void Dispose()\n {\n _gl.DeleteVertexArray(_handle);\n _gl.CheckError();\n }\n\n public void Bind()\n {\n _gl.BindVertexArray(_handle);\n _gl.CheckError();\n }\n\n public unsafe void VertexAttribPointer(int location, int size, VertexAttribPointerType type, bool normalized, int offset)\n {\n _gl.EnableVertexAttribArray((uint)location);\n _gl.VertexAttribPointer((uint)location, size, type, normalized, (uint)_stride, (void*)offset);\n _gl.CheckError();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/WhisperNetSpeechTranscriptorFactory.cs", "using System.Globalization;\n\nusing PersonaEngine.Lib.Configuration;\n\nusing Whisper.net;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic sealed class WhisperSpeechTranscriptorFactory : ISpeechTranscriptorFactory\n{\n private readonly WhisperProcessorBuilder builder;\n\n private readonly WhisperFactory? whisperFactory;\n\n public WhisperSpeechTranscriptorFactory(WhisperFactory factory, bool dispose = true)\n {\n builder = factory.CreateBuilder();\n if ( dispose )\n {\n whisperFactory = factory;\n }\n }\n\n public WhisperSpeechTranscriptorFactory(WhisperProcessorBuilder builder) { this.builder = builder; }\n\n public WhisperSpeechTranscriptorFactory(string modelFileName)\n {\n whisperFactory = WhisperFactory.FromPath(modelFileName);\n builder = whisperFactory.CreateBuilder();\n }\n\n public ISpeechTranscriptor Create(SpeechTranscriptorOptions options)\n {\n var currentBuilder = builder;\n if ( options.Prompt != null )\n {\n currentBuilder = currentBuilder.WithPrompt(options.Prompt);\n }\n\n if ( options.LanguageAutoDetect )\n {\n currentBuilder = currentBuilder.WithLanguage(\"auto\");\n }\n else\n {\n currentBuilder = currentBuilder.WithLanguage(ToWhisperLanguage(options.Language));\n }\n\n if ( options.RetrieveTokenDetails )\n {\n currentBuilder = currentBuilder.WithTokenTimestamps();\n }\n \n if ( options.Template != null )\n {\n currentBuilder = currentBuilder.ApplyTemplate(options.Template.Value);\n }\n\n var processor = currentBuilder.Build();\n\n return new WhisperNetSpeechTranscriptor(processor);\n }\n\n public void Dispose() { whisperFactory?.Dispose(); }\n\n private static string ToWhisperLanguage(CultureInfo languageCode)\n {\n if ( !WhisperNetSupportedLanguage.IsSupported(languageCode) )\n {\n throw new NotSupportedException($\"The language provided as: {languageCode.ThreeLetterISOLanguageName} is not supported by Whisper.net.\");\n }\n\n return languageCode.TwoLetterISOLanguageName;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeEntry.cs", "using System.Text.Json;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic abstract record PhonemeEntry\n{\n // Factory method to create the appropriate entry type from JSON\n public static PhonemeEntry FromJsonElement(JsonElement element)\n {\n if ( element.ValueKind == JsonValueKind.String )\n {\n return new SimplePhonemeEntry(element.GetString()!);\n }\n\n if ( element.ValueKind == JsonValueKind.Object )\n {\n var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);\n foreach ( var property in element.EnumerateObject() )\n {\n if ( property.Value.ValueKind == JsonValueKind.String )\n {\n dict[property.Name] = property.Value.GetString()!;\n }\n }\n\n return new ContextualPhonemeEntry(dict);\n }\n\n throw new JsonException($\"Unexpected JSON element type: {element.ValueKind}\");\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismRendererProfile_OpenGLES2.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal class CubismRendererProfile_OpenGLES2(OpenGLApi gl)\n{\n /// \n /// モデル描画直前のアクティブなテクスチャ\n /// \n internal int LastActiveTexture;\n\n /// \n /// モデル描画直前の頂点バッファ\n /// \n internal int LastArrayBufferBinding;\n\n /// \n /// モデル描画直前のGL_SCISSOR_TESTパラメータ\n /// \n internal bool LastBlend;\n\n /// \n /// モデル描画直前のカラーブレンディングパラメータ\n /// \n internal int[] LastBlending = new int[4];\n\n /// \n /// モデル描画直前のGL_COLOR_WRITEMASKパラメータ\n /// \n internal bool[] LastColorMask = new bool[4];\n\n /// \n /// モデル描画直前のGL_CULL_FACEパラメータ\n /// \n internal bool LastCullFace;\n\n /// \n /// モデル描画直前のGL_DEPTH_TESTパラメータ\n /// \n internal bool LastDepthTest;\n\n /// \n /// モデル描画直前のElementバッファ\n /// \n internal int LastElementArrayBufferBinding;\n\n /// \n /// モデル描画直前のフレームバッファ\n /// \n internal int LastFBO;\n\n /// \n /// モデル描画直前のGL_CULL_FACEパラメータ\n /// \n internal int LastFrontFace;\n\n /// \n /// モデル描画直前のシェーダプログラムバッファ\n /// \n internal int LastProgram;\n\n /// \n /// モデル描画直前のGL_VERTEX_ATTRIB_ARRAY_ENABLEDパラメータ\n /// \n internal bool LastScissorTest;\n\n /// \n /// モデル描画直前のGL_STENCIL_TESTパラメータ\n /// \n internal bool LastStencilTest;\n\n /// \n /// モデル描画直前のテクスチャユニット0\n /// \n internal int LastTexture0Binding2D;\n\n /// \n /// モデル描画直前のテクスチャユニット1\n /// \n internal int LastTexture1Binding2D;\n\n /// \n /// モデル描画直前のテクスチャユニット1\n /// \n internal int[] LastVertexAttribArrayEnabled = new int[4];\n\n /// \n /// モデル描画直前のビューポート\n /// \n internal int[] LastViewport = new int[4];\n\n /// \n /// OpenGLES2のステートを保持する\n /// \n internal void Save()\n {\n //-- push state --\n gl.GetIntegerv(gl.GL_ARRAY_BUFFER_BINDING, out LastArrayBufferBinding);\n gl.GetIntegerv(gl.GL_ELEMENT_ARRAY_BUFFER_BINDING, out LastElementArrayBufferBinding);\n gl.GetIntegerv(gl.GL_CURRENT_PROGRAM, out LastProgram);\n\n gl.GetIntegerv(gl.GL_ACTIVE_TEXTURE, out LastActiveTexture);\n gl.ActiveTexture(gl.GL_TEXTURE1); //テクスチャユニット1をアクティブに(以後の設定対象とする)\n gl.GetIntegerv(gl.GL_TEXTURE_BINDING_2D, out LastTexture1Binding2D);\n\n gl.ActiveTexture(gl.GL_TEXTURE0); //テクスチャユニット0をアクティブに(以後の設定対象とする)\n gl.GetIntegerv(gl.GL_TEXTURE_BINDING_2D, out LastTexture0Binding2D);\n\n gl.GetVertexAttribiv(0, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[0]);\n gl.GetVertexAttribiv(1, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[1]);\n gl.GetVertexAttribiv(2, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[2]);\n gl.GetVertexAttribiv(3, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[3]);\n\n LastScissorTest = gl.IsEnabled(gl.GL_SCISSOR_TEST);\n LastStencilTest = gl.IsEnabled(gl.GL_STENCIL_TEST);\n LastDepthTest = gl.IsEnabled(gl.GL_DEPTH_TEST);\n LastCullFace = gl.IsEnabled(gl.GL_CULL_FACE);\n LastBlend = gl.IsEnabled(gl.GL_BLEND);\n\n gl.GetIntegerv(gl.GL_FRONT_FACE, out LastFrontFace);\n\n gl.GetBooleanv(gl.GL_COLOR_WRITEMASK, LastColorMask);\n\n // backup blending\n gl.GetIntegerv(gl.GL_BLEND_SRC_RGB, out LastBlending[0]);\n gl.GetIntegerv(gl.GL_BLEND_DST_RGB, out LastBlending[1]);\n gl.GetIntegerv(gl.GL_BLEND_SRC_ALPHA, out LastBlending[2]);\n gl.GetIntegerv(gl.GL_BLEND_DST_ALPHA, out LastBlending[3]);\n\n // モデル描画直前のFBOとビューポートを保存\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out LastFBO);\n gl.GetIntegerv(gl.GL_VIEWPORT, LastViewport);\n }\n\n /// \n /// 保持したOpenGLES2のステートを復帰させる\n /// \n internal void Restore()\n {\n gl.UseProgram(LastProgram);\n\n SetGlEnableVertexAttribArray(0, LastVertexAttribArrayEnabled[0] > 0);\n SetGlEnableVertexAttribArray(1, LastVertexAttribArrayEnabled[1] > 0);\n SetGlEnableVertexAttribArray(2, LastVertexAttribArrayEnabled[2] > 0);\n SetGlEnableVertexAttribArray(3, LastVertexAttribArrayEnabled[3] > 0);\n\n SetGlEnable(gl.GL_SCISSOR_TEST, LastScissorTest);\n SetGlEnable(gl.GL_STENCIL_TEST, LastStencilTest);\n SetGlEnable(gl.GL_DEPTH_TEST, LastDepthTest);\n SetGlEnable(gl.GL_CULL_FACE, LastCullFace);\n SetGlEnable(gl.GL_BLEND, LastBlend);\n\n gl.FrontFace(LastFrontFace);\n\n gl.ColorMask(LastColorMask[0], LastColorMask[1], LastColorMask[2], LastColorMask[3]);\n\n gl.BindBuffer(gl.GL_ARRAY_BUFFER, LastArrayBufferBinding); //前にバッファがバインドされていたら破棄する必要がある\n gl.BindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, LastElementArrayBufferBinding);\n\n gl.ActiveTexture(gl.GL_TEXTURE1); //テクスチャユニット1を復元\n gl.BindTexture(gl.GL_TEXTURE_2D, LastTexture1Binding2D);\n\n gl.ActiveTexture(gl.GL_TEXTURE0); //テクスチャユニット0を復元\n gl.BindTexture(gl.GL_TEXTURE_2D, LastTexture0Binding2D);\n\n gl.ActiveTexture(LastActiveTexture);\n\n // restore blending\n gl.BlendFuncSeparate(LastBlending[0], LastBlending[1], LastBlending[2], LastBlending[3]);\n }\n\n /// \n /// OpenGLES2の機能の有効・無効をセットする\n /// \n /// 有効・無効にする機能\n /// trueなら有効にする\n internal void SetGlEnable(int index, bool enabled)\n {\n if ( enabled )\n {\n gl.Enable(index);\n }\n else\n {\n gl.Disable(index);\n }\n }\n\n /// \n /// OpenGLES2のVertex Attribute Array機能の有効・無効をセットする\n /// \n /// 有効・無効にする機能\n /// trueなら有効にする\n internal void SetGlEnableVertexAttribArray(int index, bool enabled)\n {\n if ( enabled )\n {\n gl.EnableVertexAttribArray(index);\n }\n else\n {\n gl.DisableVertexAttribArray(index);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeEntryConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemeEntryConverter : JsonConverter\n{\n public override PhonemeEntry Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n using var doc = JsonDocument.ParseValue(ref reader);\n\n return PhonemeEntry.FromJsonElement(doc.RootElement);\n }\n\n public override void Write(Utf8JsonWriter writer, PhonemeEntry value, JsonSerializerOptions options)\n {\n switch ( value )\n {\n case SimplePhonemeEntry simple:\n writer.WriteStringValue(simple.Phoneme);\n\n break;\n case ContextualPhonemeEntry contextual:\n writer.WriteStartObject();\n foreach ( var form in contextual.Forms )\n {\n writer.WriteString(form.Key, form.Value);\n }\n\n writer.WriteEndObject();\n\n break;\n default:\n throw new JsonException($\"Unsupported PhonemeEntry type: {value.GetType()}\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/WhisperNetSpeechTranscriptor.cs", "using System.Globalization;\nusing System.Runtime.CompilerServices;\n\nusing PersonaEngine.Lib.Audio;\n\nusing Whisper.net;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\ninternal class WhisperNetSpeechTranscriptor(WhisperProcessor whisperProcessor) : ISpeechTranscriptor\n{\n public async IAsyncEnumerable TranscribeAsync(IAudioSource source, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n if ( source.ChannelCount != 1 )\n {\n throw new NotSupportedException(\"Only mono-channel audio is supported. Consider one channel aggregation on the audio source.\");\n }\n\n if ( source.SampleRate != 16000 )\n {\n throw new NotSupportedException(\"Only 16 kHz audio is supported. Consider resampling before calling this transcriptor.\");\n }\n\n var samples = await source.GetSamplesAsync(0, cancellationToken: cancellationToken);\n\n await foreach ( var segment in whisperProcessor.ProcessAsync(samples, cancellationToken) )\n {\n yield return new TranscriptSegment {\n Metadata = source.Metadata,\n StartTime = segment.Start,\n Duration = segment.End - segment.Start,\n ConfidenceLevel = segment.Probability,\n Language = new CultureInfo(segment.Language),\n Text = segment.Text,\n Tokens = segment?.Tokens.Select(t => new TranscriptToken {\n Id = t.Id,\n Text = t.Text,\n Confidence = t.Probability,\n ConfidenceLog = t.ProbabilityLog,\n StartTime = TimeSpan.FromMilliseconds(t.Start),\n Duration = TimeSpan.FromMilliseconds(t.End - t.Start),\n DtwTimestamp = t.DtwTimestamp,\n TimestampConfidence = t.TimestampProbability,\n TimestampConfidenceSum = t.TimestampProbabilitySum\n }).ToList()\n };\n }\n }\n\n public async ValueTask DisposeAsync() { await whisperProcessor.DisposeAsync(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleSegment.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Represents a processed audio segment, broken down into lines and words\n/// with calculated timing and layout information ready for the timeline.\n/// \npublic class SubtitleSegment(AudioSegment originalAudioSegment, float absoluteStartTime, string fullText)\n{\n public AudioSegment OriginalAudioSegment { get; } = originalAudioSegment;\n\n public float AbsoluteStartTime { get; } = absoluteStartTime;\n\n public string FullText { get; } = fullText;\n\n public List Lines { get; } = new();\n\n public float EstimatedEndTime { get; private set; } = absoluteStartTime;\n\n public void AddLine(SubtitleLine line)\n {\n Lines.Add(line);\n if ( line.Words.Count <= 0 )\n {\n return;\n }\n\n var lastWord = line.Words[^1];\n EstimatedEndTime = Math.Max(EstimatedEndTime, lastWord.AbsoluteStartTime + lastWord.Duration);\n }\n\n public void Clear()\n {\n Lines.Clear();\n EstimatedEndTime = AbsoluteStartTime;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/LexiconEntry.cs", "using System.Text.Json.Serialization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Lexicon entry representing pronunciation for a word\n/// \npublic class LexiconEntry\n{\n /// \n /// Simple phoneme string (for entries with only one pronunciation)\n /// \n public string? Simple { get; set; }\n\n /// \n /// Phoneme strings by part-of-speech tag\n /// \n public Dictionary? ByTag { get; set; }\n\n /// \n /// Whether this is a simple entry\n /// \n [JsonIgnore]\n public bool IsSimple => ByTag == null;\n\n /// \n /// Gets phoneme string for a specific tag\n /// \n public string? GetForTag(string? tag)\n {\n if ( IsSimple )\n {\n return Simple;\n }\n\n if ( tag != null && ByTag != null && ByTag.TryGetValue(tag, out var value) )\n {\n return value;\n }\n\n if ( ByTag != null && ByTag.TryGetValue(\"DEFAULT\", out var def) )\n {\n return def;\n }\n\n return null;\n }\n\n /// \n /// Whether this entry has a specific tag\n /// \n public bool HasTag(string tag) { return ByTag != null && ByTag.ContainsKey(tag); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/WindowManager.cs", "using Silk.NET.Maths;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI;\n\n/// \n/// Wraps Silk.NET window creation, events, and OpenGL context initialization.\n/// \npublic class WindowManager\n{\n public WindowManager(Vector2D size, string title)\n {\n var options = WindowOptions.Default;\n options.Size = size;\n options.Title = title;\n options.UpdatesPerSecond = 60;\n options.FramesPerSecond = 30;\n options.WindowBorder = WindowBorder.Fixed;\n MainWindow = Window.Create(options);\n MainWindow.Load += OnLoad;\n MainWindow.Update += OnUpdate;\n MainWindow.Render += OnRender;\n MainWindow.Resize += OnResize;\n MainWindow.Closing += OnClose;\n }\n\n public IWindow MainWindow { get; }\n\n public GL GL { get; private set; }\n\n public event Action RenderFrame;\n\n public event Action Load;\n\n public event Action> Resize;\n\n public event Action Update;\n\n public event Action Close;\n\n private void OnLoad()\n {\n GL = GL.GetApi(MainWindow);\n Load?.Invoke();\n }\n\n private void OnUpdate(double delta) { Update?.Invoke(delta); }\n\n private void OnRender(double delta) { RenderFrame?.Invoke(delta); }\n\n private void OnResize(Vector2D size) { Resize?.Invoke(size); }\n\n private void OnClose() { Close?.Invoke(); }\n\n public void Run() { MainWindow.Run(); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/LexiconEntryJsonConverter.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Custom JSON converter for lexicon entries\n/// \npublic class LexiconEntryJsonConverter : JsonConverter\n{\n public override LexiconEntry Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n var entry = new LexiconEntry();\n\n if ( reader.TokenType == JsonTokenType.String )\n {\n entry.Simple = reader.GetString();\n }\n else if ( reader.TokenType == JsonTokenType.StartObject )\n {\n entry.ByTag = JsonSerializer.Deserialize>(ref reader, options);\n }\n else\n {\n throw new JsonException($\"Unexpected token {reader.TokenType} when deserializing lexicon entry\");\n }\n\n return entry;\n }\n\n public override void Write(Utf8JsonWriter writer, LexiconEntry value, JsonSerializerOptions options)\n {\n if ( value.IsSimple )\n {\n writer.WriteStringValue(value.Simple);\n }\n else\n {\n JsonSerializer.Serialize(writer, value.ByTag, options);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppDefine.cs", "using PersonaEngine.Lib.Live2D.Framework;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// アプリケーションクラス。\n/// Cubism SDK の管理を行う。\n/// \npublic static class LAppDefine\n{\n // 画面\n public const float ViewScale = 1.0f;\n\n public const float ViewMaxScale = 2.0f;\n\n public const float ViewMinScale = 0.8f;\n\n public const float ViewLogicalLeft = -1.0f;\n\n public const float ViewLogicalRight = 1.0f;\n\n public const float ViewLogicalBottom = -1.0f;\n\n public const float ViewLogicalTop = -1.0f;\n\n public const float ViewLogicalMaxLeft = -2.0f;\n\n public const float ViewLogicalMaxRight = 2.0f;\n\n public const float ViewLogicalMaxBottom = -2.0f;\n\n public const float ViewLogicalMaxTop = 2.0f;\n\n // 外部定義ファイル(json)と合わせる\n public const string MotionGroupIdle = \"Idle\"; // アイドリング\n\n public const string MotionGroupTapBody = \"TapBody\"; // 体をタップしたとき\n\n // 外部定義ファイル(json)と合わせる\n public const string HitAreaNameHead = \"Head\";\n\n public const string HitAreaNameBody = \"Body\";\n\n // MOC3の整合性検証オプション\n public const bool MocConsistencyValidationEnable = true;\n\n // Frameworkから出力するログのレベル設定\n public const LogLevel CubismLoggingLevel = LogLevel.Verbose;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionInternal.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーション再生終了コールバック関数定義\n/// \npublic delegate void FinishedMotionCallback(CubismModel model, ACubismMotion self);\n\n/// \n/// イベントのコールバックに登録できる関数の型情報\n/// \n/// 発火したイベントの文字列データ\n/// コールバックに返される登録時に指定されたデータ\npublic delegate void CubismMotionEventFunction(CubismUserModel? customData, string eventValue);\n\n/// \n/// モーションカーブのセグメントの評価関数。\n/// \n/// モーションカーブの制御点リスト\n/// 評価する時間[秒]\npublic delegate float csmMotionSegmentEvaluationFunction(CubismMotionPoint[] points, int start, float time);\n\n/// \n/// モーションの優先度定数\n/// \npublic enum MotionPriority\n{\n PriorityNone = 0,\n\n PriorityIdle = 1,\n\n PriorityLow = 2,\n \n PriorityNormal = 3,\n\n PriorityForce = 4\n}\n\n/// \n/// 表情パラメータ値の計算方式\n/// \npublic enum ExpressionBlendType\n{\n /// \n /// 加算\n /// \n Add = 0,\n\n /// \n /// 乗算\n /// \n Multiply = 1,\n\n /// \n /// 上書き\n /// \n Overwrite = 2\n}\n\n/// \n/// 表情のパラメータ情報の構造体。\n/// \npublic record ExpressionParameter\n{\n /// \n /// パラメータID\n /// \n public required string ParameterId { get; set; }\n\n /// \n /// パラメータの演算種類\n /// \n public ExpressionBlendType BlendType { get; set; }\n\n /// \n /// 値\n /// \n public float Value { get; set; }\n}\n\n/// \n/// モーションカーブの種類。\n/// \npublic enum CubismMotionCurveTarget\n{\n /// \n /// モデルに対して\n /// \n Model,\n\n /// \n /// パラメータに対して\n /// \n Parameter,\n\n /// \n /// パーツの不透明度に対して\n /// \n PartOpacity\n}\n\n/// \n/// モーションカーブのセグメントの種類。\n/// \npublic enum CubismMotionSegmentType\n{\n /// \n /// リニア\n /// \n Linear = 0,\n\n /// \n /// ベジェ曲線\n /// \n Bezier = 1,\n\n /// \n /// ステップ\n /// \n Stepped = 2,\n\n /// \n /// インバースステップ\n /// \n InverseStepped = 3\n}\n\n/// \n/// モーションカーブの制御点。\n/// \npublic struct CubismMotionPoint\n{\n /// \n /// 時間[秒]\n /// \n public float Time;\n\n /// \n /// 値\n /// \n public float Value;\n}\n\n/// \n/// モーションカーブのセグメント。\n/// \npublic record CubismMotionSegment\n{\n /// \n /// 最初のセグメントへのインデックス\n /// \n public int BasePointIndex;\n\n /// \n /// 使用する評価関数\n /// \n public csmMotionSegmentEvaluationFunction Evaluate;\n\n /// \n /// セグメントの種類\n /// \n public CubismMotionSegmentType SegmentType;\n}\n\n/// \n/// モーションカーブ。\n/// \npublic record CubismMotionCurve\n{\n /// \n /// 最初のセグメントのインデックス\n /// \n public int BaseSegmentIndex;\n\n /// \n /// フェードインにかかる時間[秒]\n /// \n public float FadeInTime;\n\n /// \n /// フェードアウトにかかる時間[秒]\n /// \n public float FadeOutTime;\n\n /// \n /// カーブのID\n /// \n public string Id;\n\n /// \n /// セグメントの個数\n /// \n public int SegmentCount;\n\n /// \n /// カーブの種類\n /// \n public CubismMotionCurveTarget Type;\n}\n\n/// \n/// イベント。\n/// \npublic record CubismMotionEvent\n{\n public float FireTime;\n\n public string Value;\n}\n\n/// \n/// モーションデータ。\n/// \npublic record CubismMotionData\n{\n /// \n /// カーブの個数\n /// \n public int CurveCount;\n\n /// \n /// カーブのリスト\n /// \n public CubismMotionCurve[] Curves;\n\n /// \n /// モーションの長さ[秒]\n /// \n public float Duration;\n\n /// \n /// UserDataの個数\n /// \n public int EventCount;\n\n /// \n /// イベントのリスト\n /// \n public CubismMotionEvent[] Events;\n\n /// \n /// フレームレート\n /// \n public float Fps;\n\n /// \n /// ループするかどうか\n /// \n public bool Loop;\n\n /// \n /// ポイントのリスト\n /// \n public CubismMotionPoint[] Points;\n\n /// \n /// セグメントのリスト\n /// \n public CubismMotionSegment[] Segments;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppAllocator.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// メモリ確保・解放処理のインターフェースの実装。\n/// フレームワークから呼び出される。\n/// \npublic class LAppAllocator : ICubismAllocator\n{\n /// \n /// メモリ領域を割り当てる。\n /// \n /// 割り当てたいサイズ。\n /// 指定したメモリ領域\n public IntPtr Allocate(int size) { return Marshal.AllocHGlobal(size); }\n\n /// \n /// メモリ領域を解放する\n /// \n /// 解放するメモリ。\n public void Deallocate(IntPtr memory) { Marshal.FreeHGlobal(memory); }\n\n /// \n /// \n /// 割り当てたいサイズ。\n /// 割り当てたいサイズ。\n /// alignedAddress\n public unsafe IntPtr AllocateAligned(int size, int alignment)\n {\n IntPtr offset,\n shift,\n alignedAddress;\n\n IntPtr allocation;\n void** preamble;\n\n offset = alignment - 1 + sizeof(void*);\n\n allocation = Allocate((int)(size + offset));\n\n alignedAddress = allocation + sizeof(void*);\n\n shift = alignedAddress % alignment;\n\n if ( shift != 0 )\n {\n alignedAddress += alignment - shift;\n }\n\n preamble = (void**)alignedAddress;\n preamble[-1] = (void*)allocation;\n\n return alignedAddress;\n }\n\n /// \n /// \n /// 解放するメモリ。\n public unsafe void DeallocateAligned(IntPtr alignedMemory)\n {\n var preamble = (void**)alignedMemory;\n\n Deallocate(new IntPtr(preamble[-1]));\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.App/Program.cs", "using System.Text;\n\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\n\nusing PersonaEngine.Lib;\nusing PersonaEngine.Lib.Core;\n\nusing Serilog;\nusing Serilog.Events;\n\nnamespace PersonaEngine.App;\n\ninternal static class Program\n{\n private static async Task Main()\n {\n Console.OutputEncoding = Encoding.UTF8;\n\n var builder = new ConfigurationBuilder()\n .SetBasePath(Directory.GetCurrentDirectory())\n .AddJsonFile(\"appsettings.json\", false, true);\n\n IConfiguration config = builder.Build();\n var services = new ServiceCollection();\n\n services.AddLogging(loggingBuilder =>\n {\n CreateLogger();\n loggingBuilder.AddSerilog();\n });\n\n services.AddMetrics();\n services.AddApp(config);\n\n var serviceProvider = services.BuildServiceProvider();\n \n var window = serviceProvider.GetRequiredService();\n window.Run();\n\n await serviceProvider.DisposeAsync();\n }\n\n private static void CreateLogger()\n {\n Log.Logger = new LoggerConfiguration()\n .MinimumLevel.Warning()\n .MinimumLevel.Override(\"PersonaEngine.Lib.Core.Conversation\", LogEventLevel.Information)\n .Enrich.FromLogContext()\n .Enrich.With()\n .WriteTo.Console(\n outputTemplate: \"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}\"\n )\n .CreateLogger();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/SilkNetApi.cs", "using PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D;\n\npublic class SilkNetApi : OpenGLApi\n{\n private readonly GL Gl;\n\n private readonly int Height;\n\n private readonly int Width;\n\n public SilkNetApi(GL gl, int width, int height)\n {\n Width = width;\n Height = height;\n Gl = gl;\n }\n\n public override bool IsES2 => false;\n\n public override bool IsPhoneES2 => false;\n\n public override bool AlwaysClear => false;\n\n public override void GetWindowSize(out int w, out int h)\n {\n w = Width;\n h = Height;\n }\n\n public override void ActiveTexture(int bit) { Gl.ActiveTexture((TextureUnit)bit); }\n\n public override void AttachShader(int program, int shader) { Gl.AttachShader((uint)program, (uint)shader); }\n\n public override void BindBuffer(int target, int buffer) { Gl.BindBuffer((BufferTargetARB)target, (uint)buffer); }\n\n public override void BindFramebuffer(int target, int framebuffer) { Gl.BindFramebuffer((FramebufferTarget)target, (uint)framebuffer); }\n\n public override void BindTexture(int target, int texture) { Gl.BindTexture((TextureTarget)target, (uint)texture); }\n\n public override void BindVertexArrayOES(int array) { Gl.BindVertexArray((uint)array); }\n\n public override void BlendFunc(int sfactor, int dfactor) { Gl.BlendFunc((BlendingFactor)sfactor, (BlendingFactor)dfactor); }\n\n public override void BlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { Gl.BlendFuncSeparate((BlendingFactor)srcRGB, (BlendingFactor)dstRGB, (BlendingFactor)srcAlpha, (BlendingFactor)dstAlpha); }\n\n public override void Clear(int mask) { Gl.Clear((ClearBufferMask)mask); }\n\n public override void ClearColor(float r, float g, float b, float a) { Gl.ClearColor(r, g, b, a); }\n\n public override void ClearDepthf(float depth) { Gl.ClearDepth(depth); }\n\n public override void ColorMask(bool r, bool g, bool b, bool a) { Gl.ColorMask(r, g, b, a); }\n\n public override void CompileShader(int shader) { Gl.CompileShader((uint)shader); }\n\n public override int CreateProgram() { return (int)Gl.CreateProgram(); }\n\n public override int CreateShader(int type) { return (int)Gl.CreateShader((ShaderType)type); }\n\n public override void DeleteFramebuffer(int framebuffer) { Gl.DeleteFramebuffer((uint)framebuffer); }\n\n public override void DeleteProgram(int program) { Gl.DeleteProgram((uint)program); }\n\n public override void DeleteShader(int shader) { Gl.DeleteShader((uint)shader); }\n\n public override void DeleteTexture(int texture) { Gl.DeleteTexture((uint)texture); }\n\n public override void DetachShader(int program, int shader) { Gl.DetachShader((uint)program, (uint)shader); }\n\n public override void Disable(int cap) { Gl.Disable((EnableCap)cap); }\n\n public override void DisableVertexAttribArray(int index) { Gl.DisableVertexAttribArray((uint)index); }\n\n public override void DrawElements(int mode, int count, int type, nint indices)\n {\n unsafe\n {\n Gl.DrawElements((PrimitiveType)mode, (uint)count, (DrawElementsType)type, (void*)indices);\n }\n }\n\n public override void Enable(int cap) { Gl.Enable((EnableCap)cap); }\n\n public override void EnableVertexAttribArray(int index) { Gl.EnableVertexAttribArray((uint)index); }\n\n public override void FramebufferTexture2D(int target, int attachment, int textarget, int texture, int level)\n {\n Gl.FramebufferTexture2D((FramebufferTarget)target, (FramebufferAttachment)attachment,\n (TextureTarget)textarget, (uint)texture, level);\n }\n\n public override void FrontFace(int mode) { Gl.FrontFace((FrontFaceDirection)mode); }\n\n public override void GenerateMipmap(int target) { Gl.GenerateMipmap((TextureTarget)target); }\n\n public override int GenFramebuffer() { return (int)Gl.GenFramebuffer(); }\n\n public override int GenTexture() { return (int)Gl.GenTexture(); }\n\n public override int GetAttribLocation(int program, string name) { return Gl.GetAttribLocation((uint)program, name); }\n\n public override void GetBooleanv(int pname, bool[] data) { Gl.GetBoolean((GetPName)pname, out data[0]); }\n\n public override void GetIntegerv(int pname, out int data) { Gl.GetInteger((GetPName)pname, out data); }\n\n public override void GetIntegerv(int pname, int[] data) { Gl.GetInteger((GetPName)pname, out data[0]); }\n\n public override void GetProgramInfoLog(int program, out string infoLog)\n {\n var length = Gl.GetProgram((uint)program, GLEnum.InfoLogLength);\n infoLog = Gl.GetProgramInfoLog((uint)program);\n }\n\n public override unsafe void GetProgramiv(int program, int pname, int* length) { Gl.GetProgram((uint)program, (GLEnum)pname, length); }\n\n public override void GetShaderInfoLog(int shader, out string infoLog)\n {\n var length = Gl.GetShader((uint)shader, GLEnum.InfoLogLength);\n infoLog = Gl.GetShaderInfoLog((uint)shader);\n }\n\n public override unsafe void GetShaderiv(int shader, int pname, int* length) { Gl.GetShader((uint)shader, (GLEnum)pname, length); }\n\n public override int GetUniformLocation(int program, string name) { return Gl.GetUniformLocation((uint)program, name); }\n\n public override void GetVertexAttribiv(int index, int pname, out int @params) { Gl.GetVertexAttrib((uint)index, (VertexAttribPropertyARB)pname, out @params); }\n\n public override bool IsEnabled(int cap) { return Gl.IsEnabled((EnableCap)cap); }\n\n public override void LinkProgram(int program) { Gl.LinkProgram((uint)program); }\n\n public override void ShaderSource(int shader, string source) { Gl.ShaderSource((uint)shader, source); }\n\n public override void TexImage2D(int target, int level, int internalformat, int width, int height, int border,\n int format, int type, nint pixels)\n {\n unsafe\n {\n Gl.TexImage2D((TextureTarget)target, level, (InternalFormat)internalformat,\n (uint)width, (uint)height, border, (PixelFormat)format,\n (PixelType)type, pixels == 0 ? null : (void*)pixels);\n }\n }\n\n public override void TexParameterf(int target, int pname, float param) { Gl.TexParameter((TextureTarget)target, (TextureParameterName)pname, param); }\n\n public override void TexParameteri(int target, int pname, int param) { Gl.TexParameter((TextureTarget)target, (TextureParameterName)pname, param); }\n\n public override void Uniform1i(int location, int v0) { Gl.Uniform1(location, v0); }\n\n public override void Uniform4f(int location, float v0, float v1, float v2, float v3) { Gl.Uniform4(location, v0, v1, v2, v3); }\n\n public override void UniformMatrix4fv(int location, int count, bool transpose, float[] value) { Gl.UniformMatrix4(location, (uint)count, transpose, value); }\n\n public override void UseProgram(int program) { Gl.UseProgram((uint)program); }\n\n public override void ValidateProgram(int program) { Gl.ValidateProgram((uint)program); }\n\n public override void VertexAttribPointer(int index, int size, int type, bool normalized,\n int stride, nint pointer)\n {\n unsafe\n {\n Gl.VertexAttribPointer((uint)index, size, (VertexAttribPointerType)type,\n normalized, (uint)stride, (void*)pointer);\n }\n }\n\n public override void Viewport(int x, int y, int width, int height) { Gl.Viewport(x, y, (uint)width, (uint)height); }\n\n public override int GetError() { return (int)Gl.GetError(); }\n\n public override int GenBuffer() { return (int)Gl.GenBuffer(); }\n\n public override void BufferData(int target, int size, nint data, int usage)\n {\n unsafe\n {\n Gl.BufferData((BufferTargetARB)target, (nuint)size, (void*)data, (BufferUsageARB)usage);\n }\n }\n\n public override int GenVertexArray() { return (int)Gl.GenVertexArray(); }\n\n public override void BindVertexArray(int array) { Gl.BindVertexArray((uint)array); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/RealtimeOptions.cs", "namespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic class RealtimeOptions\n{\n /// \n /// Represents the length of the padding segmetents that will be appended to each sement detected by the VAD.\n /// \n /// \n /// If the VAD detects a segment of 1200ms starting at offset 200ms, and the is 125ms,\n /// 125ms of the original stream will be appended at the beginning and 125ms at the end of the segment.\n /// \n /// \n /// If the original stream is not long enough to append the padding segments, the padding won't be applied.\n /// \n public TimeSpan PaddingDuration { get; set; } = TimeSpan.FromMilliseconds(125);\n\n /// \n /// Represents the minimum length of a segment that will be processed by the transcriptor, if the segment is shorter\n /// than this value it will be ignored.\n /// \n public TimeSpan MinTranscriptDuration { get; set; } = TimeSpan.FromMilliseconds(200);\n\n /// \n /// Represents the minimum length of a segment and if it is shorter than this value it will be padded with silence.\n /// \n /// \n /// If the segment is 700ms, and the is 1100ms, the segment will be padded with\n /// 400ms of silence (200 ms at the beginning and 200ms at the end).\n /// \n public TimeSpan MinDurationWithPadding { get; set; } = TimeSpan.FromMilliseconds(1100);\n\n /// \n /// If set to true, the recognized segments will be concatenated to form the prompt for newer recognition.\n /// \n public bool ConcatenateSegmentsToPrompt { get; set; }\n\n /// \n /// Represents the interval at which the transcriptor will process the audio stream.\n /// \n public TimeSpan ProcessingInterval { get; set; } = TimeSpan.FromMilliseconds(100);\n\n /// \n /// Represents the interval at which the transcriptor will discard silence audio segments.\n /// \n public TimeSpan SilenceDiscardInterval { get; set; } = TimeSpan.FromSeconds(5);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Strategies/MinWordsBargeInStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Input;\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Strategies;\n\npublic class MinWordsBargeInStrategy : IBargeInStrategy\n{\n public bool ShouldAllowBargeIn(BargeInContext context)\n {\n switch ( context.InputEvent )\n {\n case SttSegmentRecognizing segmentRecognizing:\n {\n var wordCount = segmentRecognizing.PartialTranscript.GetWordCount();\n\n return wordCount >= context.ConversationOptions.BargeInMinWords;\n }\n case SttSegmentRecognized segmentRecognized:\n {\n var wordCount = segmentRecognized.FinalTranscript.GetWordCount();\n\n return wordCount >= context.ConversationOptions.BargeInMinWords;\n }\n default:\n return false;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ContextualPhonemeEntry.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record ContextualPhonemeEntry(IReadOnlyDictionary Forms) : PhonemeEntry\n{\n public string? GetForm(string? tag, TokenContext? ctx)\n {\n // First try exact tag match\n if ( tag != null && Forms.TryGetValue(tag, out var exactMatch) )\n {\n return exactMatch;\n }\n\n // Try context-specific form\n if ( ctx?.FutureVowel == null && Forms.TryGetValue(\"None\", out var noneForm) )\n {\n return noneForm;\n }\n\n // Try parent tag\n var parentTag = LexiconUtils.GetParentTag(tag);\n if ( parentTag != null && Forms.TryGetValue(parentTag, out var parentMatch) )\n {\n return parentMatch;\n }\n\n // Finally, use default\n return Forms.TryGetValue(\"DEFAULT\", out var defaultForm) ? defaultForm : null;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Type/RectF.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Type;\n\n/// \n/// 矩形形状(座標・長さはfloat値)を定義するクラス\n/// \npublic class RectF\n{\n /// \n /// 高さ\n /// \n public float Height;\n\n /// \n /// 幅\n /// \n public float Width;\n\n /// \n /// 左端X座標\n /// \n public float X;\n\n /// \n /// 上端Y座標\n /// \n public float Y;\n\n public RectF() { }\n\n /// \n /// 引数付きコンストラクタ\n /// \n /// 左端X座標\n /// 上端Y座標\n /// 幅\n /// 高さ\n public RectF(float x, float y, float w, float h)\n {\n X = x;\n Y = y;\n Width = w;\n Height = h;\n }\n\n /// \n /// 矩形に値をセットする\n /// \n /// 矩形のインスタンス\n public void SetRect(RectF r)\n {\n X = r.X;\n Y = r.Y;\n Width = r.Width;\n Height = r.Height;\n }\n\n /// \n /// 矩形中央を軸にして縦横を拡縮する\n /// \n /// 幅方向に拡縮する量\n /// 高さ方向に拡縮する量\n public void Expand(float w, float h)\n {\n X -= w;\n Y -= h;\n Width += w * 2.0f;\n Height += h * 2.0f;\n }\n\n /// \n /// 矩形中央のX座標を取得する\n /// \n public float GetCenterX() { return X + 0.5f * Width; }\n\n /// \n /// 矩形中央のY座標を取得する\n /// \n public float GetCenterY() { return Y + 0.5f * Height; }\n\n /// \n /// 右端のX座標を取得する\n /// \n public float GetRight() { return X + Width; }\n\n /// \n /// 下端のY座標を取得する\n /// \n public float GetBottom() { return Y + Height; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismDefaultParameterId.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class CubismDefaultParameterId\n{\n // パーツID\n public const string HitAreaPrefix = \"HitArea\";\n\n public const string HitAreaHead = \"Head\";\n\n public const string HitAreaBody = \"Body\";\n\n public const string PartsIdCore = \"Parts01Core\";\n\n public const string PartsArmPrefix = \"Parts01Arm_\";\n\n public const string PartsArmLPrefix = \"Parts01ArmL_\";\n\n public const string PartsArmRPrefix = \"Parts01ArmR_\";\n\n // パラメータID\n public const string ParamAngleX = \"ParamAngleX\";\n\n public const string ParamAngleY = \"ParamAngleY\";\n\n public const string ParamAngleZ = \"ParamAngleZ\";\n\n public const string ParamEyeLOpen = \"ParamEyeLOpen\";\n\n public const string ParamEyeLSmile = \"ParamEyeLSmile\";\n\n public const string ParamEyeROpen = \"ParamEyeROpen\";\n\n public const string ParamEyeRSmile = \"ParamEyeRSmile\";\n\n public const string ParamEyeBallX = \"ParamEyeBallX\";\n\n public const string ParamEyeBallY = \"ParamEyeBallY\";\n\n public const string ParamEyeBallForm = \"ParamEyeBallForm\";\n\n public const string ParamBrowLY = \"ParamBrowLY\";\n\n public const string ParamBrowRY = \"ParamBrowRY\";\n\n public const string ParamBrowLX = \"ParamBrowLX\";\n\n public const string ParamBrowRX = \"ParamBrowRX\";\n\n public const string ParamBrowLAngle = \"ParamBrowLAngle\";\n\n public const string ParamBrowRAngle = \"ParamBrowRAngle\";\n\n public const string ParamBrowLForm = \"ParamBrowLForm\";\n\n public const string ParamBrowRForm = \"ParamBrowRForm\";\n\n public const string ParamMouthForm = \"ParamMouthForm\";\n\n public const string ParamMouthOpenY = \"ParamMouthOpenY\";\n\n public const string ParamCheek = \"ParamCheek\";\n\n public const string ParamBodyAngleX = \"ParamBodyAngleX\";\n\n public const string ParamBodyAngleY = \"ParamBodyAngleY\";\n\n public const string ParamBodyAngleZ = \"ParamBodyAngleZ\";\n\n public const string ParamBreath = \"ParamBreath\";\n\n public const string ParamArmLA = \"ParamArmLA\";\n\n public const string ParamArmRA = \"ParamArmRA\";\n\n public const string ParamArmLB = \"ParamArmLB\";\n\n public const string ParamArmRB = \"ParamArmRB\";\n\n public const string ParamHandL = \"ParamHandL\";\n\n public const string ParamHandR = \"ParamHandR\";\n\n public const string ParamHairFront = \"ParamHairFront\";\n\n public const string ParamHairSide = \"ParamHairSide\";\n\n public const string ParamHairBack = \"ParamHairBack\";\n\n public const string ParamHairFluffy = \"ParamHairFluffy\";\n\n public const string ParamShoulderY = \"ParamShoulderY\";\n\n public const string ParamBustX = \"ParamBustX\";\n\n public const string ParamBustY = \"ParamBustY\";\n\n public const string ParamBaseX = \"ParamBaseX\";\n\n public const string ParamBaseY = \"ParamBaseY\";\n\n public const string ParamNONE = \"NONE\";\n\n public static readonly string ParamVoiceA = \"ParamA\";\n\n public static readonly string ParamVoiceI = \"ParamI\";\n\n public static readonly string ParamVoiceU = \"ParamU\";\n\n public static readonly string ParamVoiceE = \"ParamE\";\n\n public static readonly string ParamVoiceO = \"ParamO\";\n\n public static readonly string ParamVoiceSilence = \"ParamSilence\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismTextureColor.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// テクスチャの色をRGBAで扱うための構造体\n/// \npublic struct CubismTextureColor\n{\n /// \n /// 赤チャンネル\n /// \n public float R;\n\n /// \n /// 緑チャンネル\n /// \n public float G;\n\n /// \n /// 青チャンネル\n /// \n public float B;\n\n /// \n /// αチャンネル\n /// \n public float A;\n\n public CubismTextureColor()\n {\n R = 1.0f;\n G = 1.0f;\n B = 1.0f;\n A = 1.0f;\n }\n\n public CubismTextureColor(CubismTextureColor old)\n {\n R = old.R;\n G = old.G;\n B = old.B;\n A = old.A;\n Check();\n }\n\n public CubismTextureColor(float r, float g, float b, float a)\n {\n R = r;\n G = g;\n B = b;\n A = a;\n Check();\n }\n\n private void Check()\n {\n R = R > 1.0f ? 1f : R;\n G = G > 1.0f ? 1f : G;\n B = B > 1.0f ? 1f : B;\n A = A > 1.0f ? 1f : A;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\npublic interface IAudioSource : IDisposable\n{\n IReadOnlyDictionary Metadata { get; }\n\n /// \n /// Gets the duration of the audio stream.\n /// \n TimeSpan Duration { get; }\n\n /// \n /// Gets the total duration of the audio stream.\n /// \n /// \n /// TotalDuration can include virtual frames that are not available in the source.\n /// \n TimeSpan TotalDuration { get; }\n\n /// \n /// Gets or sets the sample rate of the audio stream.\n /// \n uint SampleRate { get; }\n\n /// \n /// Gets the number of frames available in the stream\n /// \n /// \n /// The total number of samples in the stream is equal to the number of frames multiplied by the number of channels.\n /// \n long FramesCount { get; }\n\n /// \n /// Gets the actual number of channels in the source.\n /// \n /// \n /// Note, that the actual number of channels may be different from the number of channels in the header if the source\n /// uses an aggregation strategy.\n /// \n ushort ChannelCount { get; }\n\n /// \n /// Gets a value indicating whether the stream is initialized.\n /// \n bool IsInitialized { get; }\n\n ushort BitsPerSample { get; }\n\n /// \n /// Gets the memory slices for all the samples interleaved by channel.\n /// \n /// The frame index of the samples to get.\n /// Optional. The maximum length of the frames to get.\n /// The cancellation token to observe.\n /// \n /// \n /// The maximum length of the returned memory is * .\n /// \n Task> GetSamplesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default);\n\n /// \n /// Gets the memory slices for all the frames interleaved by channel.\n /// \n /// The frame index of the samples to get.\n /// Optional. The maximum length of the frames to get.\n /// The cancellation token to observe.\n /// \n /// \n /// The maximum length of the returned memory is * *\n /// / 8.\n /// \n Task> GetFramesAsync(long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default);\n\n Task CopyFramesAsync(Memory destination, long startFrame, int maxFrames = int.MaxValue, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/GLUtility.cs", "using System.Diagnostics.Contracts;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\ninternal static class GlUtility\n{\n [Pure]\n public static float Clamp(float value, float min, float max)\n {\n return value < min\n ? min\n : value > max\n ? max\n : value;\n }\n\n public static void CheckError(this GL gl, string? title = null)\n {\n var error = gl.GetError();\n if ( error == GLEnum.NoError )\n {\n return;\n }\n\n if ( title != null )\n {\n throw new Exception($\"{title}: {error}\");\n }\n\n throw new Exception($\"GL.GetError(): {error}\");\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/PartData.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// パーツにまつわる諸々のデータを管理する。\n/// \npublic record PartData\n{\n /// \n /// 連動するパラメータ\n /// \n public readonly List Link = [];\n\n /// \n /// パーツID\n /// \n public required string PartId { get; set; }\n\n /// \n /// パラメータのインデックス\n /// \n public int ParameterIndex { get; set; }\n\n /// \n /// パーツのインデックス\n /// \n public int PartIndex { get; set; }\n\n /// \n /// 初期化する。\n /// \n /// 初期化に使用するモデル\n public void Initialize(CubismModel model)\n {\n ParameterIndex = model.GetParameterIndex(PartId);\n PartIndex = model.GetPartIndex(PartId);\n\n model.SetParameterValue(ParameterIndex, 1);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TokenContext.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class TokenContext\n{\n public bool? FutureVowel { get; set; }\n\n public bool FutureTo { get; set; }\n\n public static TokenContext UpdateContext(TokenContext ctx, string? phonemes, Token token)\n {\n var vowel = ctx.FutureVowel;\n\n if ( !string.IsNullOrEmpty(phonemes) )\n {\n foreach ( var c in phonemes )\n {\n if ( PhonemizerConstants.Vowels.Contains(c) ||\n PhonemizerConstants.Consonants.Contains(c) ||\n PhonemizerConstants.NonQuotePuncts.Contains(c) )\n {\n vowel = PhonemizerConstants.NonQuotePuncts.Contains(c) ? null : PhonemizerConstants.Vowels.Contains(c);\n\n break;\n }\n }\n }\n\n return new TokenContext { FutureVowel = vowel, FutureTo = token.IsTo() };\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioFormat.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents the format of audio data.\n/// \npublic readonly struct AudioFormat\n{\n /// \n /// The number of channels in the audio.\n /// \n public readonly ushort Channels;\n\n /// \n /// The number of bits per sample.\n /// \n public readonly ushort BitsPerSample;\n\n /// \n /// The sample rate in Hz.\n /// \n public readonly uint SampleRate;\n\n /// \n /// Creates a new audio format.\n /// \n public AudioFormat(ushort channels, ushort bitsPerSample, uint sampleRate)\n {\n Channels = channels;\n BitsPerSample = bitsPerSample;\n SampleRate = sampleRate;\n }\n\n /// \n /// Gets the number of bytes per sample.\n /// \n public int BytesPerSample => BitsPerSample / 8;\n\n /// \n /// Gets the number of bytes per frame (a frame contains one sample for each channel).\n /// \n public int BytesPerFrame => BytesPerSample * Channels;\n\n /// \n /// Creates a mono format with the specified bits per sample and sample rate.\n /// \n public static AudioFormat CreateMono(ushort bitsPerSample, uint sampleRate) { return new AudioFormat(1, bitsPerSample, sampleRate); }\n\n /// \n /// Creates a stereo format with the specified bits per sample and sample rate.\n /// \n public static AudioFormat CreateStereo(ushort bitsPerSample, uint sampleRate) { return new AudioFormat(2, bitsPerSample, sampleRate); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IPlaybackController.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Interface for controlling audio playback scheduling and timing.\n/// \npublic interface IPlaybackController : IDisposable\n{\n /// \n /// Gets the current playback time in seconds.\n /// \n float CurrentTime { get; }\n\n /// \n /// Gets the total number of samples that have been scheduled for playback.\n /// \n long TotalSamplesPlayed { get; }\n\n /// \n /// Gets the current latency in milliseconds.\n /// \n double CurrentLatencyMs { get; }\n\n /// \n /// Gets whether latency information is available.\n /// \n bool HasLatencyInformation { get; }\n\n /// \n /// Event raised when playback time changes significantly.\n /// \n event EventHandler TimeChanged;\n\n /// \n /// Event raised when latency changes significantly.\n /// \n event EventHandler LatencyChanged;\n\n /// \n /// Resets the controller to its initial state.\n /// \n void Reset();\n\n /// \n /// Updates the latency information.\n /// \n /// The latency in milliseconds.\n void UpdateLatency(double latencyMs);\n\n /// \n /// Schedules a packet of audio data for playback.\n /// \n /// The number of samples per channel in the packet.\n /// The sample rate of the audio data.\n /// A token to monitor for cancellation requests.\n /// \n /// A task that completes when the packet is scheduled, with a boolean indicating whether the packet should be\n /// sent.\n /// \n Task SchedulePlaybackAsync(int samplesPerChannel, int sampleRate, CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanityTestData.cs", "namespace PersonaEngine.Lib.TTS.Profanity;\n\npublic class ProfanityTestData\n{\n public static IEnumerable<(string Sentence, bool ExpectedIsProfane)> TestCases => new List<(string, bool)> {\n // Explicit Profanity (Expanded)\n (\"You're a cunt and everyone knows it.\", true),\n (\"Holy shit, that's one massive cock!\", true),\n (\"Bullshit detector going off the charts.\", true),\n (\"Eat a bag of dicks, you worthless twat.\", true),\n (\"This nazi propaganda makes me sick.\", true),\n\n // Innocent Phrases (Expanded)\n (\"Mansfield's historical documents\", false),\n (\"Cockburn Harbour shipping schedule\", false),\n (\"Shitake mushroom risotto recipe\", false),\n (\"Cummins engine specifications\", false),\n (\"Titmouse spotted in woodland area\", false),\n\n // Foreign Words (Expanded)\n (\"Fart means 'speed' in Norwegian\", false),\n (\"Kuk (Polish for 'rooster') symbolism\", false),\n (\"Concha (Spanish seashell) collection\", false),\n (\"Puta madre (Spanish idiom) explanation\", false),\n (\"Fica (Italian fig fruit) exports\", false),\n\n // Contextual Slurs (Expanded)\n (\"Digital rectal examination needed\", false),\n (\"Spasticity in cerebral palsy\", false),\n (\"Midget submarine technology\", true),\n (\"Gyp payment systems\", true),\n (\"Retardant chemical formula\", false),\n\n // Split Evasion (Expanded)\n (\"F.u.c.k.e.r.y in progress\", true),\n (\"B-i-t-c-h please!\", true),\n (\"S H I T B R I C K S\", true),\n\n // Homophones/Near-Misses (Expanded)\n (\"Pass the Bass ale\", false),\n (\"Duck dynasty documentary\", false),\n (\"Master debater competition\", false),\n (\"Cockpit voice recorder data\", false),\n (\"Therapist ass.ociation meeting\", false),\n\n // Implicit Offense (Expanded)\n (\"That's so jewish of you\", true),\n (\"Gypsy lifestyle portrayal\", true),\n (\"Wheelchair-bound vocabulary\", true),\n (\"Tranny fluid replacement\", true), // Mechanical context but problematic\n (\"Pikey market traders\", true),\n\n // Technical Terms (New Category)\n (\"Cumulus cloud formation\", false),\n (\"Scunthorpe town council\", false),\n (\"Cumbustion engine manual\", false), // Typo but should pass\n (\"Clbuttic encoding error\", false),\n (\"Rectum measurement device\", false),\n\n // Cultural References (Expanded)\n (\"Kick the bucket list\", false),\n (\"Donkey's years since\", false),\n (\"The bee's knees cocktail\", false),\n (\"Cat got your tongue?\", false),\n (\"Bob's your uncle\", false),\n\n // Digital Contexts (New Category)\n (\"http://cunt.ly/shortener\", true),\n (\"User@analytics.com\", false),\n (\"WTF_Championship results\", true),\n (\"dickbutt.png filename\", true),\n (\"NSFW_Content_Warning\", true),\n\n // Word Boundaries (New Category)\n (\"Assassin's creed gameplay\", false),\n (\"Classicass movie review\", true), // \"classic ass\"\n (\"Butternut squash soup\", false),\n (\"Masshole driver behavior\", true), // MA + asshole\n (\"Grasshopper infestation\", false),\n\n // Multi-Language Mix (New Category)\n (\"Foda-se (Portuguese) phrasebook\", true),\n (\"Merde alors! (French)\", true),\n (\"Chingado (Spanish) cultural study\", true),\n (\"Kurwa (Polish) linguistics\", true),\n (\"Scheiße (German) dictionary\", true),\n\n // Historical Terms (New Category)\n (\"Niggardly medieval records\", false),\n (\"Spastic colony archives\", true),\n (\"Retardation in horology\", false),\n (\"Gay 90s fashion exhibit\", false),\n (\"Oriental rug cleaning\", false),\n\n // Corporate/Product Names\n (\"Buttplug.io developer tools\", true),\n (\"CumEx Financial scandal\", true),\n (\"Hitler's Poodle pub\", true),\n (\"DikFm radio station\", true),\n (\"FckngKlm apparel brand\", true),\n\n // Poetic/Literary\n (\"Wherefore art thou, Romeo?\", false),\n (\"Shakespeare's sonnet 69\", false),\n (\"Byron's dark fuckëdness\", true),\n (\"Whitman's body electric\", false),\n (\"Plath's bell jar metaphor\", false),\n\n // Youth Vernacular\n (\"That's sus cap no bussin\", false),\n (\"Lit af fam no kizzy\", false),\n (\"She's being extra salty\", false),\n (\"Ghosted his toxic ass\", true),\n (\"Daddy chill vibes only\", true)\n };\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IAudioBufferManager.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Manages audio buffers for playback.\n/// \npublic interface IAudioBufferManager : IAsyncDisposable\n{\n /// \n /// Gets the number of audio buffers in the queue.\n /// \n int BufferCount { get; }\n\n bool ProducerCompleted { get; }\n\n /// \n /// Enqueues audio segments for playback.\n /// \n /// Audio segments to enqueue.\n /// Cancellation token.\n Task EnqueueSegmentsAsync(IAsyncEnumerable audioSegments, CancellationToken cancellationToken);\n\n /// \n /// Tries to get the next audio buffer from the queue.\n /// \n /// The audio buffer if available.\n /// Timeout in milliseconds.\n /// Cancellation token.\n /// True if a buffer was retrieved, false otherwise.\n bool TryGetNextBuffer(out (Memory Data, AudioSegment Segment) buffer, int timeoutMs, CancellationToken cancellationToken);\n\n /// \n /// Clears all buffers from the queue.\n /// \n void Clear();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITtsCache.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for a TTS caching mechanism\n/// \npublic interface ITtsCache : IAsyncDisposable\n{\n /// \n /// Gets or adds an item to the cache\n /// \n /// The type of the item\n /// The cache key\n /// Factory function to create the value if not found\n /// Cancellation token\n /// The cached or newly created value\n Task GetOrAddAsync(\n string key,\n Func> valueFactory,\n CancellationToken cancellationToken = default) where T : class;\n\n /// \n /// Removes an item from the cache\n /// \n /// The cache key to remove\n void Remove(string key);\n\n /// \n /// Clears all items from the cache\n /// \n void Clear();\n\n /// \n /// Gets the current cache statistics\n /// \n /// Tuple with current stats\n (int Size, long Hits, long Misses, long Evictions) GetStatistics();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/NameTextFilter.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic class NameTextFilter : ITextFilter\n{\n public int Priority => 9999;\n\n public ValueTask ProcessAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text ?? string.Empty });\n }\n\n var span = text.AsSpan();\n\n if ( span.Length <= 2 || span[0] != '[' )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n var closingBracketIndex = span.IndexOf(']');\n\n if ( closingBracketIndex <= 1 )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n var remainingSpan = span[(closingBracketIndex + 1)..];\n\n remainingSpan = remainingSpan.TrimStart();\n\n var processedText = remainingSpan.ToString();\n\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = processedText });\n }\n\n public ValueTask PostProcessAsync(TextFilterResult textFilterResult, AudioSegment segment, CancellationToken cancellationToken = default) { return ValueTask.CompletedTask; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigSectionRegistrationTask.cs", "using PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class ConfigSectionRegistrationTask : IStartupTask\n{\n private readonly ChatEditor _chatEditor;\n\n private readonly IConfigSectionRegistry _registry;\n\n private readonly RouletteWheelEditor _rouletteWheelEditor;\n\n private readonly TtsConfigEditor _ttsEditor;\n\n private readonly MicrophoneConfigEditor _microphoneConfigEditor;\n\n public ConfigSectionRegistrationTask(IConfigSectionRegistry registry, TtsConfigEditor ttsEditor, RouletteWheelEditor rouletteWheelEditor, ChatEditor chatEditor, MicrophoneConfigEditor microphoneConfigEditor)\n {\n _registry = registry;\n _ttsEditor = ttsEditor;\n _rouletteWheelEditor = rouletteWheelEditor;\n _chatEditor = chatEditor;\n _microphoneConfigEditor = microphoneConfigEditor;\n }\n\n public void Execute(GL _)\n {\n _registry.RegisterSection(_ttsEditor);\n _registry.RegisterSection(_rouletteWheelEditor);\n _registry.RegisterSection(_chatEditor);\n _registry.RegisterSection(_microphoneConfigEditor);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleLine.cs", "namespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Represents a single line of processed subtitles containing multiple words.\n/// \npublic class SubtitleLine\n{\n public SubtitleLine(int segmentIndex, int lineIndexInSegment)\n {\n SegmentIndex = segmentIndex;\n LineIndexInSegment = lineIndexInSegment;\n }\n\n public List Words { get; } = new();\n\n public float TotalWidth { get; set; }\n\n public float BaselineY { get; set; }\n\n public int SegmentIndex { get; }\n\n public int LineIndexInSegment { get; }\n\n public void AddWord(SubtitleWordInfo word)\n {\n Words.Add(word);\n TotalWidth += word.Size.X;\n }\n\n public void Clear()\n {\n Words.Clear();\n TotalWidth = 0;\n BaselineY = 0;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/OpenGLApi.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic abstract class OpenGLApi\n{\n public readonly int GL_ACTIVE_TEXTURE = 0x84E0;\n\n public readonly int GL_ARRAY_BUFFER = 0x8892;\n\n public readonly int GL_ARRAY_BUFFER_BINDING = 0x8894;\n\n public readonly int GL_BLEND = 0x0BE2;\n\n public readonly int GL_BLEND_DST_ALPHA = 0x80CA;\n\n public readonly int GL_BLEND_DST_RGB = 0x80C8;\n\n public readonly int GL_BLEND_SRC_ALPHA = 0x80CB;\n\n public readonly int GL_BLEND_SRC_RGB = 0x80C9;\n\n public readonly int GL_CCW = 0x0901;\n\n public readonly int GL_CLAMP_TO_EDGE = 0x812F;\n\n public readonly int GL_COLOR_ATTACHMENT0 = 0x8CE0;\n\n public readonly int GL_COLOR_BUFFER_BIT = 0x4000;\n\n public readonly int GL_COLOR_WRITEMASK = 0x0C23;\n\n public readonly int GL_COMPILE_STATUS = 0x8B81;\n\n public readonly int GL_CULL_FACE = 0x0B44;\n\n public readonly int GL_CURRENT_PROGRAM = 0x8B8D;\n\n public readonly int GL_DEPTH_BUFFER_BIT = 0x0100;\n\n public readonly int GL_DEPTH_TEST = 0x0B71;\n\n public readonly int GL_DST_COLOR = 0x0306;\n\n public readonly int GL_ELEMENT_ARRAY_BUFFER = 0x8893;\n\n public readonly int GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;\n\n public readonly int GL_FALSE = 0;\n\n public readonly int GL_FLOAT = 0x1406;\n\n public readonly int GL_FRAGMENT_SHADER = 0x8B30;\n\n public readonly int GL_FRAMEBUFFER = 0x8D40;\n\n public readonly int GL_FRAMEBUFFER_BINDING = 0x8CA6;\n\n public readonly int GL_FRONT_FACE = 0x0B46;\n\n public readonly int GL_INFO_LOG_LENGTH = 0x8B84;\n\n public readonly int GL_LINEAR = 0x2601;\n\n public readonly int GL_LINEAR_MIPMAP_LINEAR = 0x2703;\n\n public readonly int GL_LINK_STATUS = 0x8B82;\n\n public readonly int GL_ONE = 1;\n\n public readonly int GL_ONE_MINUS_SRC_ALPHA = 0x0303;\n\n public readonly int GL_ONE_MINUS_SRC_COLOR = 0x0301;\n\n public readonly int GL_RGBA = 0x1908;\n\n public readonly int GL_SCISSOR_TEST = 0x0C11;\n\n public readonly int GL_SRC_ALPHA = 0x0302;\n\n public readonly int GL_STATIC_DRAW = 0x88E4;\n\n public readonly int GL_STENCIL_TEST = 0x0B90;\n\n public readonly int GL_TEXTURE_2D = 0x0DE1;\n\n public readonly int GL_TEXTURE_BINDING_2D = 0x8069;\n\n public readonly int GL_TEXTURE_MAG_FILTER = 0x2800;\n\n public readonly int GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;\n\n public readonly int GL_TEXTURE_MIN_FILTER = 0x2801;\n\n public readonly int GL_TEXTURE_WRAP_S = 0x2802;\n\n public readonly int GL_TEXTURE_WRAP_T = 0x2803;\n\n public readonly int GL_TEXTURE0 = 0x84C0;\n\n public readonly int GL_TEXTURE1 = 0x84C1;\n\n public readonly int GL_TRIANGLES = 0x0004;\n\n public readonly int GL_UNSIGNED_BYTE = 0x1401;\n\n public readonly int GL_UNSIGNED_SHORT = 0x1403;\n\n public readonly int GL_VALIDATE_STATUS = 0x8B83;\n\n public readonly int GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;\n\n public readonly int GL_VERTEX_SHADER = 0x8B31;\n\n public readonly int GL_VIEWPORT = 0x0BA2;\n\n public readonly int GL_ZERO = 0;\n\n public abstract bool AlwaysClear { get; }\n\n public abstract bool IsES2 { get; }\n\n public abstract bool IsPhoneES2 { get; }\n\n public abstract void Viewport(int x, int y, int w, int h);\n\n public abstract void ClearColor(float r, float g, float b, float a);\n\n public abstract void Clear(int bit);\n\n public abstract void Enable(int bit);\n\n public abstract void Disable(int bit);\n\n public abstract void EnableVertexAttribArray(int index);\n\n public abstract void DisableVertexAttribArray(int index);\n\n public abstract void GetIntegerv(int bit, out int data);\n\n public abstract void GetIntegerv(int bit, int[] data);\n\n public abstract void ActiveTexture(int bit);\n\n public abstract void GetVertexAttribiv(int index, int bit, out int data);\n\n public abstract bool IsEnabled(int bit);\n\n public abstract void GetBooleanv(int bit, bool[] data);\n\n public abstract void UseProgram(int index);\n\n public abstract void FrontFace(int data);\n\n public abstract void ColorMask(bool a, bool b, bool c, bool d);\n\n public abstract void BindBuffer(int bit, int index);\n\n public abstract void BindTexture(int bit, int index);\n\n public abstract void BlendFuncSeparate(int a, int b, int c, int d);\n\n public abstract void DeleteProgram(int index);\n\n public abstract int GetAttribLocation(int index, string attr);\n\n public abstract int GetUniformLocation(int index, string uni);\n\n public abstract void Uniform1i(int index, int data);\n\n public abstract void VertexAttribPointer(int index, int length, int type, bool b, int size, nint arr);\n\n public abstract void Uniform4f(int index, float a, float b, float c, float d);\n\n public abstract void UniformMatrix4fv(int index, int length, bool b, float[] data);\n\n public abstract int CreateProgram();\n\n public abstract void AttachShader(int a, int b);\n\n public abstract void DeleteShader(int index);\n\n public abstract void DetachShader(int index, int data);\n\n public abstract int CreateShader(int type);\n\n public abstract void ShaderSource(int a, string source);\n\n public abstract void CompileShader(int index);\n\n public abstract unsafe void GetShaderiv(int index, int type, int* length);\n\n public abstract void GetShaderInfoLog(int index, out string log);\n\n public abstract void LinkProgram(int index);\n\n public abstract unsafe void GetProgramiv(int index, int type, int* length);\n\n public abstract void GetProgramInfoLog(int index, out string log);\n\n public abstract void ValidateProgram(int index);\n\n public abstract void DrawElements(int type, int count, int type1, nint arry);\n\n public abstract void BindVertexArrayOES(int data);\n\n public abstract void TexParameterf(int type, int type1, float value);\n\n public abstract void BindFramebuffer(int type, int data);\n\n public abstract int GenTexture();\n\n public abstract void TexImage2D(int type, int a, int type1, int w, int h, int size, int type2, int type3, IntPtr data);\n\n public abstract void TexParameteri(int a, int b, int c);\n\n public abstract int GenFramebuffer();\n\n public abstract void FramebufferTexture2D(int a, int b, int c, int buff, int data);\n\n public abstract void DeleteTexture(int data);\n\n public abstract void DeleteFramebuffer(int fb);\n\n public abstract void BlendFunc(int a, int b);\n\n public abstract void GetWindowSize(out int w, out int h);\n\n public abstract void GenerateMipmap(int a);\n\n public abstract void ClearDepthf(float data);\n\n public abstract int GetError();\n\n public abstract int GenBuffer();\n\n public abstract void BufferData(int type, int v1, nint v2, int type1);\n\n public abstract int GenVertexArray();\n\n public abstract void BindVertexArray(int vertexArray);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/IRVCVoiceProvider.cs", "namespace PersonaEngine.Lib.TTS.RVC;\n\npublic interface IRVCVoiceProvider : IAsyncDisposable\n{\n /// \n /// Gets the fullpath to the voice model\n /// \n /// Voice identifier\n /// Cancellation token\n /// Voice model path\n Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets all available voice IDs\n /// \n /// List of voice IDs\n Task> GetAvailableVoicesAsync(\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/RealtimeSpeechTranscriptorOptions.cs", "using PersonaEngine.Lib.ASR.Transcriber;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic record RealtimeSpeechTranscriptorOptions : SpeechTranscriptorOptions\n{\n /// \n /// Gets or sets a value indicating whether to include speech recognizing events.\n /// \n /// \n /// This events are emitted before the segment is complete and are not final.\n /// \n public bool IncludeSpeechRecogizingEvents { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to autodetect the language only once at startup and use it for all the\n /// segments, instead of autodetecting it for each segment.\n /// \n public bool AutodetectLanguageOnce { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsInternal.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// 物理演算の適用先の種類。\n/// \npublic enum CubismPhysicsTargetType\n{\n /// \n /// パラメータに対して適用\n /// \n CubismPhysicsTargetType_Parameter\n}\n\n/// \n/// 物理演算の入力の種類。\n/// \npublic enum CubismPhysicsSource\n{\n /// \n /// X軸の位置から\n /// \n CubismPhysicsSource_X,\n\n /// \n /// Y軸の位置から\n /// \n CubismPhysicsSource_Y,\n\n /// \n /// 角度から\n /// \n CubismPhysicsSource_Angle\n}\n\n/// \n/// 物理演算で使用する外部の力。\n/// \npublic record PhysicsJsonEffectiveForces\n{\n /// \n /// 重力\n /// \n public Vector2 Gravity;\n\n /// \n /// 風\n /// \n public Vector2 Wind;\n}\n\n/// \n/// 物理演算のパラメータ情報。\n/// \npublic record CubismPhysicsParameter\n{\n /// \n /// パラメータID\n /// \n public required string Id;\n\n /// \n /// 適用先の種類\n /// \n public CubismPhysicsTargetType TargetType;\n}\n\n/// \n/// 物理演算の正規化情報。\n/// \npublic record CubismPhysicsNormalization\n{\n /// \n /// デフォルト値\n /// \n public float Default;\n\n /// \n /// 最小値\n /// \n public float Maximum;\n\n /// \n /// 最大値\n /// \n public float Minimum;\n}\n\n/// \n/// 物理演算の演算に使用する物理点の情報。\n/// \npublic record CubismPhysicsParticle\n{\n /// \n /// 加速度\n /// \n public float Acceleration;\n\n /// \n /// 遅れ\n /// \n public float Delay;\n\n /// \n /// 現在かかっている力\n /// \n public Vector2 Force;\n\n /// \n /// 初期位置\n /// \n public Vector2 InitialPosition;\n\n /// \n /// 最後の重力\n /// \n public Vector2 LastGravity;\n\n /// \n /// 最後の位置\n /// \n public Vector2 LastPosition;\n\n /// \n /// 動きやすさ\n /// \n public float Mobility;\n\n /// \n /// 現在の位置\n /// \n public Vector2 Position;\n\n /// \n /// 距離\n /// \n public float Radius;\n\n /// \n /// 現在の速度\n /// \n public Vector2 Velocity;\n}\n\n/// \n/// 物理演算の物理点の管理。\n/// \npublic record CubismPhysicsSubRig\n{\n /// \n /// 入力の最初のインデックス\n /// \n public int BaseInputIndex;\n\n /// \n /// 出力の最初のインデックス\n /// \n public int BaseOutputIndex;\n\n /// \n /// /物理点の最初のインデックス\n /// \n public int BaseParticleIndex;\n\n /// \n /// 入力の個数\n /// \n public int InputCount;\n\n /// \n /// 正規化された角度\n /// \n public required CubismPhysicsNormalization NormalizationAngle;\n\n /// \n /// 正規化された位置\n /// \n public required CubismPhysicsNormalization NormalizationPosition;\n\n /// \n /// 出力の個数\n /// \n public int OutputCount;\n\n /// \n /// 物理点の個数\n /// \n public int ParticleCount;\n}\n\n/// \n/// 正規化されたパラメータの取得関数の宣言。\n/// \n/// 演算結果の移動値\n/// 演算結果の角度\n/// パラメータの値\n/// パラメータの最小値\n/// パラメータの最大値\n/// パラメータのデフォルト値\n/// 正規化された位置\n/// 正規化された角度\n/// 値が反転されているか?\n/// 重み\npublic delegate void NormalizedPhysicsParameterValueGetter(\n ref Vector2 targetTranslation,\n ref float targetAngle,\n float value,\n float parameterMinimumValue,\n float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted,\n float weight\n);\n\n/// \n/// 物理演算の値の取得関数の宣言。\n/// \n/// 移動値\n/// 物理点のリスト\n/// \n/// 値が反転されているか?\n/// 重力\n/// \npublic delegate float PhysicsValueGetter(\n Vector2 translation,\n CubismPhysicsParticle[] particles,\n int currentParticleIndex,\n int particleIndex,\n bool isInverted,\n Vector2 parentGravity\n);\n\n/// \n/// 物理演算のスケールの取得関数の宣言。\n/// \n/// 移動値のスケール\n/// 角度のスケール\n/// スケール値\npublic delegate float PhysicsScaleGetter(Vector2 translationScale, float angleScale);\n\n/// \n/// 物理演算の入力情報。\n/// \npublic record CubismPhysicsInput\n{\n /// \n /// 正規化されたパラメータ値の取得関数\n /// \n public NormalizedPhysicsParameterValueGetter GetNormalizedParameterValue;\n\n /// \n /// 値が反転されているかどうか\n /// \n public bool Reflect;\n\n /// \n /// 入力元のパラメータ\n /// \n public required CubismPhysicsParameter Source;\n\n /// \n /// 入力元のパラメータのインデックス\n /// \n public int SourceParameterIndex;\n\n /// \n /// 入力の種類\n /// \n public CubismPhysicsSource Type;\n\n /// \n /// 重み\n /// \n public float Weight;\n}\n\n/// \n/// 物理演算の出力情報。\n/// \npublic record CubismPhysicsOutput\n{\n /// \n /// 角度のスケール\n /// \n public float AngleScale;\n\n /// \n /// 出力先のパラメータ\n /// \n public required CubismPhysicsParameter Destination;\n\n /// \n /// 出力先のパラメータのインデックス\n /// \n public int DestinationParameterIndex;\n\n /// \n /// 物理演算のスケール値の取得関数\n /// \n public PhysicsScaleGetter GetScale;\n\n /// \n /// 物理演算の値の取得関数\n /// \n public PhysicsValueGetter GetValue;\n\n /// \n /// 値が反転されているかどうか\n /// \n public bool Reflect;\n\n /// \n /// 移動値のスケール\n /// \n public Vector2 TranslationScale;\n\n /// \n /// 出力の種類\n /// \n public CubismPhysicsSource Type;\n\n /// \n /// 最小値を下回った時の値\n /// \n public float ValueBelowMinimum;\n\n /// \n /// 最大値をこえた時の値\n /// \n public float ValueExceededMaximum;\n\n /// \n /// 振り子のインデックス\n /// \n public int VertexIndex;\n\n /// \n /// 重み\n /// \n public float Weight;\n}\n\n/// \n/// 物理演算のデータ。\n/// \npublic record CubismPhysicsRig\n{\n /// \n /// 物理演算動作FPS\n /// \n public float Fps;\n\n /// \n /// 重力\n /// \n public Vector2 Gravity;\n\n /// \n /// 物理演算の入力のリスト\n /// \n public required CubismPhysicsInput[] Inputs;\n\n /// \n /// 物理演算の出力のリスト\n /// \n public required CubismPhysicsOutput[] Outputs;\n\n /// \n /// 物理演算の物理点のリスト\n /// \n public required CubismPhysicsParticle[] Particles;\n\n /// \n /// 物理演算の物理点の管理のリスト\n /// \n public required CubismPhysicsSubRig[] Settings;\n\n /// \n /// 物理演算の物理点の個数\n /// \n public int SubRigCount;\n\n /// \n /// 風\n /// \n public Vector2 Wind;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismLog.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class CubismLog\n{\n public static void CubismLogPrintln(LogLevel level, string head, string fmt, params object?[] args)\n {\n var data = $\"[CSM] {head} {string.Format(fmt, args)}\";\n if ( level < CubismFramework.GetLoggingLevel() )\n {\n return;\n }\n\n CubismFramework.CoreLogFunction(data);\n }\n\n public static void Verbose(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Verbose, \"[V]\", fmt, args); }\n\n public static void Debug(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Debug, \"[D]\", fmt, args); }\n\n public static void Info(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Info, \"[I]\", fmt, args); }\n\n public static void Warning(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Warning, \"[W]\", fmt, args); }\n\n public static void Error(string fmt, params object?[] args) { CubismLogPrintln(LogLevel.Error, \"[E]\", fmt, args); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/RouletteWheelOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record RouletteWheelOptions\n{\n // Font and Text Settings\n public string Font { get; set; } = \"DynaPuff_Condensed-Bold.ttf\";\n\n public int FontSize { get; set; } = 24;\n\n public string TextColor { get; set; } = \"#FFFFFF\";\n\n public float TextScale { get; set; } = 1f;\n\n public int TextStroke { get; set; } = 2;\n\n public bool AdaptiveText { get; set; } = true;\n\n public bool RadialTextOrientation { get; set; } = true;\n\n // Wheel Configuration\n public string[] SectionLabels { get; set; } = [];\n\n public float SpinDuration { get; set; } = 8f;\n\n public float MinRotations { get; set; } = 5f;\n\n public float WheelSizePercentage { get; set; } = 1.0f;\n\n // Viewport and Position\n public int Width { get; set; } = 1080;\n\n public int Height { get; set; } = 1080;\n\n public string PositionMode { get; set; } = \"Anchored\"; // \"Absolute\", \"Percentage\", or \"Anchored\"\n\n public string ViewportAnchor { get; set; } = \"Center\"; // One of the ViewportAnchor enum values\n\n public float PositionXPercentage { get; set; } = 0.5f;\n\n public float PositionYPercentage { get; set; } = 0.5f;\n\n public float AnchorOffsetX { get; set; } = 0f;\n\n public float AnchorOffsetY { get; set; } = 0f;\n\n public float AbsolutePositionX { get; set; } = 0f;\n\n public float AbsolutePositionY { get; set; } = 0f;\n\n // State and Animation\n public bool Enabled { get; set; } = false;\n\n public float RotationDegrees { get; set; } = 0;\n\n public bool AnimateToggle { get; set; } = true;\n\n public float AnimationDuration { get; set; } = 0.5f;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IAwaitableAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents an audio source that can be awaited for new samples and can be flushed.\n/// \npublic interface IAwaitableAudioSource : IAudioSource\n{\n bool IsFlushed { get; }\n\n /// \n /// Waits for new samples to be available.\n /// \n /// The sample count to wait for.\n /// The cancellation token.\n /// The number of times the wait was performed.\n Task WaitForInitializationAsync(CancellationToken cancellationToken);\n\n /// \n /// Waits for the source to have at least the specified number of samples.\n /// \n /// The cancellation token.\n Task WaitForNewSamplesAsync(long sampleCount, CancellationToken cancellationToken);\n\n /// \n /// Waits for the source to be at least the specified duration.\n /// \n /// The cancellation token.\n /// \n Task WaitForNewSamplesAsync(TimeSpan minimumDuration, CancellationToken cancellationToken);\n\n /// \n /// Flushes the stream, indicating that no more data will be written.\n /// \n void Flush();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ActiveOperation.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Data structure for active operations with progress tracking\n/// \npublic class ActiveOperation\n{\n public ActiveOperation(string id, string name)\n {\n Id = id;\n Name = name;\n Progress = 0f;\n CancellationSource = new CancellationTokenSource();\n }\n\n public string Id { get; }\n\n public string Name { get; }\n\n public float Progress { get; set; }\n\n public CancellationTokenSource CancellationSource { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismClippingContext.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Type;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic unsafe class CubismClippingContext(CubismClippingManager manager, int* clippingDrawableIndices, int clipCount)\n{\n /// \n /// このクリッピングで、クリッピングされる全ての描画オブジェクトの囲み矩形(毎回更新)\n /// \n public RectF AllClippedDrawRect = new();\n\n /// \n /// このマスクが割り当てられるレンダーテクスチャ(フレームバッファ)やカラーバッファのインデックス\n /// \n public int BufferIndex;\n\n /// \n /// このマスクにクリップされる描画オブジェクトのリスト\n /// \n public List ClippedDrawableIndexList = [];\n\n /// \n /// クリッピングマスクの数\n /// \n public int ClippingIdCount = clipCount;\n\n /// \n /// クリッピングマスクのIDリスト\n /// \n public int* ClippingIdList = clippingDrawableIndices;\n\n /// \n /// 現在の描画状態でマスクの準備が必要ならtrue\n /// \n public bool IsUsing;\n\n /// \n /// マスク用チャンネルのどの領域にマスクを入れるか(View座標-1..1, UVは0..1に直す)\n /// \n public RectF LayoutBounds = new();\n\n /// \n /// RGBAのいずれのチャンネルにこのクリップを配置するか(0:R , 1:G , 2:B , 3:A)\n /// \n public int LayoutChannelIndex = 0;\n\n /// \n /// 描画オブジェクトの位置計算結果を保持する行列\n /// \n public CubismMatrix44 MatrixForDraw = new();\n\n /// \n /// マスクの位置計算結果を保持する行列\n /// \n public CubismMatrix44 MatrixForMask = new();\n\n public CubismClippingManager Manager { get; } = manager;\n\n /// \n /// このマスクにクリップされる描画オブジェクトを追加する\n /// \n /// クリッピング対象に追加する描画オブジェクトのインデックス\n public void AddClippedDrawable(int drawableIndex) { ClippedDrawableIndexList.Add(drawableIndex); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IAudioTransport.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Defines methods for transporting audio data over a network.\n/// \npublic interface IAudioTransport : IAsyncDisposable\n{\n /// \n /// Initializes the transport.\n /// \n Task InitializeAsync();\n\n /// \n /// Sends an audio packet over the transport.\n /// \n /// Audio data to send.\n /// Sample rate of the audio.\n /// Number of samples per channel.\n /// Number of audio channels.\n /// Cancellation token.\n Task SendAudioPacketAsync(\n ReadOnlyMemory audioData,\n int sampleRate,\n int samplesPerChannel,\n int channels,\n CancellationToken cancellationToken);\n\n Task FlushAsync(CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Strategies/AllowBargeInStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Strategies;\n\n public class AllowBargeInStrategy : IBargeInStrategy\n {\n public bool ShouldAllowBargeIn(BargeInContext context)\n {\n return true;\n }\n }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IModelProvider.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for model loading and management\n/// \npublic interface IModelProvider : IAsyncDisposable\n{\n /// \n /// Gets a model by type\n /// \n /// Type of model\n /// Cancellation token\n /// Model resource\n Task GetModelAsync(\n ModelType modelType,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroInferenceState.cs", "using Microsoft.ML.OnnxRuntime;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroInferenceState(OrtIoBinding binding)\n{\n /// Array for storing the context + input\n\n public float[] State { get; set; } = new float[SileroConstants.StateSize];\n\n // The state for the next inference\n public float[] PendingState { get; set; } = new float[SileroConstants.StateSize];\n\n public float[] Output { get; set; } = new float[SileroConstants.OutputSize];\n\n public OrtIoBinding Binding { get; } = binding;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleWordInfo.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Holds the intrinsic properties and calculated state of a single word for rendering.\n/// Designed as a struct to potentially reduce GC pressure when dealing with many words,\n/// but be mindful of copying costs if passed around extensively by value.\n/// \npublic struct SubtitleWordInfo\n{\n public string Text;\n\n public Vector2 Size;\n\n public float AbsoluteStartTime;\n\n public float Duration;\n\n public Vector2 Position;\n\n public float AnimationProgress;\n\n public FSColor CurrentColor;\n\n public Vector2 CurrentScale;\n\n public bool IsActive(float currentTime) { return currentTime >= AbsoluteStartTime && currentTime < AbsoluteStartTime + Duration; }\n\n public bool IsComplete(float currentTime) { return currentTime >= AbsoluteStartTime + Duration; }\n\n public bool HasStarted(float currentTime) { return currentTime >= AbsoluteStartTime; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/AtomicCounter.cs", "using System.Runtime.CompilerServices;\n\nnamespace PersonaEngine.Lib.Utils;\n\n/// \n/// Thread-safe counter implementation.\n/// \npublic class AtomicCounter\n{\n private uint _value;\n\n public uint GetValue() { return _value; }\n\n public uint Increment() { return (uint)Interlocked.Increment(ref Unsafe.As(ref _value)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/IRenderComponent.cs", "using Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nnamespace PersonaEngine.Lib.UI;\n\npublic interface IRenderComponent : IDisposable\n{\n bool UseSpout { get; }\n\n string SpoutTarget { get; }\n \n /// \n /// Priority of the filter (higher values run first)\n /// \n int Priority { get; }\n\n void Update(float deltaTime);\n\n void Render(float deltaTime);\n\n void Resize();\n\n void Initialize(GL gl, IView view, IInputContext input);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsCacheOptions.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Options for configuring the TTS memory cache behavior\n/// \npublic class TtsCacheOptions\n{\n /// \n /// Maximum number of items to store in the cache (0 = unlimited)\n /// \n public int MaxItems { get; set; } = 1000;\n\n /// \n /// Time after which cache items expire (null = never expire)\n /// \n public TimeSpan? ItemExpiration { get; set; } = TimeSpan.FromHours(1);\n\n /// \n /// Whether to collect performance metrics\n /// \n public bool CollectMetrics { get; set; } = true;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/InteractionTurn.cs", "using OpenAI.Chat;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic class InteractionTurn\n{\n public InteractionTurn(Guid turnId, IEnumerable participantIds, DateTimeOffset startTime, DateTimeOffset? endTime, IEnumerable messages, bool wasInterrupted)\n {\n TurnId = turnId;\n ParticipantIds = participantIds.ToList().AsReadOnly();\n StartTime = startTime;\n EndTime = endTime;\n Messages = messages.ToList();\n WasInterrupted = wasInterrupted;\n }\n\n private InteractionTurn(Guid turnId, IEnumerable participantIds, DateTimeOffset startTime, IEnumerable messages)\n {\n TurnId = turnId;\n ParticipantIds = participantIds.ToList().AsReadOnly();\n StartTime = startTime;\n EndTime = null;\n Messages = messages.Select(m => new ChatMessage(m.MessageId, m.ParticipantId, m.ParticipantName, m.Text, m.Timestamp, m.IsPartial, m.Role)).ToList();\n WasInterrupted = false;\n }\n\n public Guid TurnId { get; }\n\n public IReadOnlyList ParticipantIds { get; }\n\n public DateTimeOffset StartTime { get; }\n\n public DateTimeOffset? EndTime { get; internal set; }\n\n public List Messages { get; }\n\n public bool WasInterrupted { get; internal set; }\n\n internal InteractionTurn CreateSnapshot() { return new InteractionTurn(TurnId, ParticipantIds, StartTime, Messages); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/MicrophoneConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record MicrophoneConfiguration\n{\n /// \n /// The friendly name of the desired input device.\n /// If null, empty, or whitespace, the default device (DeviceNumber 0) will be used.\n /// \n public string? DeviceName { get; init; } = null;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IDiscardableAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Represents a source that can discard frames from the beginning of the audio stream if they are no longer needed.\n/// \npublic interface IDiscardableAudioSource : IAudioSource\n{\n /// \n /// Discards a specified number of frames.\n /// \n /// The number of frames to discard.\n void DiscardFrames(int count);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiTheme.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// UI theme configuration data\n/// \npublic class UiTheme\n{\n public Vector4 TextColor { get; set; } = new(1.0f, 1.0f, 1.0f, 1.0f);\n\n public float WindowRounding { get; set; } = 10.0f;\n\n public float FrameRounding { get; set; } = 5.0f;\n\n public Vector2 WindowPadding { get; set; } = new(8.0f, 8.0f);\n\n public Vector2 FramePadding { get; set; } = new(5.0f, 3.5f);\n\n public Vector2 ItemSpacing { get; set; } = new(5.0f, 4.0f);\n\n // All style properties from TOML\n public float Alpha { get; set; } = 1.0f;\n\n public float DisabledAlpha { get; set; } = 0.1000000014901161f;\n\n public float WindowBorderSize { get; set; } = 0.0f;\n\n public Vector2 WindowMinSize { get; set; } = new(30.0f, 30.0f);\n\n public Vector2 WindowTitleAlign { get; set; } = new(0.5f, 0.5f);\n\n public string WindowMenuButtonPosition { get; set; } = \"Right\";\n\n public float ChildRounding { get; set; } = 5.0f;\n\n public float ChildBorderSize { get; set; } = 1.0f;\n\n public float PopupRounding { get; set; } = 10.0f;\n\n public float PopupBorderSize { get; set; } = 0.0f;\n\n public float FrameBorderSize { get; set; } = 0.0f;\n\n public Vector2 ItemInnerSpacing { get; set; } = new(5.0f, 5.0f);\n\n public Vector2 CellPadding { get; set; } = new(4.0f, 2.0f);\n\n public float IndentSpacing { get; set; } = 5.0f;\n\n public float ColumnsMinSpacing { get; set; } = 5.0f;\n\n public float ScrollbarSize { get; set; } = 15.0f;\n\n public float ScrollbarRounding { get; set; } = 9.0f;\n\n public float GrabMinSize { get; set; } = 15.0f;\n\n public float GrabRounding { get; set; } = 5.0f;\n\n public float TabRounding { get; set; } = 5.0f;\n\n public float TabBorderSize { get; set; } = 0.0f;\n\n public float TabCloseButtonMinWidthSelected { get; set; } = 0.0f;\n\n public float TabCloseButtonMinWidthUnselected { get; set; } = 0.0f;\n\n public string ColorButtonPosition { get; set; } = \"Right\";\n\n public Vector2 ButtonTextAlign { get; set; } = new(0.5f, 0.5f);\n\n public Vector2 SelectableTextAlign { get; set; } = new(0.0f, 0.0f);\n\n // All colors from TOML\n public Vector4 TextDisabledColor { get; set; } = new(1.0f, 1.0f, 1.0f, 0.3605149984359741f);\n\n public Vector4 WindowBgColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 ChildBgColor { get; set; } = new(1.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 PopupBgColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 BorderColor { get; set; } = new(0.424f, 0.380f, 0.573f, 0.54935622215271f);\n\n public Vector4 BorderShadowColor { get; set; } = new(0.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 FrameBgColor { get; set; } = new(0.157f, 0.157f, 0.157f, 1.0f);\n\n public Vector4 FrameBgHoveredColor { get; set; } = new(0.380f, 0.424f, 0.573f, 0.5490196347236633f);\n\n public Vector4 FrameBgActiveColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 TitleBgColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 TitleBgActiveColor { get; set; } = new(0.098f, 0.098f, 0.098f, 1.0f);\n\n public Vector4 TitleBgCollapsedColor { get; set; } = new(0.259f, 0.259f, 0.259f, 0.0f);\n\n public Vector4 MenuBarBgColor { get; set; } = new(0.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 ScrollbarBgColor { get; set; } = new(0.157f, 0.157f, 0.157f, 0.0f);\n\n public Vector4 ScrollbarGrabColor { get; set; } = new(0.157f, 0.157f, 0.157f, 1.0f);\n\n public Vector4 ScrollbarGrabHoveredColor { get; set; } = new(0.235f, 0.235f, 0.235f, 1.0f);\n\n public Vector4 ScrollbarGrabActiveColor { get; set; } = new(0.294f, 0.294f, 0.294f, 1.0f);\n\n public Vector4 CheckMarkColor { get; set; } = new(0.294f, 0.294f, 0.294f, 1.0f);\n\n public Vector4 SliderGrabColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 SliderGrabActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 ButtonColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 ButtonHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 ButtonActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 HeaderColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 HeaderHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 HeaderActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 SeparatorColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 SeparatorHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 SeparatorActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 ResizeGripColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 ResizeGripHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 ResizeGripActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 TabColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 TabHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 TabActiveColor { get; set; } = new(0.816f, 0.773f, 0.965f, 0.5490196347236633f);\n\n public Vector4 TabUnfocusedColor { get; set; } = new(0.0f, 0.451f, 1.0f, 0.0f);\n\n public Vector4 TabUnfocusedActiveColor { get; set; } = new(0.133f, 0.259f, 0.424f, 0.0f);\n\n public Vector4 PlotLinesColor { get; set; } = new(0.294f, 0.294f, 0.294f, 1.0f);\n\n public Vector4 PlotLinesHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 PlotHistogramColor { get; set; } = new(0.620f, 0.576f, 0.769f, 0.5490196347236633f);\n\n public Vector4 PlotHistogramHoveredColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 TableHeaderBgColor { get; set; } = new(0.188f, 0.188f, 0.200f, 1.0f);\n\n public Vector4 TableBorderStrongColor { get; set; } = new(0.424f, 0.380f, 0.573f, 0.5490196347236633f);\n\n public Vector4 TableBorderLightColor { get; set; } = new(0.424f, 0.380f, 0.573f, 0.2918455004692078f);\n\n public Vector4 TableRowBgColor { get; set; } = new(0.0f, 0.0f, 0.0f, 0.0f);\n\n public Vector4 TableRowBgAltColor { get; set; } = new(1.0f, 1.0f, 1.0f, 0.03433477878570557f);\n\n public Vector4 TextSelectedBgColor { get; set; } = new(0.737f, 0.694f, 0.886f, 0.5490196347236633f);\n\n public Vector4 DragDropTargetColor { get; set; } = new(1.0f, 1.0f, 0.0f, 0.8999999761581421f);\n\n public Vector4 NavWindowingHighlightColor { get; set; } = new(1.0f, 1.0f, 1.0f, 0.699999988079071f);\n\n public Vector4 NavWindowingDimBgColor { get; set; } = new(0.8f, 0.8f, 0.8f, 0.2000000029802322f);\n\n public Vector4 ModalWindowDimBgColor { get; set; } = new(0.8f, 0.8f, 0.8f, 0.3499999940395355f);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/TranscriptToken.cs", "namespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic class TranscriptToken\n{\n /// \n /// The logaritmic confidence of the token.\n /// \n public float? ConfidenceLog;\n\n /// \n /// The text representation of the token.\n /// \n public string? Text;\n\n /// \n /// The unique identifier for the token for transcriptors that uses IDs\n /// \n /// \n /// The type is object to allow for different types of IDs based on the transcriptor, this ID is not used inside\n /// EchoSharp library.\n /// \n public object? Id { get; set; }\n\n /// \n /// The confidence of the token.\n /// \n public float? Confidence { get; set; }\n\n /// \n /// The confidence of the timestamp of the token.\n /// \n public float TimestampConfidence { get; set; }\n\n /// \n /// The timestamp confidence sum of the token.\n /// \n public float TimestampConfidenceSum { get; set; }\n\n /// \n /// The start time of the token.\n /// \n public TimeSpan StartTime { get; set; }\n\n /// \n /// The duration of the token.\n /// \n public TimeSpan Duration { get; set; }\n\n /// \n /// Dynamic Time Warping timestamp of the token.\n /// \n public long DtwTimestamp { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsObj.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\npublic record CubismPhysicsObj\n{\n public MetaObj Meta { get; set; }\n\n public List PhysicsSettings { get; set; }\n\n public record MetaObj\n {\n public EffectiveForce EffectiveForces { get; set; }\n\n public float Fps { get; set; }\n\n public int PhysicsSettingCount { get; set; }\n\n public int TotalInputCount { get; set; }\n\n public int TotalOutputCount { get; set; }\n\n public int VertexCount { get; set; }\n\n public record EffectiveForce\n {\n public Vector2 Gravity { get; set; }\n\n public Vector2 Wind { get; set; }\n }\n }\n\n public record PhysicsSetting\n {\n public NormalizationObj Normalization { get; set; }\n\n public List Input { get; set; }\n\n public List Output { get; set; }\n\n public List Vertices { get; set; }\n\n public record NormalizationObj\n {\n public PositionObj Position { get; set; }\n\n public PositionObj Angle { get; set; }\n\n public record PositionObj\n {\n public float Minimum { get; set; }\n\n public float Maximum { get; set; }\n\n public float Default { get; set; }\n }\n }\n\n public record InputObj\n {\n public float Weight { get; set; }\n\n public bool Reflect { get; set; }\n\n public string Type { get; set; }\n\n public SourceObj Source { get; set; }\n\n public record SourceObj\n {\n public string Id { get; set; }\n }\n }\n\n public record OutputObj\n {\n public int VertexIndex { get; set; }\n\n public float Scale { get; set; }\n\n public float Weight { get; set; }\n\n public DestinationObj Destination { get; set; }\n\n public string Type { get; set; }\n\n public bool Reflect { get; set; }\n\n public record DestinationObj\n {\n public string Id { get; set; }\n }\n }\n\n public record Vertice\n {\n public float Mobility { get; set; }\n\n public float Delay { get; set; }\n\n public float Acceleration { get; set; }\n\n public float Radius { get; set; }\n\n public Vector2 Position { get; set; }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/SubtitleOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\n/// \n/// Configuration for the subtitle renderer\n/// \npublic class SubtitleOptions\n{\n public string Font { get; set; } = \"DynaPuff_Condensed-Bold.ttf\";\n\n public int FontSize { get; set; } = 72;\n\n public string Color { get; set; } = \"#FFFFFF\";\n\n public string HighlightColor { get; set; } = \"#4FC3F7\";\n\n public int BottomMargin { get; set; } = 50;\n\n public int SideMargin { get; set; } = 100;\n\n public float InterSegmentSpacing { get; set; } = 16f;\n\n public int MaxVisibleLines { get; set; } = 6;\n\n public float AnimationDuration { get; set; } = 0.3f;\n \n public int StrokeThickness { get; set; } = 3;\n\n public int Width { get; set; } = 1920;\n\n public int Height { get; set; } = 1080;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/EditorStateChangedEventArgs.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Event arguments for editor state changes\n/// \npublic class EditorStateChangedEventArgs : EventArgs\n{\n public EditorStateChangedEventArgs(string stateKey, object oldValue, object newValue)\n {\n StateKey = stateKey;\n OldValue = oldValue;\n NewValue = newValue;\n }\n\n public string StateKey { get; }\n\n public object OldValue { get; }\n\n public object NewValue { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IPhonemizer.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for converting text to phonemes\n/// \npublic interface IPhonemizer : IDisposable\n{\n /// \n /// Converts text to phoneme representation\n /// \n /// Input text\n /// Cancellation token\n /// Phoneme result\n Task ToPhonemesAsync(\n string text,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/VadSegment.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\n/// \n/// Represents a voice activity detection segment.\n/// \npublic class VadSegment\n{\n /// \n /// Gets or sets the start time of the segment.\n /// \n public TimeSpan StartTime { get; set; }\n\n /// \n /// Gets or sets the duration of the segment.\n /// \n public TimeSpan Duration { get; set; }\n\n /// \n /// Gets or sets a value indicating whether this segment is the last one in the audio stream and can be incomplete.\n /// \n public bool IsIncomplete { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/ModelSettingObj.cs", "using System.ComponentModel;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\npublic record ModelSettingObj\n{\n public FileReference FileReferences { get; set; }\n\n public List HitAreas { get; set; }\n\n public Dictionary Layout { get; set; }\n\n public List Groups { get; set; }\n\n public record FileReference\n {\n public string Moc { get; set; }\n\n public List Textures { get; set; }\n\n public string Physics { get; set; }\n\n public string Pose { get; set; }\n\n public string DisplayInfo { get; set; }\n\n public List Expressions { get; set; }\n\n public Dictionary> Motions { get; set; }\n\n public string UserData { get; set; }\n\n public record Expression\n {\n public string Name { get; set; }\n\n public string File { get; set; }\n }\n\n public record Motion\n {\n public string File { get; set; }\n\n public string Sound { get; set; }\n\n [DefaultValue(-1f)] public float FadeInTime { get; set; }\n\n [DefaultValue(-1f)] public float FadeOutTime { get; set; }\n }\n }\n\n public record HitArea\n {\n public string Id { get; set; }\n\n public string Name { get; set; }\n }\n\n public record Parameter\n {\n public string Name { get; set; }\n\n public List Ids { get; set; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/IVadDetector.cs", "using PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\n/// \n/// Represents a voice activity detection component that can detect voice activity segments in mono-channel audio\n/// samples at 16 kHz.\n/// \npublic interface IVadDetector\n{\n /// \n /// Detects voice activity segments in the given audio source.\n /// \n /// The audio source to analyze.\n /// The cancellation token to observe.\n IAsyncEnumerable DetectSegmentsAsync(IAudioSource source, CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionExtensions.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Extension methods for accessing emotion data in audio segments\n/// \npublic static class EmotionExtensions\n{\n /// \n /// Gets the emotions associated with an audio segment\n /// \n public static IReadOnlyList GetEmotions(this AudioSegment segment, IEmotionService emotionService) { return emotionService.GetEmotions(segment.Id); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IMicrophone.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Interface for a microphone audio source.\n/// Extends IAwaitableAudioSource with recording control methods\n/// and device information retrieval.\n/// \npublic interface IMicrophone : IAwaitableAudioSource\n{\n /// \n /// Starts capturing audio from the microphone.\n /// \n void StartRecording();\n\n /// \n /// Stops capturing audio from the microphone.\n /// \n void StopRecording();\n\n /// \n /// Gets a list of available audio input device names.\n /// \n /// An enumerable collection of device names.\n IEnumerable GetAvailableDevices();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/ArrayPoolConfig.cs", "namespace PersonaEngine.Lib.Utils;\n\n/// \n/// Configuration for the ArrayPools used in the library.\n/// \npublic class ArrayPoolConfig\n{\n /// \n /// Determines whether arrays should be cleared before being returned to the pool.\n /// \n /// \n /// Default value is false for performance reasons. If you are working with sensitive data, you may want to set\n /// this to true.\n /// \n public static bool ClearOnReturn { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Strategies/NoSpeakingBargeInStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Strategies;\n\npublic class NoSpeakingBargeInStrategy : IBargeInStrategy\n{\n public bool ShouldAllowBargeIn(BargeInContext context) { return context.CurrentState != ConversationState.Speaking; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeResult.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Result of phoneme conversion\n/// \npublic class PhonemeResult\n{\n public PhonemeResult(string phonemes, IReadOnlyList tokens)\n {\n Phonemes = phonemes;\n Tokens = tokens;\n }\n\n /// \n /// Phoneme string representation\n /// \n public string Phonemes { get; }\n\n /// \n /// Tokens with phonetic information\n /// \n public IReadOnlyList Tokens { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/EyeState.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\npublic enum EyeState\n{\n /// \n /// 初期状態\n /// \n First = 0,\n\n /// \n /// まばたきしていない状態\n /// \n Interval,\n\n /// \n /// まぶたが閉じていく途中の状態\n /// \n Closing,\n\n /// \n /// まぶたが閉じている状態\n /// \n Closed,\n\n /// \n /// まぶたが開いていく途中の状態\n /// \n Opening\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/AudioData.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Result of audio synthesis\n/// \npublic class AudioData\n{\n public AudioData(Memory samples, ReadOnlyMemory phonemeTimings)\n {\n Samples = samples;\n PhonemeTimings = phonemeTimings;\n }\n\n /// \n /// Audio samples\n /// \n public Memory Samples { get; }\n\n /// \n /// Durations for phoneme timing\n /// \n public ReadOnlyMemory PhonemeTimings { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/AudioSegment.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record AudioSegment\n{\n public AudioSegment(Memory audioData, int sampleRate, IReadOnlyList tokens)\n {\n AudioData = audioData;\n SampleRate = sampleRate;\n Channels = 1;\n Tokens = tokens ?? Array.Empty();\n }\n\n public Guid Id { get; init; } = Guid.NewGuid();\n\n public Memory AudioData { get; set; }\n\n public int SampleRate { get; set; }\n\n public float DurationInSeconds => AudioData.Length / (float)SampleRate;\n\n public IReadOnlyList Tokens { get; }\n\n public int Channels { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IAudioSynthesizer.cs", "using PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for audio synthesis from phonemes\n/// \npublic interface IAudioSynthesizer : IAsyncDisposable\n{\n /// \n /// Synthesizes audio from phonemes\n /// \n /// Phoneme string\n /// Voice identifier\n /// Synthesis options\n /// Cancellation token\n /// Audio data with timing information\n Task SynthesizeAsync(\n string phonemes,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeConstants.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Phonetic constants used in pronunciation\n/// \npublic class PhonemeConstants\n{\n public PhonemeConstants(bool useBritishEnglish) { UseBritishEnglish = useBritishEnglish; }\n\n /// \n /// Whether to use British English pronunciation\n /// \n public bool UseBritishEnglish { get; init; }\n\n /// \n /// US-specific tau sounds for flapping rules\n /// \n public HashSet UsTauSounds { get; } = new(\"aeiouAEIOUæɑɒɔəɛɪʊʌᵻ\");\n\n /// \n /// Currency symbols with their word representations\n /// \n public Dictionary CurrencyRepresentations { get; } = new() { { '$', (\"dollar\", \"cent\") }, { '£', (\"pound\", \"pence\") }, { '€', (\"euro\", \"cent\") } };\n\n public Dictionary Symbols { get; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ProcessedText.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Result of text preprocessing\n/// \npublic class ProcessedText\n{\n public ProcessedText(string normalizedText, IReadOnlyList sentences)\n {\n NormalizedText = normalizedText;\n Sentences = sentences;\n }\n\n /// \n /// Normalized text\n /// \n public string NormalizedText { get; }\n\n /// \n /// Segmented sentences\n /// \n public IReadOnlyList Sentences { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/TranscriptSegment.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic class TranscriptSegment\n{\n public IReadOnlyDictionary Metadata { get; init; }\n\n /// \n /// Gets or sets the text of the segment.\n /// \n public string Text { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the start time of the segment.\n /// \n public TimeSpan StartTime { get; set; }\n\n /// \n /// Gets or sets the duration of the segment\n /// \n public TimeSpan Duration { get; set; }\n\n /// \n /// Gets or sets the confidence of the segment\n /// \n public float? ConfidenceLevel { get; set; }\n\n /// \n /// Gets or sets the language of the segment.\n /// \n public CultureInfo? Language { get; set; }\n\n /// \n /// Gets or sets the tokens of the segment.\n /// \n /// \n /// Not all the transcriptors will provide tokens.\n /// \n public IList? Tokens { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IKokoroVoiceProvider.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic interface IKokoroVoiceProvider : IAsyncDisposable\n{\n Task GetVoiceAsync(\n string voiceId,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets all available voice IDs\n /// \n /// List of voice IDs\n Task> GetAvailableVoicesAsync(\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IVBANPacketBuilder.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Builder for VBAN packets.\n/// \npublic interface IVBANPacketBuilder\n{\n /// \n /// Builds a VBAN packet from audio data.\n /// \n byte[] BuildPacket(ReadOnlyMemory audioData, int sampleRate, int samplesPerChannel, int channels);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/ISpeechTranscriptor.cs", "using PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\n/// \n/// Represents a segment of transcribed text.\n/// \npublic interface ISpeechTranscriptor : IAsyncDisposable\n{\n /// \n /// Transcribes the given audio stream to segments of text.\n /// \n /// The audio source to transcribe.\n /// The cancellation token to observe.\n /// \n IAsyncEnumerable TranscribeAsync(IAudioSource source, CancellationToken cancellationToken);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigurationChangedEventArgs.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Event arguments for configuration changes\n/// \npublic class ConfigurationChangedEventArgs : EventArgs\n{\n public enum ChangeType\n {\n Updated,\n\n Reloaded,\n\n Saved\n }\n\n public ConfigurationChangedEventArgs(string sectionKey, ChangeType type)\n {\n SectionKey = sectionKey;\n Type = type;\n }\n\n public string SectionKey { get; }\n\n public ChangeType Type { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Adapters/IOutputAdapter.cs", "using System.Threading.Channels;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\n\npublic interface IOutputAdapter : IAsyncDisposable\n{\n Guid AdapterId { get; }\n\n ValueTask InitializeAsync(Guid sessionId, CancellationToken cancellationToken);\n\n ValueTask StartAsync(CancellationToken cancellationToken);\n\n ValueTask StopAsync(CancellationToken cancellationToken);\n}\n\npublic interface IAudioOutputAdapter : IOutputAdapter\n{\n Task SendAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n CancellationToken cancellationToken = default);\n}\n\npublic interface ITextOutputAdapter : IOutputAdapter\n{\n Task SendAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/IStreamingAudioPlayer.cs", "// using System.Threading.Channels;\n//\n// using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n// using PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n// using PersonaEngine.Lib.TTS.Synthesis;\n//\n// namespace PersonaEngine.Lib.Audio.Player;\n//\n// public class AudioPlaybackEventArgs : EventArgs\n// {\n// public AudioPlaybackEventArgs(AudioSegment segment) { Segment = segment; }\n//\n// public AudioSegment Segment { get; }\n// }\n//\n// public interface IStreamingAudioPlayer : IAsyncDisposable\n// {\n// Task StartPlaybackAsync(IAsyncEnumerable audioSegments, CancellationToken cancellationToken = default);\n//\n// public Task StopPlaybackAsync();\n// }\n//\n// public interface IStreamingAudioPlayerHost\n// {\n// float CurrentTime { get; }\n//\n// PlayerState State { get; }\n//\n// event EventHandler? OnPlaybackStarted;\n//\n// event EventHandler? OnPlaybackCompleted;\n// }\n//\n// public interface IAggregatedStreamingAudioPlayer : IStreamingAudioPlayer\n// {\n// IReadOnlyCollection Players { get; }\n//\n// void AddPlayer(IStreamingAudioPlayer player);\n//\n// bool RemovePlayer(IStreamingAudioPlayer player);\n// }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionTiming.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Represents an emotion with its timestamp in the audio\n/// \npublic record EmotionTiming\n{\n /// \n /// Timestamp in seconds when the emotion occurs\n /// \n public double Timestamp { get; set; }\n \n /// \n /// Emotion emoji\n /// \n public string Emotion { get; set; } = string.Empty;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Strategies/IBargeInStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\npublic record struct BargeInContext(\n ConversationOptions ConversationOptions,\n ConversationState CurrentState,\n IInputEvent InputEvent,\n Guid SessionId,\n Guid? TurnId\n);\n\npublic interface IBargeInStrategy\n{\n bool ShouldAllowBargeIn(BargeInContext context);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/ICubismAllocator.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// メモリアロケーションを抽象化したクラス.\n/// メモリ確保・解放処理をプラットフォーム側で実装して\n/// フレームワークから呼び出すためのインターフェース。\n/// \npublic interface ICubismAllocator\n{\n /// \n /// アラインメント制約なしのヒープ・メモリーを確保します。\n /// \n /// 確保するバイト数\n /// 成功すると割り当てられたメモリのアドレス。 そうでなければ '0'を返す。\n IntPtr Allocate(int size);\n\n /// \n /// アラインメント制約なしのヒープ・メモリーを解放します。\n /// \n /// 解放するメモリのアドレス\n void Deallocate(IntPtr memory);\n\n /// \n /// アラインメント制約ありのヒープ・メモリーを確保します。\n /// \n /// 確保するバイト数\n /// メモリーブロックのアラインメント幅\n /// 成功すると割り当てられたメモリのアドレス。 そうでなければ '0'を返す。\n IntPtr AllocateAligned(int size, int alignment);\n\n /// \n /// アラインメント制約ありのヒープ・メモリーを解放します。\n /// \n /// 解放するメモリのアドレス\n void DeallocateAligned(IntPtr alignedMemory);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/TtsConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record TtsConfiguration\n{\n public string ModelDirectory { get; init; } = Path.Combine(Directory.GetCurrentDirectory(), \"Resources\", \"Models\");\n\n public string EspeakPath { get; init; } = \"espeak-ng\";\n\n public KokoroVoiceOptions Voice { get; init; } = new();\n\n public RVCFilterOptions Rvc { get; init; } = new();\n}\n\npublic record KokoroVoiceOptions\n{\n public string DefaultVoice { get; init; } = \"af_heart\";\n\n public bool UseBritishEnglish { get; init; } = false;\n\n public float DefaultSpeed { get; init; } = 1.0f;\n\n public int MaxPhonemeLength { get; init; } = 510;\n\n public int SampleRate { get; init; } = 24000;\n\n public bool TrimSilence { get; init; } = false;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/BenchmarkResult.cs", "namespace PersonaEngine.Lib.TTS.Profanity;\n\n/// \n/// Holds benchmark statistics for a profanity detection run.\n/// \npublic record BenchmarkResult\n{\n public int Total { get; set; }\n\n public int TruePositives { get; set; }\n\n public int FalsePositives { get; set; }\n\n public int TrueNegatives { get; set; }\n\n public int FalseNegatives { get; set; }\n\n public double Accuracy { get; set; }\n\n public double Precision { get; set; }\n\n public double Recall { get; set; }\n\n public override string ToString()\n {\n return $\"Total: {Total}, TP: {TruePositives}, FP: {FalsePositives}, TN: {TrueNegatives}, FN: {FalseNegatives}, \" +\n $\"Accuracy: {Accuracy:P2}, Precision: {Precision:P2}, Recall: {Recall:P2}\";\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/INotificationService.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Provides notification services for the UI\n/// \npublic interface INotificationService\n{\n void ShowInfo(string message, Action? action = null, string actionLabel = \"OK\");\n\n void ShowSuccess(string message, Action? action = null, string actionLabel = \"OK\");\n\n void ShowWarning(string message, Action? action = null, string actionLabel = \"OK\");\n\n void ShowError(string message, Action? action = null, string actionLabel = \"OK\");\n\n IReadOnlyList GetActiveNotifications();\n\n void Update(float deltaTime);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionObj.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\npublic record CubismMotionObj\n{\n public MetaObj Meta { get; set; }\n\n public List Curves { get; set; }\n\n public List UserData { get; set; }\n\n public record MetaObj\n {\n public float Duration { get; set; }\n\n public bool Loop { get; set; }\n\n public bool AreBeziersRestricted { get; set; }\n\n public int CurveCount { get; set; }\n\n public float Fps { get; set; }\n\n public int TotalSegmentCount { get; set; }\n\n public int TotalPointCount { get; set; }\n\n public float? FadeInTime { get; set; }\n\n public float? FadeOutTime { get; set; }\n\n public int UserDataCount { get; set; }\n\n public int TotalUserDataSize { get; set; }\n }\n\n public record Curve\n {\n public float? FadeInTime { get; set; }\n\n public float? FadeOutTime { get; set; }\n\n public List Segments { get; set; }\n\n public string Target { get; set; }\n\n public string Id { get; set; }\n }\n\n public record UserDataObj\n {\n public float Time { get; set; }\n\n public string Value { get; set; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionMarker.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Stores emotion data extracted from text with its position information\n/// \npublic record EmotionMarker\n{\n /// \n /// Character position in the cleaned text\n /// \n public int Position { get; set; }\n\n /// \n /// Emotion emoji\n /// \n public string Emotion { get; set; } = string.Empty;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/WhisperNetSupportedLanguage.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic static class WhisperNetSupportedLanguage\n{\n private static readonly HashSet supportedLanguages = [\n \"en\", \"zh\", \"de\", \"es\", \"ru\", \"ko\", \"fr\", \"ja\", \"pt\", \"tr\", \"pl\", \"ca\", \"nl\",\n \"ar\", \"sv\", \"it\", \"id\", \"hi\", \"fi\", \"vi\", \"he\", \"uk\", \"el\", \"ms\", \"cs\", \"ro\",\n \"da\", \"hu\", \"ta\", \"no\", \"th\", \"ur\", \"hr\", \"bg\", \"lt\", \"la\", \"mi\", \"ml\", \"cy\",\n \"sk\", \"te\", \"fa\", \"lv\", \"bn\", \"sr\", \"az\", \"sl\", \"kn\", \"et\", \"mk\", \"br\", \"eu\",\n \"is\", \"hy\", \"ne\", \"mn\", \"bs\", \"kk\", \"sq\", \"sw\", \"gl\", \"mr\", \"pa\", \"si\", \"km\",\n \"sn\", \"yo\", \"so\", \"af\", \"oc\", \"ka\", \"be\", \"tg\", \"sd\", \"gu\", \"am\", \"yi\", \"lo\",\n \"uz\", \"fo\", \"ht\", \"ps\", \"tk\", \"nn\", \"mt\", \"sa\", \"lb\", \"my\", \"bo\", \"tl\", \"mg\",\n \"as\", \"tt\", \"haw\", \"ln\", \"ha\", \"ba\", \"jw\", \"su\", \"yue\"\n ];\n\n public static bool IsSupported(CultureInfo cultureInfo) { return supportedLanguages.Contains(cultureInfo.TwoLetterISOLanguageName); }\n\n public static IEnumerable GetSupportedLanguages() { return supportedLanguages.Select(x => new CultureInfo(x)); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/IChatEngine.cs", "using System.Threading.Channels;\n\nusing Microsoft.SemanticKernel;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic record VisualChatMessage(string Query, ReadOnlyMemory ImageData);\n\npublic interface IChatEngine : IDisposable\n{\n Task GetStreamingChatResponseAsync(\n IConversationContext context,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n PromptExecutionSettings? executionSettings = null,\n CancellationToken cancellationToken = default);\n}\n\npublic interface IVisualChatEngine : IDisposable\n{\n IAsyncEnumerable GetStreamingChatResponseAsync(\n VisualChatMessage userInput,\n PromptExecutionSettings? executionSettings = null,\n CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/IEmotionService.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Service that tracks emotion timings for audio segments\n/// \npublic interface IEmotionService\n{\n /// \n /// Associates emotion timings with an audio segment\n /// \n void RegisterEmotions(Guid segmentId, IReadOnlyList emotions);\n\n /// \n /// Retrieves emotion timings for an audio segment\n /// \n IReadOnlyList GetEmotions(Guid segmentId);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioSourceHeader.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// Details of the audio source header.\n/// \npublic class AudioSourceHeader\n{\n /// \n /// Gets the number of channels in the current wave file.\n /// \n public ushort Channels { get; set; }\n\n /// \n /// Gets the Sample Rate in the current wave file.\n /// \n public uint SampleRate { get; set; }\n\n /// \n /// Gets the Bits Per Sample in the current wave file.\n /// \n public ushort BitsPerSample { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Option.cs", "using PersonaEngine.Lib.Live2D.Framework.Core;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// ログ出力のレベル\n/// \npublic enum LogLevel\n{\n /// \n /// 詳細ログ\n /// \n Verbose = 0,\n\n /// \n /// デバッグログ\n /// \n Debug,\n\n /// \n /// Infoログ\n /// \n Info,\n\n /// \n /// 警告ログ\n /// \n Warning,\n\n /// \n /// エラーログ\n /// \n Error,\n\n /// \n /// ログ出力無効\n /// \n Off\n}\n\n/// \n/// CubismFrameworkに設定するオプション要素を定義するクラス\n/// \npublic class Option\n{\n /// \n /// ログ出力の関数ポイ\n /// \n public required LogFunction LogFunction;\n\n /// \n /// ログ出力レベル設定\n /// \n public LogLevel LoggingLevel;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadOptions.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\npublic class SileroVadOptions(string modelPath)\n{\n public string ModelPath { get; set; } = modelPath;\n\n public float ThresholdGap { get; set; } = 0.15f;\n\n public float Threshold { get; set; } = 0.5f;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IEditorStateManager.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages the state of the configuration editor UI\n/// \npublic interface IEditorStateManager\n{\n bool HasUnsavedChanges { get; }\n\n event EventHandler StateChanged;\n\n void MarkAsChanged(string? sectionKey = null);\n\n void MarkAsSaved();\n\n ActiveOperation? GetActiveOperation();\n\n void RegisterActiveOperation(ActiveOperation operation);\n\n void ClearActiveOperation(string operationId);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITtsEngine.cs", "using System.Threading.Channels;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic interface ITtsEngine : IDisposable\n{\n Task SynthesizeStreamingAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default\n );\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismBlendMode.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// カラーブレンディングのモード\n/// \npublic enum CubismBlendMode\n{\n /// \n /// 通常\n /// \n Normal = 0,\n\n /// \n /// 加算\n /// \n Additive = 1,\n\n /// \n /// 乗算\n /// \n Multiplicative = 2,\n\n /// \n /// マスク\n /// \n Mask = 3\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/ISpeechTranscriptorFactory.cs", "namespace PersonaEngine.Lib.ASR.Transcriber;\n\n/// \n/// Factory for creating instances of .\n/// \npublic interface ISpeechTranscriptorFactory : IDisposable\n{\n /// \n /// Creates a new instance of .\n /// \n /// \n ISpeechTranscriptor Create(SpeechTranscriptorOptions options);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsJson.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// physics3.jsonのコンテナ。\n/// \npublic record CubismPhysicsJson\n{\n public const string Position = \"Position\";\n\n public const string X = \"X\";\n\n public const string Y = \"Y\";\n\n public const string Angle = \"Angle\";\n\n public const string Type = \"Type\";\n\n public const string Id = \"Id\";\n\n // Meta\n public const string Meta = \"Meta\";\n\n public const string EffectiveForces = \"EffectiveForces\";\n\n public const string TotalInputCount = \"TotalInputCount\";\n\n public const string TotalOutputCount = \"TotalOutputCount\";\n\n public const string PhysicsSettingCount = \"PhysicsSettingCount\";\n\n public const string Gravity = \"Gravity\";\n\n public const string Wind = \"Wind\";\n\n public const string VertexCount = \"VertexCount\";\n\n public const string Fps = \"Fps\";\n\n // PhysicsSettings\n public const string PhysicsSettings = \"PhysicsSettings\";\n\n public const string Normalization = \"Normalization\";\n\n public const string Minimum = \"Minimum\";\n\n public const string Maximum = \"Maximum\";\n\n public const string Default = \"Default\";\n\n public const string Reflect = \"Reflect\";\n\n public const string Weight = \"Weight\";\n\n // Input\n public const string Input = \"Input\";\n\n public const string Source = \"Source\";\n\n // Output\n public const string Output = \"Output\";\n\n public const string Scale = \"Scale\";\n\n public const string VertexIndex = \"VertexIndex\";\n\n public const string Destination = \"Destination\";\n\n // Particle\n public const string Vertices = \"Vertices\";\n\n public const string Mobility = \"Mobility\";\n\n public const string Delay = \"Delay\";\n\n public const string Radius = \"Radius\";\n\n public const string Acceleration = \"Acceleration\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/ILive2DModel.cs", "namespace PersonaEngine.Lib.Live2D;\n\npublic interface ILive2DModel : IDisposable\n{\n string ModelId { get; }\n\n void SetParameter(string paramName, float value);\n\n void Update(float deltaTime);\n\n void Draw();\n\n void SetPosition(float x, float y);\n\n void SetScale(float scale);\n\n void SetRotation(float rotation);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/VertexPositionTexture.cs", "using System.Numerics;\nusing System.Runtime.InteropServices;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\n[StructLayout(LayoutKind.Sequential, Pack = 1)]\npublic readonly struct VertexPositionTexture\n{\n public readonly Vector3 Position;\n\n public readonly Vector2 TextureCoordinate;\n\n public VertexPositionTexture(Vector3 position, Vector2 textureCoordinate)\n {\n Position = position;\n TextureCoordinate = textureCoordinate;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/JsonContext.cs", "using System.Text.Json.Serialization;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Physics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n[JsonSourceGenerationOptions(WriteIndented = true)]\n[JsonSerializable(typeof(ModelSettingObj))]\npublic partial class ModelSettingObjContext : JsonSerializerContext { }\n\n[JsonSerializable(typeof(CubismMotionObj))]\npublic partial class CubismMotionObjContext : JsonSerializerContext { }\n\n[JsonSerializable(typeof(CubismModelUserDataObj))]\npublic partial class CubismModelUserDataObjContext : JsonSerializerContext { }\n\n[JsonSerializable(typeof(CubismPhysicsObj))]\npublic partial class CubismPhysicsObjContext : JsonSerializerContext { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Strategies/IgnoreBargeInStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Strategies;\n\npublic class IgnoreBargeInStrategy : IBargeInStrategy\n{\n public bool ShouldAllowBargeIn(BargeInContext context) { return false; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/VisionConfig.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record VisionConfig\n{\n public string WindowTitle { get; init; } = \"Paint\";\n\n public bool Enabled { get; init; } = false;\n\n public TimeSpan CaptureInterval { get; init; } = TimeSpan.FromSeconds(45);\n\n public int CaptureMinPixels { get; init; } = 224 * 224;\n\n public int CaptureMaxPixels { get; init; } = 2048 * 2048;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PosToken.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Token with part-of-speech information\n/// \npublic class PosToken\n{\n /// \n /// The text of the token\n /// \n public string Text { get; set; } = string.Empty;\n\n /// \n /// Part of speech tag\n /// \n public string? PartOfSpeech { get; set; }\n\n /// \n /// Whitespace after this token\n /// \n public bool IsWhitespace { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserDataObj.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Model;\n\npublic record CubismModelUserDataObj\n{\n public MetaObj Meta { get; set; }\n\n public List UserData { get; set; }\n\n public record MetaObj\n {\n public int UserDataCount { get; set; }\n\n public int TotalUserDataSize { get; set; }\n }\n\n public record UserDataObj\n {\n public string Target { get; set; }\n\n public string Id { get; set; }\n\n public string Value { get; set; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/TextureInfo.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 画像情報構造体\n/// \npublic record TextureInfo\n{\n /// \n /// ファイル名\n /// \n public required string FileName;\n\n /// \n /// 高さ\n /// \n public int Height;\n\n /// \n /// テクスチャID\n /// \n public int ID;\n\n /// \n /// 横幅\n /// \n public int Width;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppPal.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// プラットフォーム依存機能を抽象化する Cubism Platform Abstraction Layer.\n/// ファイル読み込みや時刻取得等のプラットフォームに依存する関数をまとめる\n/// \npublic static class LAppPal\n{\n /// \n /// デルタ時間(前回フレームとの差分)を取得する\n /// \n /// デルタ時間[ms]\n public static float DeltaTime { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITextProcessor.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for text preprocessing\n/// \npublic interface ITextProcessor\n{\n /// \n /// Processes raw text for TTS synthesis\n /// \n /// Input text\n /// Cancellation token\n /// Processed text with sentences\n Task ProcessAsync(string text, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserDataNode.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// Jsonから読み込んだユーザデータを記録しておくための構造体\n/// \npublic record CubismModelUserDataNode\n{\n /// \n /// ユーザデータターゲットタイプ\n /// \n public required string TargetType { get; set; }\n\n /// \n /// ユーザデータターゲットのID\n /// \n public required string TargetId { get; set; }\n\n /// \n /// ユーザデータ\n /// \n public required string Value { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IFallbackPhonemizer.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for fallback phoneme generation\n/// \npublic interface IFallbackPhonemizer : IAsyncDisposable\n{\n /// \n /// Gets phonemes for a word when the lexicon fails\n /// \n Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(string word, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismShaderSet.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal record CubismShaderSet\n{\n /// \n /// シェーダプログラムに渡す変数のアドレス(Position)\n /// \n internal int AttributePositionLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(TexCoord)\n /// \n internal int AttributeTexCoordLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(Texture0)\n /// \n internal int SamplerTexture0Location;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(Texture1)\n /// \n internal int SamplerTexture1Location;\n\n /// \n /// シェーダプログラムのアドレス\n /// \n internal int ShaderProgram;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(BaseColor)\n /// \n internal int UniformBaseColorLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(ClipMatrix)\n /// \n internal int UniformClipMatrixLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(Matrix)\n /// \n internal int UniformMatrixLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(MultiplyColor)\n /// \n internal int UniformMultiplyColorLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(ScreenColor)\n /// \n internal int UniformScreenColorLocation;\n\n /// \n /// シェーダプログラムに渡す変数のアドレス(ChannelFlag)\n /// \n internal int UnifromChannelFlagLocation;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/Live2DOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic class Live2DOptions\n{\n public string ModelPath { get; set; } = \"Resources/Live2D/Avatars\";\n\n public string ModelName { get; set; } = \"angel\";\n\n public int Width { get; set; } = 1920;\n\n public int Height { get; set; } = 1080;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IUiConfigurationManager.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages configuration loading, saving, and access\n/// \npublic interface IUiConfigurationManager\n{\n event EventHandler ConfigurationChanged;\n\n T GetConfiguration(string sectionKey = null);\n\n void UpdateConfiguration(T configuration, string? sectionKey = null);\n\n void SaveConfiguration();\n\n void ReloadConfiguration();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/BreathParameterData.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 呼吸のパラメータ情報。\n/// \npublic record BreathParameterData\n{\n /// \n /// 呼吸をひもづけるパラメータIDs\n /// \n public required string ParameterId { get; set; }\n\n /// \n /// 呼吸を正弦波としたときの、波のオフセット\n /// \n public float Offset { get; set; }\n\n /// \n /// 呼吸を正弦波としたときの、波の高さ\n /// \n public float Peak { get; set; }\n\n /// \n /// 呼吸を正弦波としたときの、波の周期\n /// \n public float Cycle { get; set; }\n\n /// \n /// パラメータへの重み\n /// \n public float Weight { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/IConversationContext.cs", "using Microsoft.SemanticKernel.ChatCompletion;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic interface IConversationContext : IDisposable\n{\n IReadOnlyDictionary Participants { get; }\n\n IReadOnlyList History { get; }\n\n string? CurrentVisualContext { get; }\n\n InteractionTurn? PendingTurn { get; }\n\n bool TryAddParticipant(ParticipantInfo participant);\n\n bool TryRemoveParticipant(string participantId);\n\n void StartTurn(Guid turnId, IEnumerable participantIds);\n\n void AppendToTurn(string participantId, string chunk);\n\n string GetPendingMessageText(string participantId);\n\n void CompleteTurnPart(string participantId, bool interrupted = false);\n\n IReadOnlyList GetProjectedHistory();\n\n public void AbortTurn();\n\n ChatHistory GetSemanticKernelChatHistory(bool includePendingTurn = true);\n\n bool TryUpdateMessage(Guid turnId, Guid messageId, string newText);\n\n bool TryDeleteMessage(Guid turnId, Guid messageId);\n\n void ApplyCleanupStrategy();\n\n void ClearHistory();\n\n event EventHandler? ConversationUpdated;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/WindowConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic class WindowConfiguration\n{\n public int Width { get; set; } = 1920;\n\n public int Height { get; set; } = 1080;\n\n public string Title { get; set; } = \"Avatar Application\";\n\n public bool Fullscreen { get; set; } = false;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/IWordAnimator.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Interface for defining word animation strategies (scale, color).\n/// \npublic interface IWordAnimator\n{\n Vector2 CalculateScale(float progress);\n\n FSColor CalculateColor(FSColor startColor, FSColor endColor, float progress);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Logging/ResilienceKeys.cs", "using Microsoft.Extensions.Logging;\n\nusing Polly;\n\nnamespace PersonaEngine.Lib.Logging;\n\npublic static class ResilienceKeys\n{\n public static readonly ResiliencePropertyKey SessionId = new(\"session-id\");\n \n public static readonly ResiliencePropertyKey Logger = new(\"logger\");\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/AvatarAppConfig.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\nnamespace PersonaEngine.Lib.Configuration;\n\npublic record AvatarAppConfig\n{\n public WindowConfiguration Window { get; set; } = new();\n\n public LlmOptions Llm { get; set; } = new();\n\n public TtsConfiguration Tts { get; set; } = new();\n\n public AsrConfiguration Asr { get; set; } = new();\n\n public MicrophoneConfiguration Microphone { get; set; } = new();\n\n public SubtitleOptions Subtitle { get; set; } = new();\n\n public Live2DOptions Live2D { get; set; } = new();\n\n public SpoutConfiguration[] SpoutConfigs { get; set; } = [];\n\n public VisionConfig Vision { get; set; } = new();\n\n public RouletteWheelOptions RouletteWheel { get; set; } = new();\n\n public ConversationOptions Conversation { get; set; } = new();\n \n // This would need to be seperate per configured conversation session\n public ConversationContextOptions ConversationContext { get; set; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanitySeverity.cs", "namespace PersonaEngine.Lib.TTS.Profanity;\n\n/// \n/// Represents the severity level of profanity.\n/// \npublic enum ProfanitySeverity\n{\n Clean, // No profanity detected.\n\n Mild, // Some profanity detected.\n\n Moderate, // Moderate profanity detected.\n\n Severe // High level of profanity detected.\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/RVCFilterOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record RVCFilterOptions\n{\n public string DefaultVoice { get; init; } = \"KasumiVA\";\n\n public bool Enabled { get; set; } = true;\n\n public int HopSize { get; set; } = 64;\n\n public int SpeakerId { get; set; } = 0;\n\n public int F0UpKey { get; set; } = 0;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IPosTagger.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for part-of-speech tagging\n/// \npublic interface IPosTagger : IDisposable\n{\n /// \n /// Tags parts of speech in text\n /// \n Task> TagAsync(string text, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ITextNormalizer.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for text normalization\n/// \npublic interface ITextNormalizer\n{\n /// \n /// Normalizes text for TTS synthesis\n /// \n /// Input text\n /// Normalized text\n string Normalize(string text);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ISentenceSegmenter.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for sentence segmentation\n/// \npublic interface ISentenceSegmenter\n{\n /// \n /// Splits text into sentences\n /// \n /// Input text\n /// List of sentences\n IReadOnlyList Segment(string text);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroConstants.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroConstants\n{\n public const int BatchSize = 512;\n\n public const int ContextSize = 64;\n\n public const int StateSize = 256;\n\n public const int OutputSize = 1;\n\n public const int SampleRate = 16000;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IConfigSectionEditor.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Interface for configuration section editors\n/// \npublic interface IConfigSectionEditor\n{\n string SectionKey { get; }\n\n string DisplayName { get; }\n\n bool HasUnsavedChanges { get; }\n\n void Initialize();\n\n void Render();\n\n void RenderMenuItems();\n\n void Update(float deltaTime);\n\n void OnConfigurationChanged(ConfigurationChangedEventArgs args);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IRealtimeRecognitionEvent.cs", "using PersonaEngine.Lib.ASR.Transcriber;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic interface IRealtimeRecognitionEvent { }\n\npublic interface IRealtimeTranscriptionSegment : IRealtimeRecognitionEvent\n{\n public TranscriptSegment Segment { get; }\n}\n\npublic class RealtimeSessionStarted(string sessionId) : IRealtimeRecognitionEvent\n{\n public string SessionId { get; } = sessionId;\n}\n\npublic class RealtimeSessionStopped(string sessionId) : IRealtimeRecognitionEvent\n{\n public object SessionId { get; } = sessionId;\n}\n\npublic class RealtimeSessionCanceled(string sessionId) : IRealtimeRecognitionEvent\n{\n public object SessionId { get; } = sessionId;\n}\n\n\npublic class RealtimeSegmentRecognizing(TranscriptSegment segment, string sessionId) : IRealtimeTranscriptionSegment\n{\n public TranscriptSegment Segment { get; } = segment;\n\n public string SessionId { get; } = sessionId;\n}\n\npublic class RealtimeSegmentRecognized(TranscriptSegment segment, string sessionId) : IRealtimeTranscriptionSegment\n{\n public TranscriptSegment Segment { get; } = segment;\n\n public string SessionId { get; } = sessionId;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/PartColorData.cs", "using PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// テクスチャの色をRGBAで扱うための構造体\n/// \npublic record PartColorData\n{\n public CubismTextureColor Color = new();\n\n public bool IsOverwritten { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/DrawableColorData.cs", "using PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// テクスチャの色をRGBAで扱うための構造体\n/// \npublic record DrawableColorData\n{\n public CubismTextureColor Color = new();\n\n public bool IsOverwritten { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/ConversationState.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic enum ConversationState\n{\n Initial,\n \n Initializing,\n\n Idle,\n\n Listening,\n\n ActiveTurn,\n \n ProcessingInput,\n\n WaitingForLlm,\n\n StreamingResponse,\n \n Speaking,\n\n Paused,\n\n Interrupted,\n\n Error,\n\n Ended\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismCdiJson.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic class CubismCdiJson\n{\n public const string Version = \"Version\";\n\n public const string Parameters = \"Parameters\";\n\n public const string ParameterGroups = \"ParameterGroups\";\n\n public const string Parts = \"Parts\";\n\n public const string Id = \"Id\";\n\n public const string GroupId = \"GroupId\";\n\n public const string Name = \"Name\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IMlSentenceDetector.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for ML-based sentence detection\n/// \npublic interface IMlSentenceDetector : IDisposable\n{\n /// \n /// Detects sentences in text\n /// \n IReadOnlyList Detect(string text);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ModelType.cs", "using System.ComponentModel;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Types of models\n/// \npublic enum ModelType\n{\n [Description(\"kokoro/model_slim.onnx\")]\n KokoroSynthesis,\n\n [Description(\"kokoro/voices\")] KokoroVoices,\n\n [Description(\"kokoro/phoneme_to_id.txt\")]\n KokoroPhonemeMappings,\n\n [Description(\"opennlp\")] OpenNLPDir,\n\n [Description(\"rvc/voices\")] RVCVoices,\n\n [Description(\"rvc/vec-768-layer-12.onnx\")]\n RVCHubert,\n\n [Description(\"rvc/crepe_tiny.onnx\")] RVCCrepeTiny\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IConfigSectionRegistry.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages registration and access to configuration sections\n/// \npublic interface IConfigSectionRegistry\n{\n void RegisterSection(IConfigSectionEditor section);\n\n void UnregisterSection(string sectionKey);\n\n IConfigSectionEditor GetSection(string sectionKey);\n\n IReadOnlyList GetSections();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/ILexicon.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Interface for phoneme lexicon lookup\n/// \npublic interface ILexicon\n{\n public (string? Phonemes, int? Rating) ProcessToken(Token token, TokenContext ctx);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/SDKInfo.cs", "namespace PersonaEngine.Lib.Live2D.Framework;\n\npublic static class SDKInfo\n{\n public const string Version = \"Cubism 5 SDK for Native R1\";\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ConfigurationSaveException.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Exception thrown when saving configuration fails\n/// \npublic class ConfigurationSaveException : Exception\n{\n public ConfigurationSaveException(string message) : base(message) { }\n\n public ConfigurationSaveException(string message, Exception innerException) : base(message, innerException) { }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/SpeechTranscriptorOptions.cs", "using System.Globalization;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic record SpeechTranscriptorOptions\n{\n public bool LanguageAutoDetect { get; set; } = true;\n\n public bool RetrieveTokenDetails { get; set; }\n\n public CultureInfo Language { get; set; } = CultureInfo.GetCultureInfo(\"en-us\");\n\n public string? Prompt { get; set; }\n \n public WhisperConfigTemplate? Template { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/DrawableCullingData.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// テクスチャのカリング設定を管理するための構造体\n/// \npublic record DrawableCullingData\n{\n public bool IsOverwritten { get; set; }\n\n public bool IsCulling { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/IUiThemeManager.cs", "namespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Manages UI theme settings\n/// \npublic interface IUiThemeManager\n{\n void ApplyTheme();\n\n void SetTheme(UiTheme theme);\n\n UiTheme GetCurrentTheme();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Vision/IVisualQAService.cs", "namespace PersonaEngine.Lib.Vision;\n\npublic interface IVisualQAService : IAsyncDisposable\n{\n string? ScreenCaption { get; }\n\n Task StartAsync(CancellationToken cancellationToken = default);\n\n Task StopAsync();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Input/SttEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Input;\n\npublic record SttSegmentRecognizing(\n Guid SessionId,\n DateTimeOffset Timestamp,\n string ParticipantId,\n string PartialTranscript,\n TimeSpan Duration\n) : IInputEvent\n{\n public Guid? TurnId { get; } = null;\n}\n\npublic record SttSegmentRecognized(\n Guid SessionId,\n DateTimeOffset Timestamp,\n string ParticipantId,\n string FinalTranscript,\n TimeSpan Duration,\n float? Confidence\n) : IInputEvent\n{\n public Guid? TurnId { get; } = null;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/PlayerState.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\npublic enum PlayerState\n{\n Uninitialized,\n\n Initialized,\n\n Starting,\n\n Playing,\n\n Stopping,\n\n Stopped,\n\n Error\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismClippingContext_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic unsafe class CubismClippingContext_OpenGLES2(\n CubismClippingManager manager,\n CubismModel model,\n int* clippingDrawableIndices,\n int clipCount) : CubismClippingContext(manager, clippingDrawableIndices, clipCount) { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/ChatMessage.cs", "using OpenAI.Chat;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic class ChatMessage(Guid messageId, string participantId, string participantName, string text, DateTimeOffset timestamp, bool isPartial, ChatMessageRole role)\n{\n public Guid MessageId { get; } = messageId;\n\n public string ParticipantId { get; } = participantId;\n\n public string ParticipantName { get; } = participantName;\n\n public string Text { get; internal set; } = text;\n\n public DateTimeOffset Timestamp { get; } = timestamp;\n\n public bool IsPartial { get; internal set; } = isPartial;\n\n public ChatMessageRole Role { get; } = role;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/AudioEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic interface IAudioProgressEvent : IOutputEvent { }\n\npublic record AudioPlaybackEndedEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, CompletionReason FinishReason) : IOutputEvent { }\n\npublic record AudioPlaybackStartedEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent { }\n\npublic record AudioChunkPlaybackStartedEvent(\n Guid SessionId,\n Guid? TurnId,\n DateTimeOffset Timestamp,\n AudioSegment Chunk\n) : BaseOutputEvent(SessionId, TurnId, Timestamp), IAudioProgressEvent;\n\npublic record AudioChunkPlaybackEndedEvent(\n Guid SessionId,\n Guid? TurnId,\n DateTimeOffset Timestamp,\n AudioSegment Chunk\n) : BaseOutputEvent(SessionId, TurnId, Timestamp), IAudioProgressEvent;\n\npublic record AudioPlaybackProgressEvent(\n Guid SessionId,\n Guid? TurnId,\n DateTimeOffset Timestamp,\n TimeSpan CurrentPlaybackTime\n) : BaseOutputEvent(SessionId, TurnId, Timestamp), IAudioProgressEvent;"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Adapters/IInputAdapter.cs", "using System.Threading.Channels;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\n\npublic interface IInputAdapter : IAsyncDisposable\n{\n Guid AdapterId { get; }\n \n ParticipantInfo Participant { get; }\n\n ValueTask InitializeAsync(Guid sessionId, ChannelWriter inputWriter, CancellationToken cancellationToken);\n\n ValueTask StartAsync(CancellationToken cancellationToken);\n\n ValueTask StopAsync(CancellationToken cancellationToken);\n}\n\npublic interface IAudioInputAdapter : IInputAdapter\n{\n IAwaitableAudioSource GetAudioSource();\n}\n\npublic interface ITextInputAdapter : IInputAdapter { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionMarkerInfo.cs", "namespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\ninternal record EmotionMarkerInfo\n{\n public required string MarkerId { get; init; }\n\n public required string Emotion { get; init; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/VadDetectorOptions.cs", "namespace PersonaEngine.Lib.ASR.VAD;\n\npublic class VadDetectorOptions\n{\n public TimeSpan MinSpeechDuration { get; set; } = TimeSpan.FromMilliseconds(150);\n\n public TimeSpan MinSilenceDuration { get; set; } = TimeSpan.FromMilliseconds(150);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/IConversationSessionFactory.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Context;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic interface IConversationSessionFactory\n{\n IConversationSession CreateSession(ConversationContext context, ConversationOptions? options = null, Guid? sessionId = null);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/LLM/ITextFilter.cs", "using PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.LLM;\n\npublic interface ITextFilter\n{\n int Priority { get; }\n\n ValueTask ProcessAsync(string text, CancellationToken cancellationToken = default);\n\n ValueTask PostProcessAsync(TextFilterResult textFilterResult, AudioSegment segment, CancellationToken cancellationToken = default);\n}\n\npublic record TextFilterResult\n{\n public string ProcessedText { get; set; } = string.Empty;\n\n public Dictionary Metadata { get; set; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/IConversationOrchestrator.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic interface IConversationOrchestrator : IAsyncDisposable\n{\n IConversationSession GetSession(Guid sessionId);\n \n Task StartNewSessionAsync(CancellationToken cancellationToken = default);\n\n ValueTask StopSessionAsync(Guid sessionId);\n\n IEnumerable GetActiveSessionIds();\n\n ValueTask StopAllSessionsAsync();\n \n event EventHandler? SessionsUpdated;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/LlmOptions.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record LlmOptions\n{\n public string TextApiKey { get; set; } = string.Empty;\n\n public string VisionApiKey { get; set; } = string.Empty;\n\n public string TextModel { get; set; } = string.Empty;\n\n public string VisionModel { get; set; } = string.Empty;\n\n public string TextEndpoint { get; set; } = string.Empty;\n\n public string VisionEndpoint { get; set; } = string.Empty;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/AudioException.cs", "namespace PersonaEngine.Lib.Audio.Player;\n\npublic class AudioException(string message, Exception? innerException = null) : Exception(message, innerException);\n\npublic class AudioDeviceNotFoundException(string message) : Exception(message);\n\npublic class AudioPlayerInitializationException(string message, Exception? innerException = null) : Exception(message, innerException);"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Configuration/ConversationOptions.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\npublic record ConversationOptions\n{\n public BargeInType BargeInType { get; set; } = BargeInType.MinWords;\n\n public int BargeInMinWords { get; set; } = 2;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Configuration/ConversationContextOptions.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\npublic record ConversationContextOptions\n{\n public string? SystemPromptFile { get; set; }\n\n public string? SystemPrompt { get; set; }\n\n public string? CurrentContext { get; set; }\n\n public List Topics { get; set; } = new();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/LlmEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic record LlmStreamStartEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent { }\n\npublic record LlmChunkEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, string Chunk) : IOutputEvent { }\n\npublic record LlmStreamEndEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, CompletionReason FinishReason) : IOutputEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/TtsEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic record TtsStreamStartEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent { }\n\npublic record TtsChunkEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, AudioSegment Chunk) : IOutputEvent { }\n\npublic record TtsStreamEndEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, CompletionReason FinishReason) : IOutputEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/IF0Predictor.cs", "namespace PersonaEngine.Lib.TTS.RVC;\n\npublic interface IF0Predictor : IDisposable\n{\n void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemeContext.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemeContext\n{\n public bool UseBritishEnglish { get; set; }\n\n public bool? NextStartsWithVowel { get; set; }\n\n public bool HasToToken { get; set; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/IRealtimeSpeechTranscriptor.cs", "using PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\npublic interface IRealtimeSpeechTranscriptor\n{\n IAsyncEnumerable TranscribeAsync(IAwaitableAudioSource source, CancellationToken cancellationToken = default);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/ShaderNames.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic enum ShaderNames\n{\n // SetupMask\n SetupMask,\n\n //Normal\n Normal,\n\n NormalMasked,\n\n NormalMaskedInverted,\n\n NormalPremultipliedAlpha,\n\n NormalMaskedPremultipliedAlpha,\n\n NormalMaskedInvertedPremultipliedAlpha,\n\n //Add\n Add,\n\n AddMasked,\n\n AddMaskedInverted,\n\n AddPremultipliedAlpha,\n\n AddMaskedPremultipliedAlpha,\n\n AddMaskedPremultipliedAlphaInverted,\n\n //Mult\n Mult,\n\n MultMasked,\n\n MultMaskedInverted,\n\n MultPremultipliedAlpha,\n\n MultMaskedPremultipliedAlpha,\n\n MultMaskedPremultipliedAlphaInverted\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Adapters/IAudioProgressNotifier.cs", "using PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\n\npublic interface IAudioProgressNotifier\n{\n event EventHandler? ChunkPlaybackStarted;\n\n event EventHandler? ChunkPlaybackEnded;\n\n event EventHandler? PlaybackProgress;\n\n void RaiseChunkStarted(object? sender, AudioChunkPlaybackStartedEvent args);\n\n void RaiseChunkEnded(object? sender, AudioChunkPlaybackEndedEvent args);\n\n void RaiseProgress(object? sender, AudioPlaybackProgressEvent args);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/SimplePhonemeEntry.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic record SimplePhonemeEntry(string Phoneme) : PhonemeEntry;"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/ConversationTrigger.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic enum ConversationTrigger\n{\n InitializeRequested,\n \n InitializeComplete,\n \n StopRequested,\n \n PauseRequested,\n \n ResumeRequested,\n \n InputDetected,\n \n InputFinalized,\n \n LlmRequestSent,\n \n LlmStreamStarted,\n \n LlmStreamChunkReceived,\n \n LlmStreamEnded,\n \n TtsRequestSent,\n \n TtsStreamStarted,\n \n TtsStreamChunkReceived,\n\n TtsStreamEnded,\n \n AudioStreamStarted,\n \n AudioStreamEnded,\n \n ErrorOccurred,\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Session/IConversationSession.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\npublic interface IConversationSession : IAsyncDisposable\n{\n IConversationContext Context { get; }\n\n Guid SessionId { get; }\n\n ValueTask RunAsync(CancellationToken cancellationToken);\n\n ValueTask StopAsync();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Configuration/SpoutConfiguration.cs", "namespace PersonaEngine.Lib.Configuration;\n\npublic record SpoutConfiguration\n{\n public required string OutputName { get; init; }\n\n public required int Width { get; init; }\n\n public required int Height { get; init; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/IAudioFilter.cs", "namespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic interface IAudioFilter\n{\n int Priority { get; }\n\n void Process(AudioSegment audioSegment);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/IMemoryBackedAudioSource.cs", "namespace PersonaEngine.Lib.Audio;\n\npublic interface IMemoryBackedAudioSource\n{\n public bool StoresFloats { get; }\n\n public bool StoresBytes { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Events/IConversationEvent.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\npublic interface IConversationEvent\n{\n Guid SessionId { get; }\n\n Guid? TurnId { get; }\n\n DateTimeOffset Timestamp { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/IConversationCleanupStrategy.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Configuration;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic interface IConversationCleanupStrategy\n{\n bool Cleanup(List history, ConversationContextOptions options, IReadOnlyDictionary participants);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/RenderType.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic enum RenderType\n{\n OpenGL\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Common/IStartupTask.cs", "using Silk.NET.OpenGL;\n\nnamespace PersonaEngine.Lib.UI.Common;\n\npublic interface IStartupTask\n{\n void Execute(GL gl);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Output/GeneralEvents.cs", "using PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\n\npublic record BaseOutputEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp) : IOutputEvent;\n\npublic record ErrorOutputEvent(Guid SessionId, Guid? TurnId, DateTimeOffset Timestamp, Exception Exception) : IOutputEvent { }"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Events/IInputEvent.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\npublic interface IInputEvent : IConversationEvent\n{\n string ParticipantId { get; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Strategies/BargeInType.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Strategies;\n\npublic enum BargeInType\n{\n Ignore,\n\n Allow,\n\n NoSpeaking,\n\n MinWords,\n\n MinWordsNoSpeaking\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Events/Common/CompletionReason.cs", "namespace PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\n\npublic enum CompletionReason\n{\n Completed,\n\n Cancelled,\n\n Error\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/WheelStoppedEventHandler.cs", "namespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic delegate void WheelStoppedEventHandler(string selectedOption);"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Context/ParticipantInfo.cs", "using OpenAI.Chat;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\n\npublic record ParticipantInfo(\n string Id,\n string Name,\n ChatMessageRole Role\n);"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Abstractions/Events/IOutputEvent.cs", "namespace PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\n\npublic interface IOutputEvent : IConversationEvent { }"]], "task_instance_info": {"created_time": "2025-08-20 19:11:54", "created_task_model": "DeepSeek-R1", "function_skeleton": "public void Stop () {}", "code_description": "This code segment functions to: Terminate active animation processes by resetting internal states, halting ongoing motion sequences, and restoring default visual parameters to ensure a clean transition when the service is deactivated."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n /// \n /// Stops the service, resetting blinking and clearing the tracked idle motion.\n /// Attempts to leave the eyes in an open state.\n /// \n public void Stop()\n {\n ObjectDisposedException.ThrowIf(_disposed, typeof(IdleBlinkingAnimationService));\n\n if (!_isStarted)\n {\n _logger.LogWarning(\"Service not started. No action taken.\");\n return;\n }\n\n _logger.LogInformation(\"Stopping IdleBlinkingAnimationService...\");\n\n // Clear any tracked idle motion and reset animation state\n _currentIdleMotionEntry = null;\n\n // Reset blinking state\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n _timeUntilNextBlink = 0.0f;\n _blinkPhaseTimer = 0.0f;\n\n // Attempt to reset eye parameters to open state\n ResetEyesToOpenState();\n\n _isStarted = false;\n _logger.LogInformation(\"IdleBlinkingAnimationService stopped.\");\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-12-27"}, "editdistance_info": {"edit_distance": 42.6667, "calculate_time": "2025-08-20 19:12:27", "true_code_clean": "public void Stop()\n {\n if ( !_isStarted || _disposed )\n {\n return;\n }\n _isStarted = false;\n ResetEyesToOpenState();\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n _blinkPhaseTimer = 0f;\n _currentIdleMotionEntry = null;\n _logger.LogInformation(\"IdleBlinkingAnimationService stopped.\");\n }", "predict_code_clean": " public void Stop()\n {\n ObjectDisposedException.ThrowIf(_disposed, typeof(IdleBlinkingAnimationService));\n if (!_isStarted)\n {\n _logger.LogWarning(\"Service not started. No action taken.\");\n return;\n }\n _logger.LogInformation(\"Stopping IdleBlinkingAnimationService...\");\n _currentIdleMotionEntry = null;\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n _timeUntilNextBlink = 0.0f;\n _blinkPhaseTimer = 0.0f;\n ResetEyesToOpenState();\n _isStarted = false;\n _logger.LogInformation(\"IdleBlinkingAnimationService stopped.\");\n }"}} {"repo_name": "handcrafted-persona-engine", "file_name": "/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismPose.cs", "inference_info": {"prefix_code": "using System.Text.Json.Nodes;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// パーツの不透明度の管理と設定を行う。\n/// \npublic class CubismPose\n{\n public const float Epsilon = 0.001f;\n\n public const float DefaultFadeInSeconds = 0.5f;\n\n // Pose.jsonのタグ\n public const string FadeIn = \"FadeInTime\";\n\n public const string Link = \"Link\";\n\n public const string Groups = \"Groups\";\n\n public const string Id = \"Id\";\n\n /// \n /// フェード時間[秒]\n /// \n private readonly float _fadeTimeSeconds = DefaultFadeInSeconds;\n\n /// \n /// それぞれのパーツグループの個数\n /// \n private readonly List _partGroupCounts = [];\n\n /// \n /// パーツグループ\n /// \n private readonly List _partGroups = [];\n\n /// \n /// 前回操作したモデル\n /// \n private CubismModel? _lastModel;\n\n /// \n /// インスタンスを作成する。\n /// \n /// pose3.jsonのデータ\n public CubismPose(string pose3json)\n {\n using var stream = File.Open(pose3json, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var json = JsonNode.Parse(stream)?.AsObject()\n ?? throw new Exception(\"Pose json is error\");\n\n // フェード時間の指定\n if ( json.ContainsKey(FadeIn) )\n {\n var item = json[FadeIn];\n _fadeTimeSeconds = item == null ? DefaultFadeInSeconds : (float)item;\n\n if ( _fadeTimeSeconds < 0.0f )\n {\n _fadeTimeSeconds = DefaultFadeInSeconds;\n }\n }\n\n // パーツグループ\n if ( json[Groups] is not JsonArray poseListInfo )\n {\n return;\n }\n\n foreach ( var item in poseListInfo )\n {\n var idCount = item!.AsArray().Count;\n var groupCount = 0;\n\n for ( var groupIndex = 0; groupIndex < idCount; ++groupIndex )\n {\n var partInfo = item[groupIndex]!;\n PartData partData = new() { PartId = CubismFramework.CubismIdManager.GetId(partInfo[Id]!.ToString()) };\n\n // リンクするパーツの設定\n if ( partInfo[Link] != null )\n {\n var linkListInfo = partInfo[Link]!;\n var linkCount = linkListInfo.AsArray().Count;\n\n for ( var linkIndex = 0; linkIndex < linkCount; ++linkIndex )\n {\n partData.Link.Add(new PartData { PartId = CubismFramework.CubismIdManager.GetId(linkListInfo[linkIndex]!.ToString()) });\n }\n }\n\n _partGroups.Add(partData);\n\n ++groupCount;\n }\n\n _partGroupCounts.Add(groupCount);\n }\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n // 前回のモデルと同じではないときは初期化が必要\n if ( model.Model != _lastModel?.Model )\n {\n // パラメータインデックスの初期化\n Reset(model);\n }\n\n _lastModel = model;\n\n // 設定から時間を変更すると、経過時間がマイナスになることがあるので、経過時間0として対応。\n if ( deltaTimeSeconds < 0.0f )\n {\n deltaTimeSeconds = 0.0f;\n }\n\n var beginIndex = 0;\n\n foreach ( var item in _partGroupCounts )\n {\n DoFade(model, deltaTimeSeconds, beginIndex, item);\n\n beginIndex += item;\n }\n\n CopyPartOpacities(model);\n }\n\n /// \n /// 表示を初期化する。\n /// 不透明度の初期値が0でないパラメータは、不透明度を1に設定する。\n /// \n /// 対象のモデル\n ", "suffix_code": "\n\n /// \n /// パーツの不透明度をコピーし、リンクしているパーツへ設定する。\n /// \n /// 対象のモデル\n private void CopyPartOpacities(CubismModel model)\n {\n foreach ( var item in _partGroups )\n {\n if ( item.Link.Count == 0 )\n {\n continue; // 連動するパラメータはない\n }\n\n var partIndex = item.PartIndex;\n var opacity = model.GetPartOpacity(partIndex);\n\n foreach ( var item1 in item.Link )\n {\n var linkPartIndex = item1.PartIndex;\n\n if ( linkPartIndex < 0 )\n {\n continue;\n }\n\n model.SetPartOpacity(linkPartIndex, opacity);\n }\n }\n }\n\n /// \n /// パーツのフェード操作を行う。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// フェード操作を行うパーツグループの先頭インデックス\n /// フェード操作を行うパーツグループの個数\n private void DoFade(CubismModel model, float deltaTimeSeconds, int beginIndex, int partGroupCount)\n {\n var visiblePartIndex = -1;\n var newOpacity = 1.0f;\n\n var Phi = 0.5f;\n var BackOpacityThreshold = 0.15f;\n\n // 現在、表示状態になっているパーツを取得\n for ( var i = beginIndex; i < beginIndex + partGroupCount; ++i )\n {\n var partIndex = _partGroups[i].PartIndex;\n var paramIndex = _partGroups[i].ParameterIndex;\n\n if ( model.GetParameterValue(paramIndex) > Epsilon )\n {\n if ( visiblePartIndex >= 0 )\n {\n break;\n }\n\n visiblePartIndex = i;\n newOpacity = model.GetPartOpacity(partIndex);\n\n // 新しい不透明度を計算\n newOpacity += deltaTimeSeconds / _fadeTimeSeconds;\n\n if ( newOpacity > 1.0f )\n {\n newOpacity = 1.0f;\n }\n }\n }\n\n if ( visiblePartIndex < 0 )\n {\n visiblePartIndex = 0;\n newOpacity = 1.0f;\n }\n\n // 表示パーツ、非表示パーツの不透明度を設定する\n for ( var i = beginIndex; i < beginIndex + partGroupCount; ++i )\n {\n var partsIndex = _partGroups[i].PartIndex;\n\n // 表示パーツの設定\n if ( visiblePartIndex == i )\n {\n model.SetPartOpacity(partsIndex, newOpacity); // 先に設定\n }\n // 非表示パーツの設定\n else\n {\n var opacity = model.GetPartOpacity(partsIndex);\n float a1; // 計算によって求められる不透明度\n\n if ( newOpacity < Phi )\n {\n a1 = newOpacity * (Phi - 1) / Phi + 1.0f; // (0,1),(phi,phi)を通る直線式\n }\n else\n {\n a1 = (1 - newOpacity) * Phi / (1.0f - Phi); // (1,0),(phi,phi)を通る直線式\n }\n\n // 背景の見える割合を制限する場合\n var backOpacity = (1.0f - a1) * (1.0f - newOpacity);\n\n if ( backOpacity > BackOpacityThreshold )\n {\n a1 = 1.0f - BackOpacityThreshold / (1.0f - newOpacity);\n }\n\n if ( opacity > a1 )\n {\n opacity = a1; // 計算の不透明度よりも大きければ(濃ければ)不透明度を上げる\n }\n\n model.SetPartOpacity(partsIndex, opacity);\n }\n }\n }\n}", "middle_code": "public void Reset(CubismModel model)\n {\n var beginIndex = 0;\n foreach ( var item in _partGroupCounts )\n {\n for ( var j = beginIndex; j < beginIndex + item; ++j )\n {\n _partGroups[j].Initialize(model);\n var partsIndex = _partGroups[j].PartIndex;\n var paramIndex = _partGroups[j].ParameterIndex;\n if ( partsIndex < 0 )\n {\n continue;\n }\n model.SetPartOpacity(partsIndex, j == beginIndex ? 1.0f : 0.0f);\n model.SetParameterValue(paramIndex, j == beginIndex ? 1.0f : 0.0f);\n for ( var k = 0; k < _partGroups[j].Link.Count; ++k )\n {\n _partGroups[j].Link[k].Initialize(model);\n }\n }\n beginIndex += item;\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModel.cs", "using System.Numerics;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\npublic class CubismModel : IDisposable\n{\n /// \n /// 存在していないパラメータIDのリスト\n /// \n private readonly Dictionary _notExistParameterId = [];\n\n /// \n /// 存在していないパラメータの値のリスト\n /// \n private readonly Dictionary _notExistParameterValues = [];\n\n /// \n /// 存在していないパーツIDのリスト\n /// \n private readonly Dictionary _notExistPartId = [];\n\n /// \n /// 存在していないパーツの不透明度のリスト\n /// \n private readonly Dictionary _notExistPartOpacities = [];\n\n /// \n /// パラメータの最大値のリスト\n /// \n private readonly unsafe float* _parameterMaximumValues;\n\n /// \n /// パラメータの最小値のリスト\n /// \n private readonly unsafe float* _parameterMinimumValues;\n\n /// \n /// パラメータの値のリスト\n /// \n private readonly unsafe float* _parameterValues;\n\n /// \n /// Partの子DrawableIndexの配列\n /// \n private readonly List[] _partChildDrawables;\n\n /// \n /// パーツの不透明度のリスト\n /// \n private readonly unsafe float* _partOpacities;\n\n /// \n /// 保存されたパラメータ\n /// \n private readonly List _savedParameters = [];\n\n /// \n /// カリング設定の配列\n /// \n private readonly List _userCullings = [];\n\n /// \n /// Drawable スクリーン色の配列\n /// \n private readonly List _userMultiplyColors = [];\n\n /// \n /// Part スクリーン色の配列\n /// \n private readonly List _userPartMultiplyColors = [];\n\n /// \n /// Part 乗算色の配列\n /// \n private readonly List _userPartScreenColors = [];\n\n /// \n /// Drawable 乗算色の配列\n /// \n private readonly List _userScreenColors = [];\n\n public readonly List DrawableIds = [];\n\n public readonly List ParameterIds = [];\n\n public readonly List PartIds = [];\n\n /// \n /// モデルのカリング設定をすべて上書きするか?\n /// \n private bool _isOverwrittenCullings;\n\n /// \n /// 乗算色を全て上書きするか?\n /// \n private bool _isOverwrittenModelMultiplyColors;\n\n /// \n /// スクリーン色を全て上書きするか?\n /// \n private bool _isOverwrittenModelScreenColors;\n\n /// \n /// モデルの不透明度\n /// \n private float _modelOpacity;\n\n public unsafe CubismModel(IntPtr model)\n {\n Model = model;\n _modelOpacity = 1.0f;\n\n _parameterValues = CubismCore.GetParameterValues(Model);\n _partOpacities = CubismCore.GetPartOpacities(Model);\n _parameterMaximumValues = CubismCore.GetParameterMaximumValues(Model);\n _parameterMinimumValues = CubismCore.GetParameterMinimumValues(Model);\n\n {\n var parameterIds = CubismCore.GetParameterIds(Model);\n var parameterCount = CubismCore.GetParameterCount(Model);\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n var str = new string(parameterIds[i]);\n ParameterIds.Add(CubismFramework.CubismIdManager.GetId(str));\n }\n }\n\n var partCount = CubismCore.GetPartCount(Model);\n var partIds = CubismCore.GetPartIds(Model);\n\n _partChildDrawables = new List[partCount];\n for ( var i = 0; i < partCount; ++i )\n {\n var str = new string(partIds[i]);\n PartIds.Add(CubismFramework.CubismIdManager.GetId(str));\n _partChildDrawables[i] = [];\n }\n\n var drawableIds = CubismCore.GetDrawableIds(Model);\n var drawableCount = CubismCore.GetDrawableCount(Model);\n\n // カリング設定\n var userCulling = new DrawableCullingData { IsOverwritten = false, IsCulling = false };\n\n // 乗算色\n var multiplyColor = new CubismTextureColor();\n\n // スクリーン色\n var screenColor = new CubismTextureColor(0, 0, 0, 1.0f);\n\n // Parts\n for ( var i = 0; i < partCount; ++i )\n {\n _userPartMultiplyColors.Add(new PartColorData {\n IsOverwritten = false, Color = multiplyColor // 乗算色\n });\n\n _userPartScreenColors.Add(new PartColorData {\n IsOverwritten = false, Color = screenColor // スクリーン色\n });\n }\n\n // Drawables\n for ( var i = 0; i < drawableCount; ++i )\n {\n var str = new string(drawableIds[i]);\n DrawableIds.Add(CubismFramework.CubismIdManager.GetId(str));\n _userMultiplyColors.Add(new DrawableColorData {\n IsOverwritten = false, Color = multiplyColor // 乗算色\n });\n\n _userScreenColors.Add(new DrawableColorData {\n IsOverwritten = false, Color = screenColor // スクリーン色\n });\n\n _userCullings.Add(userCulling);\n\n var parentIndex = CubismCore.GetDrawableParentPartIndices(Model)[i];\n if ( parentIndex >= 0 )\n {\n _partChildDrawables[parentIndex].Add(i);\n }\n }\n }\n\n /// \n /// モデル\n /// \n public IntPtr Model { get; }\n\n public void Dispose()\n {\n CubismFramework.DeallocateAligned(Model);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// partのOverwriteColor Set関数\n /// \n public void SetPartColor(int partIndex, float r, float g, float b, float a,\n List partColors, List drawableColors)\n {\n partColors[partIndex].Color.R = r;\n partColors[partIndex].Color.G = g;\n partColors[partIndex].Color.B = b;\n partColors[partIndex].Color.A = a;\n\n if ( partColors[partIndex].IsOverwritten )\n {\n for ( var i = 0; i < _partChildDrawables[partIndex].Count; i++ )\n {\n var drawableIndex = _partChildDrawables[partIndex][i];\n drawableColors[drawableIndex].Color.R = r;\n drawableColors[drawableIndex].Color.G = g;\n drawableColors[drawableIndex].Color.B = b;\n drawableColors[drawableIndex].Color.A = a;\n }\n }\n }\n\n /// \n /// partのOverwriteFlag Set関数\n /// \n public void SetOverwriteColorForPartColors(int partIndex, bool value,\n List partColors, List drawableColors)\n {\n partColors[partIndex].IsOverwritten = value;\n\n for ( var i = 0; i < _partChildDrawables[partIndex].Count; i++ )\n {\n var drawableIndex = _partChildDrawables[partIndex][i];\n drawableColors[drawableIndex].IsOverwritten = value;\n if ( value )\n {\n drawableColors[drawableIndex].Color.R = partColors[partIndex].Color.R;\n drawableColors[drawableIndex].Color.G = partColors[partIndex].Color.G;\n drawableColors[drawableIndex].Color.B = partColors[partIndex].Color.B;\n drawableColors[drawableIndex].Color.A = partColors[partIndex].Color.A;\n }\n }\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n public void Update()\n {\n // Update model.\n CubismCore.UpdateModel(Model);\n // Reset dynamic drawable flags.\n CubismCore.ResetDrawableDynamicFlags(Model);\n }\n\n /// \n /// Pixel単位でキャンバスの幅の取得\n /// \n /// キャンバスの幅(pixel)\n public float GetCanvasWidthPixel()\n {\n if ( Model == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out _);\n\n return tmpSizeInPixels.X;\n }\n\n /// \n /// Pixel単位でキャンバスの高さの取得\n /// \n /// キャンバスの高さ(pixel)\n public float GetCanvasHeightPixel()\n {\n if ( new IntPtr(Model) == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out _);\n\n return tmpSizeInPixels.Y;\n }\n\n /// \n /// PixelsPerUnitを取得する。\n /// \n /// PixelsPerUnit\n public float GetPixelsPerUnit()\n {\n if ( new IntPtr(Model) == IntPtr.Zero )\n {\n return 0.0f;\n }\n\n CubismCore.ReadCanvasInfo(Model, out _, out _, out var tmpPixelsPerUnit);\n\n return tmpPixelsPerUnit;\n }\n\n /// \n /// Unit単位でキャンバスの幅の取得\n /// \n /// キャンバスの幅(Unit)\n public float GetCanvasWidth()\n {\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out var tmpPixelsPerUnit);\n\n return tmpSizeInPixels.X / tmpPixelsPerUnit;\n }\n\n /// \n /// Unit単位でキャンバスの高さの取得\n /// \n /// キャンバスの高さ(Unit)\n public float GetCanvasHeight()\n {\n CubismCore.ReadCanvasInfo(Model, out var tmpSizeInPixels, out _, out var tmpPixelsPerUnit);\n\n return tmpSizeInPixels.Y / tmpPixelsPerUnit;\n }\n\n /// \n /// パーツのインデックスを取得する。\n /// \n /// パーツのID\n /// パーツのインデックス\n public int GetPartIndex(string partId)\n {\n var partIndex = PartIds.IndexOf(partId);\n if ( partIndex != -1 )\n {\n return partIndex;\n }\n\n var partCount = CubismCore.GetPartCount(Model);\n\n // モデルに存在していない場合、非存在パーツIDリスト内にあるかを検索し、そのインデックスを返す\n if ( _notExistPartId.TryGetValue(partId, out var item) )\n {\n return item;\n }\n\n // 非存在パーツIDリストにない場合、新しく要素を追加する\n partIndex = partCount + _notExistPartId.Count;\n\n _notExistPartId.TryAdd(partId, partIndex);\n _notExistPartOpacities.Add(partIndex, 0);\n\n return partIndex;\n }\n\n /// \n /// パーツのIDを取得する。\n /// \n /// パーツのIndex\n /// パーツのID\n public string GetPartId(int partIndex)\n {\n if ( 0 <= partIndex && partIndex < PartIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of PartIds size\");\n }\n\n return PartIds[partIndex];\n }\n\n /// \n /// パーツの個数を取得する。\n /// \n /// パーツの個数\n public int GetPartCount() { return CubismCore.GetPartCount(Model); }\n\n /// \n /// パーツの不透明度を設定する。\n /// \n /// パーツのID\n /// 不透明度\n public void SetPartOpacity(string partId, float opacity)\n {\n // 高速化のためにPartIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var index = GetPartIndex(partId);\n\n if ( index < 0 )\n {\n return; // パーツが無いのでスキップ\n }\n\n SetPartOpacity(index, opacity);\n }\n\n /// \n /// パーツの不透明度を設定する。\n /// \n /// パーツのインデックス\n /// パーツの不透明度\n public unsafe void SetPartOpacity(int partIndex, float opacity)\n {\n if ( _notExistPartOpacities.ContainsKey(partIndex) )\n {\n _notExistPartOpacities[partIndex] = opacity;\n\n return;\n }\n\n //インデックスの範囲内検知\n if ( 0 > partIndex || partIndex >= GetPartCount() )\n {\n throw new ArgumentException(\"partIndex out of range\");\n }\n\n _partOpacities[partIndex] = opacity;\n }\n\n /// \n /// パーツの不透明度を取得する。\n /// \n /// パーツのID\n /// パーツの不透明度\n public float GetPartOpacity(string partId)\n {\n // 高速化のためにPartIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var index = GetPartIndex(partId);\n\n if ( index < 0 )\n {\n return 0; //パーツが無いのでスキップ\n }\n\n return GetPartOpacity(index);\n }\n\n /// \n /// パーツの不透明度を取得する。\n /// \n /// パーツのインデックス\n /// パーツの不透明度\n public unsafe float GetPartOpacity(int partIndex)\n {\n if ( _notExistPartOpacities.TryGetValue(partIndex, out var value) )\n {\n // モデルに存在しないパーツIDの場合、非存在パーツリストから不透明度を返す\n return value;\n }\n\n //インデックスの範囲内検知\n if ( 0 > partIndex || partIndex >= GetPartCount() )\n {\n throw new ArgumentException(\"partIndex out of range\");\n }\n\n return _partOpacities[partIndex];\n }\n\n /// \n /// パラメータのインデックスを取得する。\n /// \n /// パラメータID\n /// パラメータのインデックス\n public int GetParameterIndex(string parameterId)\n {\n var parameterIndex = ParameterIds.IndexOf(parameterId);\n if ( parameterIndex != -1 )\n {\n return parameterIndex;\n }\n\n // モデルに存在していない場合、非存在パラメータIDリスト内を検索し、そのインデックスを返す\n if ( _notExistParameterId.TryGetValue(parameterId, out var data) )\n {\n return data;\n }\n\n // 非存在パラメータIDリストにない場合、新しく要素を追加する\n parameterIndex = CubismCore.GetParameterCount(Model) + _notExistParameterId.Count;\n\n _notExistParameterId.TryAdd(parameterId, parameterIndex);\n _notExistParameterValues.Add(parameterIndex, 0);\n\n return parameterIndex;\n }\n\n /// \n /// パラメータの個数を取得する。\n /// \n /// パラメータの個数\n public int GetParameterCount() { return CubismCore.GetParameterCount(Model); }\n\n /// \n /// パラメータの種類を取得する。\n /// \n /// パラメータのインデックス\n /// \n /// csmParameterType_Normal -> 通常のパラメータ\n /// csmParameterType_BlendShape -> ブレンドシェイプパラメータ\n /// \n public unsafe int GetParameterType(int parameterIndex) { return CubismCore.GetParameterTypes(Model)[parameterIndex]; }\n\n /// \n /// パラメータの最大値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの最大値\n public unsafe float GetParameterMaximumValue(int parameterIndex) { return CubismCore.GetParameterMaximumValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータの最小値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの最小値\n public unsafe float GetParameterMinimumValue(int parameterIndex) { return CubismCore.GetParameterMinimumValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータのデフォルト値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータのデフォルト値\n public unsafe float GetParameterDefaultValue(int parameterIndex) { return CubismCore.GetParameterDefaultValues(Model)[parameterIndex]; }\n\n /// \n /// パラメータの値を取得する。\n /// \n /// パラメータID\n /// パラメータの値\n public float GetParameterValue(string parameterId)\n {\n // 高速化のためにParameterIndexを取得できる機構になっているが、外部からの設定の時は呼び出し頻度が低いため不要\n var parameterIndex = GetParameterIndex(parameterId);\n\n return GetParameterValue(parameterIndex);\n }\n\n /// \n /// パラメータの値を取得する。\n /// \n /// パラメータのインデックス\n /// パラメータの値\n public unsafe float GetParameterValue(int parameterIndex)\n {\n if ( _notExistParameterValues.TryGetValue(parameterIndex, out var item) )\n {\n return item;\n }\n\n //インデックスの範囲内検知\n if ( 0 > parameterIndex || parameterIndex >= GetParameterCount() )\n {\n throw new ArgumentException(\"parameterIndex out of range\");\n }\n\n return _parameterValues[parameterIndex];\n }\n\n /// \n /// パラメータの値を設定する。\n /// \n /// パラメータID\n /// パラメータの値\n /// 重み\n public void SetParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n SetParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を設定する。\n /// \n /// パラメータのインデックス\n /// パラメータの値\n /// 重み\n public unsafe void SetParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( _notExistParameterValues.TryGetValue(parameterIndex, out var value1) )\n {\n _notExistParameterValues[parameterIndex] = weight == 1\n ? value\n : value1 * (1 - weight) + value * weight;\n\n return;\n }\n\n //インデックスの範囲内検知\n if ( 0 > parameterIndex || parameterIndex >= GetParameterCount() )\n {\n throw new ArgumentException(\"parameterIndex out of range\");\n }\n\n if ( CubismCore.GetParameterMaximumValues(Model)[parameterIndex] < value )\n {\n value = CubismCore.GetParameterMaximumValues(Model)[parameterIndex];\n }\n\n if ( CubismCore.GetParameterMinimumValues(Model)[parameterIndex] > value )\n {\n value = CubismCore.GetParameterMinimumValues(Model)[parameterIndex];\n }\n\n _parameterValues[parameterIndex] = weight == 1\n ? value\n : _parameterValues[parameterIndex] = _parameterValues[parameterIndex] * (1 - weight) + value * weight;\n }\n\n /// \n /// パラメータの値を加算する。\n /// \n /// パラメータID\n /// 加算する値\n /// 重み\n public void AddParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n AddParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を加算する。\n /// \n /// パラメータのインデックス\n /// 加算する値\n /// 重み\n public void AddParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( parameterIndex == -1 )\n {\n return;\n }\n\n SetParameterValue(parameterIndex, GetParameterValue(parameterIndex) + value * weight);\n }\n\n /// \n /// パラメータの値を乗算する。\n /// \n /// パラメータID\n /// 乗算する値\n /// 重み\n public void MultiplyParameterValue(string parameterId, float value, float weight = 1.0f)\n {\n var index = GetParameterIndex(parameterId);\n MultiplyParameterValue(index, value, weight);\n }\n\n /// \n /// パラメータの値を乗算する。\n /// \n /// パラメータのインデックス\n /// 乗算する値\n /// 重み\n public void MultiplyParameterValue(int parameterIndex, float value, float weight = 1.0f)\n {\n if ( parameterIndex == -1 )\n {\n return;\n }\n\n SetParameterValue(parameterIndex, GetParameterValue(parameterIndex) * (1.0f + (value - 1.0f) * weight));\n }\n\n /// \n /// Drawableのインデックスを取得する。\n /// \n /// DrawableのID\n /// Drawableのインデックス\n public int GetDrawableIndex(string drawableId) { return DrawableIds.IndexOf(drawableId); }\n\n /// \n /// Drawableの個数を取得する。\n /// \n /// Drawableの個数\n public int GetDrawableCount() { return CubismCore.GetDrawableCount(Model); }\n\n /// \n /// DrawableのIDを取得する。\n /// \n /// Drawableのインデックス\n /// DrawableのID\n public string GetDrawableId(int drawableIndex)\n {\n if ( 0 <= drawableIndex && drawableIndex < DrawableIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of DrawableIds size\");\n }\n\n return DrawableIds[drawableIndex];\n }\n\n /// \n /// Drawableの描画順リストを取得する。\n /// \n /// Drawableの描画順リスト\n public unsafe int* GetDrawableRenderOrders() { return CubismCore.GetDrawableRenderOrders(Model); }\n\n /// \n /// Drawableのテクスチャインデックスリストの取得\n /// 関数名が誤っていたため、代替となる getDrawableTextureIndex を追加し、この関数は非推奨となりました。\n /// \n /// Drawableのインデックス\n /// Drawableのテクスチャインデックスリスト\n public int GetDrawableTextureIndices(int drawableIndex) { return GetDrawableTextureIndex(drawableIndex); }\n\n /// \n /// Drawableのテクスチャインデックスを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのテクスチャインデックス\n public unsafe int GetDrawableTextureIndex(int drawableIndex)\n {\n var textureIndices = CubismCore.GetDrawableTextureIndices(Model);\n\n return textureIndices[drawableIndex];\n }\n\n /// \n /// Drawableの頂点インデックスの個数を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点インデックスの個数\n public unsafe int GetDrawableVertexIndexCount(int drawableIndex) { return CubismCore.GetDrawableIndexCounts(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点の個数を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点の個数\n public unsafe int GetDrawableVertexCount(int drawableIndex) { return CubismCore.GetDrawableVertexCounts(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点リストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点リスト\n public unsafe float* GetDrawableVertices(int drawableIndex) { return (float*)GetDrawableVertexPositions(drawableIndex); }\n\n /// \n /// Drawableの頂点インデックスリストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点インデックスリスト\n public unsafe ushort* GetDrawableVertexIndices(int drawableIndex) { return CubismCore.GetDrawableIndices(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点リストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点リスト\n public unsafe Vector2* GetDrawableVertexPositions(int drawableIndex) { return CubismCore.GetDrawableVertexPositions(Model)[drawableIndex]; }\n\n /// \n /// Drawableの頂点のUVリストを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの頂点のUVリスト\n public unsafe Vector2* GetDrawableVertexUvs(int drawableIndex) { return CubismCore.GetDrawableVertexUvs(Model)[drawableIndex]; }\n\n /// \n /// Drawableの不透明度を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの不透明度\n public unsafe float GetDrawableOpacity(int drawableIndex) { return CubismCore.GetDrawableOpacities(Model)[drawableIndex]; }\n\n /// \n /// Drawableの乗算色を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableの乗算色\n public unsafe Vector4 GetDrawableMultiplyColor(int drawableIndex) { return CubismCore.GetDrawableMultiplyColors(Model)[drawableIndex]; }\n\n /// \n /// Drawableのスクリーン色を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのスクリーン色\n public unsafe Vector4 GetDrawableScreenColor(int drawableIndex) { return CubismCore.GetDrawableScreenColors(Model)[drawableIndex]; }\n\n /// \n /// Drawableの親パーツのインデックスを取得する。\n /// \n /// Drawableのインデックス\n /// drawableの親パーツのインデックス\n public unsafe int GetDrawableParentPartIndex(int drawableIndex) { return CubismCore.GetDrawableParentPartIndices(Model)[drawableIndex]; }\n\n /// \n /// Drawableのブレンドモードを取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのブレンドモード\n public unsafe CubismBlendMode GetDrawableBlendMode(int drawableIndex)\n {\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model)[drawableIndex];\n\n return IsBitSet(constantFlags, CsmEnum.CsmBlendAdditive)\n ? CubismBlendMode.Additive\n : IsBitSet(constantFlags, CsmEnum.CsmBlendMultiplicative)\n ? CubismBlendMode.Multiplicative\n : CubismBlendMode.Normal;\n }\n\n /// \n /// Drawableのマスク使用時の反転設定を取得する。\n /// マスクを使用しない場合は無視される\n /// \n /// Drawableのインデックス\n /// Drawableのマスクの反転設定\n public unsafe bool GetDrawableInvertedMask(int drawableIndex)\n {\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model)[drawableIndex];\n\n return IsBitSet(constantFlags, CsmEnum.CsmIsInvertedMask);\n }\n\n /// \n /// Drawableの表示情報を取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableが表示\n /// false Drawableが非表示\n /// \n public unsafe bool GetDrawableDynamicFlagIsVisible(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmIsVisible);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの表示状態が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの表示状態が直近のCubismModel::Update関数で変化した\n /// false Drawableの表示状態が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagVisibilityDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmVisibilityDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの不透明度が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの不透明度が直近のCubismModel::Update関数で変化した\n /// false Drawableの不透明度が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagOpacityDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmOpacityDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableのDrawOrderが変化したかを取得する。\n /// DrawOrderはArtMesh上で指定する0から1000の情報\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの不透明度が直近のCubismModel::Update関数で変化した\n /// false Drawableの不透明度が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagDrawOrderDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmDrawOrderDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの描画の順序が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの描画の順序が直近のCubismModel::Update関数で変化した\n /// false Drawableの描画の順序が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagRenderOrderDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmRenderOrderDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの頂点情報が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの頂点情報が直近のCubismModel::Update関数で変化した\n /// false Drawableの頂点情報が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagVertexPositionsDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmVertexPositionsDidChange);\n }\n\n /// \n /// 直近のCubismModel::Update関数でDrawableの乗算色・スクリーン色が変化したかを取得する。\n /// \n /// Drawableのインデックス\n /// \n /// true Drawableの乗算色・スクリーン色が直近のCubismModel::Update関数で変化した\n /// false Drawableの乗算色・スクリーン色が直近のCubismModel::Update関数で変化していない\n /// \n public unsafe bool GetDrawableDynamicFlagBlendColorDidChange(int drawableIndex)\n {\n var dynamicFlags = CubismCore.GetDrawableDynamicFlags(Model)[drawableIndex];\n\n return IsBitSet(dynamicFlags, CsmEnum.CsmBlendColorDidChange);\n }\n\n /// \n /// Drawableのクリッピングマスクリストを取得する。\n /// \n /// Drawableのクリッピングマスクリスト\n public unsafe int** GetDrawableMasks() { return CubismCore.GetDrawableMasks(Model); }\n\n /// \n /// Drawableのクリッピングマスクの個数リストを取得する。\n /// \n /// Drawableのクリッピングマスクの個数リスト\n public unsafe int* GetDrawableMaskCounts() { return CubismCore.GetDrawableMaskCounts(Model); }\n\n /// \n /// クリッピングマスクを使用しているかどうか?\n /// \n /// \n /// true クリッピングマスクを使用している\n /// false クリッピングマスクを使用していない\n /// \n public unsafe bool IsUsingMasking()\n {\n for ( var d = 0; d < CubismCore.GetDrawableCount(Model); ++d )\n {\n if ( CubismCore.GetDrawableMaskCounts(Model)[d] <= 0 )\n {\n continue;\n }\n\n return true;\n }\n\n return false;\n }\n\n /// \n /// 保存されたパラメータを読み込む\n /// \n public unsafe void LoadParameters()\n {\n var parameterCount = CubismCore.GetParameterCount(Model);\n var savedParameterCount = _savedParameters.Count;\n\n if ( parameterCount > savedParameterCount )\n {\n parameterCount = savedParameterCount;\n }\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n _parameterValues[i] = _savedParameters[i];\n }\n }\n\n /// \n /// パラメータを保存する。\n /// \n public unsafe void SaveParameters()\n {\n var parameterCount = CubismCore.GetParameterCount(Model);\n var savedParameterCount = _savedParameters.Count;\n\n if ( savedParameterCount != parameterCount )\n {\n _savedParameters.Clear();\n for ( var i = 0; i < parameterCount; ++i )\n {\n _savedParameters.Add(_parameterValues[i]);\n }\n }\n else\n {\n for ( var i = 0; i < parameterCount; ++i )\n {\n _savedParameters[i] = _parameterValues[i];\n }\n }\n }\n\n /// \n /// drawableの乗算色を取得する\n /// \n public CubismTextureColor GetMultiplyColor(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelMultiplyColors() ||\n GetOverwriteFlagForDrawableMultiplyColors(drawableIndex) )\n {\n return _userMultiplyColors[drawableIndex].Color;\n }\n\n var color = GetDrawableMultiplyColor(drawableIndex);\n\n return new CubismTextureColor(color.X, color.Y, color.Z, color.W);\n }\n\n /// \n /// drawableのスクリーン色を取得する\n /// \n public CubismTextureColor GetScreenColor(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelScreenColors() ||\n GetOverwriteFlagForDrawableScreenColors(drawableIndex) )\n {\n return _userScreenColors[drawableIndex].Color;\n }\n\n var color = GetDrawableScreenColor(drawableIndex);\n\n return new CubismTextureColor(color.X, color.Y, color.Z, color.W);\n }\n\n /// \n /// drawableの乗算色を設定する\n /// \n public void SetMultiplyColor(int drawableIndex, CubismTextureColor color) { SetMultiplyColor(drawableIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// drawableの乗算色を設定する\n /// \n public void SetMultiplyColor(int drawableIndex, float r, float g, float b, float a = 1.0f)\n {\n _userMultiplyColors[drawableIndex].Color.R = r;\n _userMultiplyColors[drawableIndex].Color.G = g;\n _userMultiplyColors[drawableIndex].Color.B = b;\n _userMultiplyColors[drawableIndex].Color.A = a;\n }\n\n /// \n /// drawableのスクリーン色を設定する\n /// \n /// \n /// \n public void SetScreenColor(int drawableIndex, CubismTextureColor color) { SetScreenColor(drawableIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// drawableのスクリーン色を設定する\n /// \n public void SetScreenColor(int drawableIndex, float r, float g, float b, float a = 1.0f)\n {\n _userScreenColors[drawableIndex].Color.R = r;\n _userScreenColors[drawableIndex].Color.G = g;\n _userScreenColors[drawableIndex].Color.B = b;\n _userScreenColors[drawableIndex].Color.A = a;\n }\n\n /// \n /// partの乗算色を取得する\n /// \n public CubismTextureColor GetPartMultiplyColor(int partIndex) { return _userPartMultiplyColors[partIndex].Color; }\n\n /// \n /// partの乗算色を取得する\n /// \n public CubismTextureColor GetPartScreenColor(int partIndex) { return _userPartScreenColors[partIndex].Color; }\n\n /// \n /// partのスクリーン色を設定する\n /// \n public void SetPartMultiplyColor(int partIndex, CubismTextureColor color) { SetPartMultiplyColor(partIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// partの乗算色を設定する\n /// \n public void SetPartMultiplyColor(int partIndex, float r, float g, float b, float a = 1.0f) { SetPartColor(partIndex, r, g, b, a, _userPartMultiplyColors, _userMultiplyColors); }\n\n /// \n /// partのスクリーン色を設定する\n /// \n public void SetPartScreenColor(int partIndex, CubismTextureColor color) { SetPartScreenColor(partIndex, color.R, color.G, color.B, color.A); }\n\n /// \n /// partのスクリーン色を設定する\n /// \n /// \n public void SetPartScreenColor(int partIndex, float r, float g, float b, float a = 1.0f) { SetPartColor(partIndex, r, g, b, a, _userPartScreenColors, _userScreenColors); }\n\n /// \n /// SDKからモデル全体の乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForModelMultiplyColors() { return _isOverwrittenModelMultiplyColors; }\n\n /// \n /// SDKからモデル全体のスクリーン色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForModelScreenColors() { return _isOverwrittenModelScreenColors; }\n\n /// \n /// SDKからモデル全体の乗算色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForModelMultiplyColors(bool value) { _isOverwrittenModelMultiplyColors = value; }\n\n /// \n /// SDKからモデル全体のスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForModelScreenColors(bool value) { _isOverwrittenModelScreenColors = value; }\n\n /// \n /// SDKからdrawableの乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForDrawableMultiplyColors(int drawableIndex) { return _userMultiplyColors[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableのスクリーン色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteFlagForDrawableScreenColors(int drawableIndex) { return _userScreenColors[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableの乗算色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableMultiplyColors(int drawableIndex, bool value) { _userMultiplyColors[drawableIndex].IsOverwritten = value; }\n\n /// \n /// SDKからdrawableのスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableScreenColors(int drawableIndex, bool value) { _userScreenColors[drawableIndex].IsOverwritten = value; }\n\n /// \n /// SDKからpartの乗算色を上書きするか。\n /// \n /// \n /// true -> SDK上の色情報を使用\n /// false -> モデルの色情報を使用\n /// \n public bool GetOverwriteColorForPartMultiplyColors(int partIndex) { return _userPartMultiplyColors[partIndex].IsOverwritten; }\n\n /// \n /// SDKからpartのスクリーン色を上書きするかをセットする\n /// SDK上の色情報を使うならtrue、モデルの色情報を使うならfalse\n /// \n public bool GetOverwriteColorForPartScreenColors(int partIndex) { return _userPartScreenColors[partIndex].IsOverwritten; }\n\n /// \n /// Drawableのカリング情報を取得する。\n /// \n /// Drawableのインデックス\n /// Drawableのカリング情報\n public unsafe bool GetDrawableCulling(int drawableIndex)\n {\n if ( GetOverwriteFlagForModelCullings() || GetOverwriteFlagForDrawableCullings(drawableIndex) )\n {\n return _userCullings[drawableIndex].IsCulling;\n }\n\n var constantFlags = CubismCore.GetDrawableConstantFlags(Model);\n\n return !IsBitSet(constantFlags[drawableIndex], CsmEnum.CsmIsDoubleSided);\n }\n\n /// \n /// Drawableのカリング情報を設定する\n /// \n public void SetDrawableCulling(int drawableIndex, bool isCulling) { _userCullings[drawableIndex].IsCulling = isCulling; }\n\n /// \n /// SDKからモデル全体のカリング設定を上書きするか。\n /// \n /// \n /// true -> SDK上のカリング設定を使用\n /// false -> モデルのカリング設定を使用\n /// \n public bool GetOverwriteFlagForModelCullings() { return _isOverwrittenCullings; }\n\n /// \n /// SDKからモデル全体のカリング設定を上書きするかをセットする\n /// SDK上のカリング設定を使うならtrue、モデルのカリング設定を使うならfalse\n /// \n public void SetOverwriteFlagForModelCullings(bool value) { _isOverwrittenCullings = value; }\n\n /// \n /// SDKからdrawableのカリング設定を上書きするか。\n /// \n /// \n /// true -> SDK上のカリング設定を使用\n /// false -> モデルのカリング設定を使用\n /// \n public bool GetOverwriteFlagForDrawableCullings(int drawableIndex) { return _userCullings[drawableIndex].IsOverwritten; }\n\n /// \n /// SDKからdrawableのカリング設定を上書きするかをセットする\n /// SDK上のカリング設定を使うならtrue、モデルのカリング設定を使うならfalse\n /// \n public void SetOverwriteFlagForDrawableCullings(int drawableIndex, bool value) { _userCullings[drawableIndex].IsOverwritten = value; }\n\n /// \n /// モデルの不透明度を取得する\n /// \n /// 不透明度の値\n public float GetModelOpacity() { return _modelOpacity; }\n\n /// \n /// モデルの不透明度を設定する\n /// \n /// 不透明度の値\n public void SetModelOpacity(float value) { _modelOpacity = value; }\n\n private static bool IsBitSet(byte data, byte mask) { return (data & mask) == mask; }\n\n public void SetOverwriteColorForPartMultiplyColors(int partIndex, bool value)\n {\n _userPartMultiplyColors[partIndex].IsOverwritten = value;\n SetOverwriteColorForPartColors(partIndex, value, _userPartMultiplyColors, _userMultiplyColors);\n }\n\n public void SetOverwriteColorForPartScreenColors(int partIndex, bool value)\n {\n _userPartScreenColors[partIndex].IsOverwritten = value;\n SetOverwriteColorForPartColors(partIndex, value, _userPartScreenColors, _userScreenColors);\n }\n\n /// \n /// パラメータのIDを取得する。\n /// \n /// パラメータのIndex\n /// パラメータのID\n public string GetParameterId(int parameterIndex)\n {\n if ( 0 <= parameterIndex && parameterIndex < ParameterIds.Count )\n {\n throw new IndexOutOfRangeException(\"Out of ParameterIds size\");\n }\n\n return ParameterIds[parameterIndex];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotion.cs", "using System.Text.Json;\n\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションのクラス。\n/// \npublic class CubismMotion : ACubismMotion\n{\n public const string EffectNameEyeBlink = \"EyeBlink\";\n\n public const string EffectNameLipSync = \"LipSync\";\n\n public const string TargetNameModel = \"Model\";\n\n public const string TargetNameParameter = \"Parameter\";\n\n public const string TargetNamePartOpacity = \"PartOpacity\";\n\n // Id\n public const string IdNameOpacity = \"Opacity\";\n\n /// \n /// mtnファイルで定義される一連のモーションの長さ\n /// \n private readonly float _loopDurationSeconds;\n\n /// \n /// 実際のモーションデータ本体\n /// \n private readonly CubismMotionData _motionData;\n\n /// \n /// ロードしたファイルのFPS。記述が無ければデフォルト値15fpsとなる\n /// \n private readonly float _sourceFrameRate;\n\n /**\n * Cubism SDK R2 以前のモーションを再現させるなら true 、アニメータのモーションを正しく再現するなら false 。\n */\n private readonly bool UseOldBeziersCurveMotion = false;\n\n /// \n /// 自動まばたきを適用するパラメータIDハンドルのリスト。 モデル(モデルセッティング)とパラメータを対応付ける。\n /// \n private List _eyeBlinkParameterIds;\n\n /// \n /// 最後に設定された重み\n /// \n private float _lastWeight;\n\n /// \n /// リップシンクを適用するパラメータIDハンドルのリスト。 モデル(モデルセッティング)とパラメータを対応付ける。\n /// \n private List _lipSyncParameterIds;\n\n /// \n /// モデルが持つ自動まばたき用パラメータIDのハンドル。 モデルとモーションを対応付ける。\n /// \n private string _modelCurveIdEyeBlink;\n\n /// \n /// モデルが持つリップシンク用パラメータIDのハンドル。 モデルとモーションを対応付ける。\n /// \n private string _modelCurveIdLipSync;\n\n /// \n /// モデルが持つ不透明度用パラメータIDのハンドル。 モデルとモーションを対応付ける。\n /// \n private string _modelCurveIdOpacity;\n\n /// \n /// モーションから取得した不透明度\n /// \n private float _modelOpacity;\n\n /// \n /// インスタンスを作成する。\n /// \n /// motion3.jsonが読み込まれているバッファ\n /// モーション再生終了時に呼び出されるコールバック関数。NULLの場合、呼び出されない。\n public CubismMotion(string buffer, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n _sourceFrameRate = 30.0f;\n _loopDurationSeconds = -1.0f;\n IsLoopFadeIn = true; // ループ時にフェードインが有効かどうかのフラグ\n _modelOpacity = 1.0f;\n\n using var stream = File.Open(buffer, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismMotionObjContext.Default.CubismMotionObj)\n ?? throw new Exception(\"Load Motion error\");\n\n _motionData = new CubismMotionData {\n Duration = obj.Meta.Duration,\n Loop = obj.Meta.Loop,\n CurveCount = obj.Meta.CurveCount,\n Fps = obj.Meta.Fps,\n EventCount = obj.Meta.UserDataCount,\n Curves = new CubismMotionCurve[obj.Meta.CurveCount],\n Segments = new CubismMotionSegment[obj.Meta.TotalSegmentCount],\n Points = new CubismMotionPoint[obj.Meta.TotalPointCount],\n Events = new CubismMotionEvent[obj.Meta.UserDataCount]\n };\n\n var areBeziersRestructed = obj.Meta.AreBeziersRestricted;\n\n if ( obj.Meta.FadeInTime != null )\n {\n FadeInSeconds = obj.Meta.FadeInTime < 0.0f ? 1.0f : (float)obj.Meta.FadeInTime;\n }\n else\n {\n FadeInSeconds = 1.0f;\n }\n\n if ( obj.Meta.FadeOutTime != null )\n {\n FadeOutSeconds = obj.Meta.FadeOutTime < 0.0f ? 1.0f : (float)obj.Meta.FadeOutTime;\n }\n else\n {\n FadeOutSeconds = 1.0f;\n }\n\n var totalPointCount = 0;\n var totalSegmentCount = 0;\n\n // Curves\n for ( var curveCount = 0; curveCount < _motionData.CurveCount; ++curveCount )\n {\n var item = obj.Curves[curveCount];\n var key = item.Target;\n _motionData.Curves[curveCount] = new CubismMotionCurve {\n Id = CubismFramework.CubismIdManager.GetId(item.Id),\n BaseSegmentIndex = totalSegmentCount,\n FadeInTime = item.FadeInTime != null ? (float)item.FadeInTime : -1.0f,\n FadeOutTime = item.FadeOutTime != null ? (float)item.FadeOutTime : -1.0f,\n Type = key switch {\n TargetNameModel => CubismMotionCurveTarget.Model,\n TargetNameParameter => CubismMotionCurveTarget.Parameter,\n TargetNamePartOpacity => CubismMotionCurveTarget.PartOpacity,\n _ => throw new Exception(\"Error: Unable to get segment type from Curve! The number of \\\"CurveCount\\\" may be incorrect!\")\n }\n };\n\n // Segments\n for ( var segmentPosition = 0; segmentPosition < item.Segments.Count; )\n {\n if ( segmentPosition == 0 )\n {\n _motionData.Segments[totalSegmentCount] = new CubismMotionSegment { BasePointIndex = totalPointCount };\n _motionData.Points[totalPointCount] = new CubismMotionPoint { Time = item.Segments[segmentPosition], Value = item.Segments[segmentPosition + 1] };\n\n totalPointCount += 1;\n segmentPosition += 2;\n }\n else\n {\n _motionData.Segments[totalSegmentCount] = new CubismMotionSegment { BasePointIndex = totalPointCount - 1 };\n }\n\n switch ( (CubismMotionSegmentType)item.Segments[segmentPosition] )\n {\n case CubismMotionSegmentType.Linear:\n {\n _motionData.Segments[totalSegmentCount].SegmentType = CubismMotionSegmentType.Linear;\n _motionData.Segments[totalSegmentCount].Evaluate = LinearEvaluate;\n\n _motionData.Points[totalPointCount] = new CubismMotionPoint { Time = item.Segments[segmentPosition + 1], Value = item.Segments[segmentPosition + 2] };\n\n totalPointCount += 1;\n segmentPosition += 3;\n\n break;\n }\n case CubismMotionSegmentType.Bezier:\n {\n _motionData.Segments[totalSegmentCount].SegmentType = CubismMotionSegmentType.Bezier;\n if ( areBeziersRestructed || UseOldBeziersCurveMotion )\n {\n _motionData.Segments[totalSegmentCount].Evaluate = BezierEvaluate;\n }\n else\n {\n _motionData.Segments[totalSegmentCount].Evaluate = BezierEvaluateCardanoInterpretation;\n }\n\n _motionData.Points[totalPointCount] = new CubismMotionPoint { Time = item.Segments[segmentPosition + 1], Value = item.Segments[segmentPosition + 2] };\n\n _motionData.Points[totalPointCount + 1] = new CubismMotionPoint { Time = item.Segments[segmentPosition + 3], Value = item.Segments[segmentPosition + 4] };\n\n _motionData.Points[totalPointCount + 2] = new CubismMotionPoint { Time = item.Segments[segmentPosition + 5], Value = item.Segments[segmentPosition + 6] };\n\n totalPointCount += 3;\n segmentPosition += 7;\n\n break;\n }\n case CubismMotionSegmentType.Stepped:\n {\n _motionData.Segments[totalSegmentCount].SegmentType = CubismMotionSegmentType.Stepped;\n _motionData.Segments[totalSegmentCount].Evaluate = SteppedEvaluate;\n\n _motionData.Points[totalPointCount] = new CubismMotionPoint { Time = item.Segments[segmentPosition + 1], Value = item.Segments[segmentPosition + 2] };\n\n totalPointCount += 1;\n segmentPosition += 3;\n\n break;\n }\n case CubismMotionSegmentType.InverseStepped:\n {\n _motionData.Segments[totalSegmentCount].SegmentType = CubismMotionSegmentType.InverseStepped;\n _motionData.Segments[totalSegmentCount].Evaluate = InverseSteppedEvaluate;\n\n _motionData.Points[totalPointCount] = new CubismMotionPoint { Time = item.Segments[segmentPosition + 1], Value = item.Segments[segmentPosition + 2] };\n\n totalPointCount += 1;\n segmentPosition += 3;\n\n break;\n }\n default:\n {\n throw new Exception(\"CubismMotionSegmentType error\");\n }\n }\n\n ++_motionData.Curves[curveCount].SegmentCount;\n ++totalSegmentCount;\n }\n }\n\n for ( var userdatacount = 0; userdatacount < obj.Meta.UserDataCount; ++userdatacount )\n {\n _motionData.Events[userdatacount] = new CubismMotionEvent { FireTime = obj.UserData[userdatacount].Time, Value = obj.UserData[userdatacount].Value };\n }\n\n _sourceFrameRate = _motionData.Fps;\n _loopDurationSeconds = _motionData.Duration;\n OnFinishedMotion = onFinishedMotionHandler;\n }\n\n /// \n /// ループするか?\n /// \n public bool IsLoop { get; set; }\n\n /// \n /// ループ時にフェードインが有効かどうかのフラグ。初期値では有効。\n /// \n public bool IsLoopFadeIn { get; set; }\n\n private static CubismMotionPoint LerpPoints(CubismMotionPoint a, CubismMotionPoint b, float t) { return new CubismMotionPoint { Time = a.Time + (b.Time - a.Time) * t, Value = a.Value + (b.Value - a.Value) * t }; }\n\n private static float LinearEvaluate(CubismMotionPoint[] points, int start, float time)\n {\n var t = (time - points[start].Time) / (points[start + 1].Time - points[start].Time);\n\n if ( t < 0.0f )\n {\n t = 0.0f;\n }\n\n return points[start].Value + (points[start + 1].Value - points[start].Value) * t;\n }\n\n private static float BezierEvaluate(CubismMotionPoint[] points, int start, float time)\n {\n var t = (time - points[start].Time) / (points[start + 3].Time - points[start].Time);\n\n if ( t < 0.0f )\n {\n t = 0.0f;\n }\n\n var p01 = LerpPoints(points[start], points[start + 1], t);\n var p12 = LerpPoints(points[start + 1], points[start + 2], t);\n var p23 = LerpPoints(points[start + 2], points[start + 3], t);\n\n var p012 = LerpPoints(p01, p12, t);\n var p123 = LerpPoints(p12, p23, t);\n\n return LerpPoints(p012, p123, t).Value;\n }\n\n //private static float BezierEvaluateBinarySearch(List points, int start, float time)\n //{\n // float x_error = 0.01f;\n\n // float x = time;\n // float x1 = points[0].Time;\n // float x2 = points[3].Time;\n // float cx1 = points[1].Time;\n // float cx2 = points[2].Time;\n\n // float ta = 0.0f;\n // float tb = 1.0f;\n // float t = 0.0f;\n // int i = 0;\n // for (; i < 20; ++i)\n // {\n // if (x < x1 + x_error)\n // {\n // t = ta;\n // break;\n // }\n\n // if (x2 - x_error < x)\n // {\n // t = tb;\n // break;\n // }\n\n // float centerx = (cx1 + cx2) * 0.5f;\n // cx1 = (x1 + cx1) * 0.5f;\n // cx2 = (x2 + cx2) * 0.5f;\n // float ctrlx12 = (cx1 + centerx) * 0.5f;\n // float ctrlx21 = (cx2 + centerx) * 0.5f;\n // centerx = (ctrlx12 + ctrlx21) * 0.5f;\n // if (x < centerx)\n // {\n // tb = (ta + tb) * 0.5f;\n // if (centerx - x_error < x)\n // {\n // t = tb;\n // break;\n // }\n\n // x2 = centerx;\n // cx2 = ctrlx12;\n // }\n // else\n // {\n // ta = (ta + tb) * 0.5f;\n // if (x < centerx + x_error)\n // {\n // t = ta;\n // break;\n // }\n\n // x1 = centerx;\n // cx1 = ctrlx21;\n // }\n // }\n\n // if (i == 20)\n // {\n // t = (ta + tb) * 0.5f;\n // }\n\n // if (t < 0.0f)\n // {\n // t = 0.0f;\n // }\n // if (t > 1.0f)\n // {\n // t = 1.0f;\n // }\n\n // CubismMotionPoint p01 = LerpPoints(points[start], points[start + 1], t);\n // CubismMotionPoint p12 = LerpPoints(points[start + 1], points[start + 2], t);\n // CubismMotionPoint p23 = LerpPoints(points[start + 2], points[start + 3], t);\n\n // CubismMotionPoint p012 = LerpPoints(p01, p12, t);\n // CubismMotionPoint p123 = LerpPoints(p12, p23, t);\n\n // return LerpPoints(p012, p123, t).Value;\n //}\n\n private static float BezierEvaluateCardanoInterpretation(CubismMotionPoint[] points, int start, float time)\n {\n var x = time;\n var x1 = points[start].Time;\n var x2 = points[start + 3].Time;\n var cx1 = points[start + 1].Time;\n var cx2 = points[start + 2].Time;\n\n var a = x2 - 3.0f * cx2 + 3.0f * cx1 - x1;\n var b = 3.0f * cx2 - 6.0f * cx1 + 3.0f * x1;\n var c = 3.0f * cx1 - 3.0f * x1;\n var d = x1 - x;\n\n var t = CubismMath.CardanoAlgorithmForBezier(a, b, c, d);\n\n var p01 = LerpPoints(points[start], points[start + 1], t);\n var p12 = LerpPoints(points[start + 1], points[start + 2], t);\n var p23 = LerpPoints(points[start + 2], points[start + 3], t);\n\n var p012 = LerpPoints(p01, p12, t);\n var p123 = LerpPoints(p12, p23, t);\n\n return LerpPoints(p012, p123, t).Value;\n }\n\n private static float SteppedEvaluate(CubismMotionPoint[] points, int start, float time) { return points[start].Value; }\n\n private static float InverseSteppedEvaluate(CubismMotionPoint[] points, int start, float time) { return points[start + 1].Value; }\n\n private static float EvaluateCurve(CubismMotionData motionData, int index, float time)\n {\n // Find segment to evaluate.\n var curve = motionData.Curves[index];\n\n var target = -1;\n var totalSegmentCount = curve.BaseSegmentIndex + curve.SegmentCount;\n var pointPosition = 0;\n for ( var i = curve.BaseSegmentIndex; i < totalSegmentCount; ++i )\n {\n // Get first point of next segment.\n pointPosition = motionData.Segments[i].BasePointIndex\n + (motionData.Segments[i].SegmentType ==\n CubismMotionSegmentType.Bezier\n ? 3\n : 1);\n\n // Break if time lies within current segment.\n if ( motionData.Points[pointPosition].Time > time )\n {\n target = i;\n\n break;\n }\n }\n\n if ( target == -1 )\n {\n return motionData.Points[pointPosition].Value;\n }\n\n var segment = motionData.Segments[target];\n\n return segment.Evaluate(motionData.Points, segment.BasePointIndex, time);\n }\n\n /// \n /// モデルのパラメータ更新を実行する。\n /// \n /// 対象のモデル\n /// 現在の時刻[秒]\n /// モーションの重み\n /// CubismMotionQueueManagerで管理されているモーション\n public override void DoUpdateParameters(CubismModel model, float userTimeSeconds, float fadeWeight, CubismMotionQueueEntry motionQueueEntry)\n {\n _modelCurveIdEyeBlink ??= CubismFramework.CubismIdManager.GetId(EffectNameEyeBlink);\n\n _modelCurveIdLipSync ??= CubismFramework.CubismIdManager.GetId(EffectNameLipSync);\n\n _modelCurveIdOpacity ??= CubismFramework.CubismIdManager.GetId(IdNameOpacity);\n\n var timeOffsetSeconds = userTimeSeconds - motionQueueEntry.StartTime;\n\n if ( timeOffsetSeconds < 0.0f )\n {\n timeOffsetSeconds = 0.0f; // エラー回避\n }\n\n var lipSyncValue = float.MaxValue;\n var eyeBlinkValue = float.MaxValue;\n\n //まばたき、リップシンクのうちモーションの適用を検出するためのビット(maxFlagCount個まで\n var MaxTargetSize = 64;\n ulong lipSyncFlags = 0;\n ulong eyeBlinkFlags = 0;\n\n //瞬き、リップシンクのターゲット数が上限を超えている場合\n if ( _eyeBlinkParameterIds.Count > MaxTargetSize )\n {\n CubismLog.Warning($\"[Live2D SDK]too many eye blink targets : {_eyeBlinkParameterIds.Count}\");\n }\n\n if ( _lipSyncParameterIds.Count > MaxTargetSize )\n {\n CubismLog.Warning($\"[Live2D SDK]too many lip sync targets : {_lipSyncParameterIds.Count}\");\n }\n\n var tmpFadeIn = FadeInSeconds <= 0.0f ? 1.0f : CubismMath.GetEasingSine((userTimeSeconds - motionQueueEntry.FadeInStartTime) / FadeInSeconds);\n\n var tmpFadeOut = FadeOutSeconds <= 0.0f || motionQueueEntry.EndTime < 0.0f ? 1.0f : CubismMath.GetEasingSine((motionQueueEntry.EndTime - userTimeSeconds) / FadeOutSeconds);\n\n float value;\n int c,\n parameterIndex;\n\n // 'Repeat' time as necessary.\n var time = timeOffsetSeconds;\n\n if ( IsLoop )\n {\n while ( time > _motionData.Duration )\n {\n time -= _motionData.Duration;\n }\n }\n\n var curves = _motionData.Curves;\n\n // Evaluate model curves.\n for ( c = 0; c < _motionData.CurveCount && curves[c].Type == CubismMotionCurveTarget.Model; ++c )\n {\n // Evaluate curve and call handler.\n value = EvaluateCurve(_motionData, c, time);\n\n if ( curves[c].Id == _modelCurveIdEyeBlink )\n {\n eyeBlinkValue = value;\n }\n else if ( curves[c].Id == _modelCurveIdLipSync )\n {\n lipSyncValue = value;\n }\n else if ( curves[c].Id == _modelCurveIdOpacity )\n {\n _modelOpacity = value;\n\n // ------ 不透明度の値が存在すれば反映する ------\n model.SetModelOpacity(GetModelOpacityValue());\n }\n }\n\n var parameterMotionCurveCount = 0;\n\n for ( ; c < _motionData.CurveCount && curves[c].Type == CubismMotionCurveTarget.Parameter; ++c )\n {\n parameterMotionCurveCount++;\n\n // Find parameter index.\n parameterIndex = model.GetParameterIndex(curves[c].Id);\n\n // Skip curve evaluation if no value in sink.\n if ( parameterIndex == -1 )\n {\n continue;\n }\n\n var sourceValue = model.GetParameterValue(parameterIndex);\n\n // Evaluate curve and apply value.\n value = EvaluateCurve(_motionData, c, time);\n\n if ( eyeBlinkValue != float.MaxValue )\n {\n for ( var i = 0; i < _eyeBlinkParameterIds.Count && i < MaxTargetSize; ++i )\n {\n if ( _eyeBlinkParameterIds[i] == curves[c].Id )\n {\n value *= eyeBlinkValue;\n eyeBlinkFlags |= 1UL << i;\n\n break;\n }\n }\n }\n\n if ( lipSyncValue != float.MaxValue )\n {\n for ( var i = 0; i < _lipSyncParameterIds.Count && i < MaxTargetSize; ++i )\n {\n if ( _lipSyncParameterIds[i] == curves[c].Id )\n {\n value += lipSyncValue;\n lipSyncFlags |= 1UL << i;\n\n break;\n }\n }\n }\n\n float v;\n // パラメータごとのフェード\n if ( curves[c].FadeInTime < 0.0f && curves[c].FadeOutTime < 0.0f )\n {\n //モーションのフェードを適用\n v = sourceValue + (value - sourceValue) * fadeWeight;\n }\n else\n {\n // パラメータに対してフェードインかフェードアウトが設定してある場合はそちらを適用\n float fin;\n float fout;\n\n if ( curves[c].FadeInTime < 0.0f )\n {\n fin = tmpFadeIn;\n }\n else\n {\n fin = curves[c].FadeInTime == 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((userTimeSeconds - motionQueueEntry.FadeInStartTime) / curves[c].FadeInTime);\n }\n\n if ( curves[c].FadeOutTime < 0.0f )\n {\n fout = tmpFadeOut;\n }\n else\n {\n fout = curves[c].FadeOutTime == 0.0f || motionQueueEntry.EndTime < 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((motionQueueEntry.EndTime - userTimeSeconds) / curves[c].FadeOutTime);\n }\n\n var paramWeight = Weight * fin * fout;\n\n // パラメータごとのフェードを適用\n v = sourceValue + (value - sourceValue) * paramWeight;\n }\n\n model.SetParameterValue(parameterIndex, v);\n }\n\n if ( eyeBlinkValue != float.MaxValue )\n {\n for ( var i = 0; i < _eyeBlinkParameterIds.Count && i < MaxTargetSize; ++i )\n {\n var sourceValue = model.GetParameterValue(_eyeBlinkParameterIds[i]);\n //モーションでの上書きがあった時にはまばたきは適用しない\n if ( ((eyeBlinkFlags >> i) & 0x01) != 0UL )\n {\n continue;\n }\n\n var v = sourceValue + (eyeBlinkValue - sourceValue) * fadeWeight;\n\n model.SetParameterValue(_eyeBlinkParameterIds[i], v);\n }\n }\n\n if ( lipSyncValue != float.MaxValue )\n {\n for ( var i = 0; i < _lipSyncParameterIds.Count && i < MaxTargetSize; ++i )\n {\n var sourceValue = model.GetParameterValue(_lipSyncParameterIds[i]);\n //モーションでの上書きがあった時にはリップシンクは適用しない\n if ( ((lipSyncFlags >> i) & 0x01) != 0UL )\n {\n continue;\n }\n\n var v = sourceValue + (lipSyncValue - sourceValue) * fadeWeight;\n\n model.SetParameterValue(_lipSyncParameterIds[i], v);\n }\n }\n\n for ( ; c < _motionData.CurveCount && curves[c].Type == CubismMotionCurveTarget.PartOpacity; ++c )\n {\n // Find parameter index.\n parameterIndex = model.GetParameterIndex(curves[c].Id);\n\n // Skip curve evaluation if no value in sink.\n if ( parameterIndex == -1 )\n {\n continue;\n }\n\n // Evaluate curve and apply value.\n value = EvaluateCurve(_motionData, c, time);\n\n model.SetParameterValue(parameterIndex, value);\n }\n\n if ( timeOffsetSeconds >= _motionData.Duration )\n {\n if ( IsLoop )\n {\n motionQueueEntry.StartTime = userTimeSeconds; //最初の状態へ\n if ( IsLoopFadeIn )\n {\n //ループ中でループ用フェードインが有効のときは、フェードイン設定し直し\n motionQueueEntry.FadeInStartTime = userTimeSeconds;\n }\n }\n else\n {\n OnFinishedMotion?.Invoke(model, this);\n\n motionQueueEntry.Finished = true;\n }\n }\n\n _lastWeight = fadeWeight;\n }\n\n /// \n /// モーションの長さを取得する。\n /// \n /// モーションの長さ[秒]\n public override float GetDuration() { return IsLoop ? -1.0f : _loopDurationSeconds; }\n\n /// \n /// モーションのループ時の長さを取得する。\n /// \n /// モーションのループ時の長さ[秒]\n public override float GetLoopDuration() { return _loopDurationSeconds; }\n\n /// \n /// パラメータに対するフェードインの時間を設定する。\n /// \n /// パラメータID\n /// フェードインにかかる時間[秒]\n public void SetParameterFadeInTime(string parameterId, float value)\n {\n var curves = _motionData.Curves;\n\n for ( var i = 0; i < _motionData.CurveCount; ++i )\n {\n if ( parameterId == curves[i].Id )\n {\n curves[i].FadeInTime = value;\n\n return;\n }\n }\n }\n\n /// \n /// パラメータに対するフェードアウトの時間を設定する。\n /// \n /// パラメータID\n /// フェードアウトにかかる時間[秒]\n public void SetParameterFadeOutTime(string parameterId, float value)\n {\n var curves = _motionData.Curves;\n\n for ( var i = 0; i < _motionData.CurveCount; ++i )\n {\n if ( parameterId == curves[i].Id )\n {\n curves[i].FadeOutTime = value;\n\n return;\n }\n }\n }\n\n /// \n /// パラメータに対するフェードインの時間を取得する。\n /// \n /// パラメータID\n /// フェードインにかかる時間[秒]\n public float GetParameterFadeInTime(string parameterId)\n {\n var curves = _motionData.Curves;\n\n for ( var i = 0; i < _motionData.CurveCount; ++i )\n {\n if ( parameterId == curves[i].Id )\n {\n return curves[i].FadeInTime;\n }\n }\n\n return -1;\n }\n\n /// \n /// パラメータに対するフェードアウトの時間を取得する。\n /// \n /// パラメータID\n /// フェードアウトにかかる時間[秒]\n public float GetParameterFadeOutTime(string parameterId)\n {\n var curves = _motionData.Curves;\n\n for ( var i = 0; i < _motionData.CurveCount; ++i )\n {\n if ( parameterId == curves[i].Id )\n {\n return curves[i].FadeOutTime;\n }\n }\n\n return -1;\n }\n\n /// \n /// 自動エフェクトがかかっているパラメータIDリストを設定する。\n /// \n /// 自動まばたきがかかっているパラメータIDのリスト\n /// リップシンクがかかっているパラメータIDのリスト\n public void SetEffectIds(List eyeBlinkParameterIds, List lipSyncParameterIds)\n {\n _eyeBlinkParameterIds = eyeBlinkParameterIds;\n _lipSyncParameterIds = lipSyncParameterIds;\n }\n\n /// \n /// イベント発火のチェック。\n /// 入力する時間は呼ばれるモーションタイミングを0とした秒数で行う。\n /// \n /// 前回のイベントチェック時間[秒]\n /// 今回の再生時間[秒]\n /// \n public override List GetFiredEvent(float beforeCheckTimeSeconds, float motionTimeSeconds)\n {\n FiredEventValues.Clear();\n /// イベントの発火チェック\n for ( var u = 0; u < _motionData.EventCount; ++u )\n {\n if ( _motionData.Events[u].FireTime > beforeCheckTimeSeconds &&\n _motionData.Events[u].FireTime <= motionTimeSeconds )\n {\n FiredEventValues.Add(_motionData.Events[u].Value);\n }\n }\n\n return FiredEventValues;\n }\n\n /// \n /// 透明度のカーブが存在するかどうかを確認する\n /// \n /// \n /// true . キーが存在する\n /// false . キーが存在しない\n /// \n public override bool IsExistModelOpacity()\n {\n for ( var i = 0; i < _motionData.CurveCount; i++ )\n {\n var curve = _motionData.Curves[i];\n\n if ( curve.Type != CubismMotionCurveTarget.Model )\n {\n continue;\n }\n\n if ( curve.Id == IdNameOpacity )\n {\n return true;\n }\n }\n\n return false;\n }\n\n /// \n /// 透明度のカーブのインデックスを返す\n /// \n /// 透明度のカーブのインデックス\n public override int GetModelOpacityIndex()\n {\n if ( IsExistModelOpacity() )\n {\n for ( var i = 0; i < _motionData.CurveCount; i++ )\n {\n var curve = _motionData.Curves[i];\n\n if ( curve.Type != CubismMotionCurveTarget.Model )\n {\n continue;\n }\n\n if ( curve.Id == IdNameOpacity )\n {\n return i;\n }\n }\n }\n\n return -1;\n }\n\n /// \n /// 透明度のIdを返す\n /// \n /// 透明度のId\n public override string? GetModelOpacityId(int index)\n {\n if ( index != -1 )\n {\n var curve = _motionData.Curves[index];\n\n if ( curve.Type == CubismMotionCurveTarget.Model )\n {\n if ( curve.Id == IdNameOpacity )\n {\n return CubismFramework.CubismIdManager.GetId(curve.Id);\n }\n }\n }\n\n return null;\n }\n\n /// \n /// 透明度の値を返す\n /// 更新後の値を取るにはUpdateParameters() の後に呼び出す。\n /// \n /// モーションの現在時間のOpacityの値\n public override float GetModelOpacityValue() { return _modelOpacity; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismExpressionMotion.cs", "using System.Text.Json.Nodes;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// 表情のモーションクラス。\n/// \npublic class CubismExpressionMotion : ACubismMotion\n{\n /// \n /// 加算適用の初期値\n /// \n public const float DefaultAdditiveValue = 0.0f;\n\n /// \n /// 乗算適用の初期値\n /// \n public const float DefaultMultiplyValue = 1.0f;\n\n public const string ExpressionKeyFadeIn = \"FadeInTime\";\n\n public const string ExpressionKeyFadeOut = \"FadeOutTime\";\n\n public const string ExpressionKeyParameters = \"Parameters\";\n\n public const string ExpressionKeyId = \"Id\";\n\n public const string ExpressionKeyValue = \"Value\";\n\n public const string ExpressionKeyBlend = \"Blend\";\n\n public const string BlendValueAdd = \"Add\";\n\n public const string BlendValueMultiply = \"Multiply\";\n\n public const string BlendValueOverwrite = \"Overwrite\";\n\n public const float DefaultFadeTime = 1.0f;\n\n /// \n /// インスタンスを作成する。\n /// \n /// expファイルが読み込まれているバッファ\n public CubismExpressionMotion(string buf)\n {\n using var stream = File.Open(buf, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonNode.Parse(stream) ?? throw new Exception(\"Load ExpressionMotion error\");\n var json = obj.AsObject();\n\n FadeInSeconds = json.ContainsKey(ExpressionKeyFadeIn)\n ? (float)json[ExpressionKeyFadeIn]!\n : DefaultFadeTime; // フェードイン\n\n FadeOutSeconds = json.ContainsKey(ExpressionKeyFadeOut)\n ? (float)json[ExpressionKeyFadeOut]!\n : DefaultFadeTime; // フェードアウト\n\n if ( FadeInSeconds < 0.0f )\n {\n FadeInSeconds = DefaultFadeTime;\n }\n\n if ( FadeOutSeconds < 0.0f )\n {\n FadeOutSeconds = DefaultFadeTime;\n }\n\n // 各パラメータについて\n var list = json[ExpressionKeyParameters]!;\n var parameterCount = list.AsArray().Count;\n\n for ( var i = 0; i < parameterCount; ++i )\n {\n var param = list[i]!;\n var parameterId = CubismFramework.CubismIdManager.GetId(param[ExpressionKeyId]!.ToString()); // パラメータID\n var value = (float)param[ExpressionKeyValue]!; // 値\n\n // 計算方法の設定\n ExpressionBlendType blendType;\n var type = param[ExpressionKeyBlend]?.ToString();\n if ( type == null || type == BlendValueAdd )\n {\n blendType = ExpressionBlendType.Add;\n }\n else if ( type == BlendValueMultiply )\n {\n blendType = ExpressionBlendType.Multiply;\n }\n else if ( type == BlendValueOverwrite )\n {\n blendType = ExpressionBlendType.Overwrite;\n }\n else\n {\n // その他 仕様にない値を設定したときは加算モードにすることで復旧\n blendType = ExpressionBlendType.Add;\n }\n\n // 設定オブジェクトを作成してリストに追加する\n Parameters.Add(new ExpressionParameter { ParameterId = parameterId, BlendType = blendType, Value = value });\n }\n }\n\n /// \n /// 表情のパラメータ情報リスト\n /// \n public List Parameters { get; init; } = [];\n\n /// \n /// 表情のフェードのウェイト値\n /// \n [Obsolete(\"CubismExpressionMotion._fadeWeightが削除予定のため非推奨\\nCubismExpressionMotionManager.getFadeWeight(int index) を使用してください。\")]\n public float FadeWeight { get; private set; }\n\n public override void DoUpdateParameters(CubismModel model, float userTimeSeconds, float weight, CubismMotionQueueEntry motionQueueEntry)\n {\n foreach ( var item in Parameters )\n {\n switch ( item.BlendType )\n {\n case ExpressionBlendType.Add:\n {\n model.AddParameterValue(item.ParameterId, item.Value, weight); // 相対変化 加算\n\n break;\n }\n case ExpressionBlendType.Multiply:\n {\n model.MultiplyParameterValue(item.ParameterId, item.Value, weight); // 相対変化 乗算\n\n break;\n }\n case ExpressionBlendType.Overwrite:\n {\n model.SetParameterValue(item.ParameterId, item.Value, weight); // 絶対変化 上書き\n\n break;\n }\n }\n }\n }\n\n /// \n /// モデルの表情に関するパラメータを計算する。\n /// \n /// 対象のモデル\n /// 対象のモデル\n /// CubismMotionQueueManagerで管理されているモーション\n /// モデルに適用する各パラメータの値\n /// 表情のインデックス\n public void CalculateExpressionParameters(CubismModel model, float userTimeSeconds, CubismMotionQueueEntry? motionQueueEntry,\n List? expressionParameterValues, int expressionIndex, float fadeWeight)\n {\n if ( motionQueueEntry == null || expressionParameterValues == null )\n {\n return;\n }\n\n if ( !motionQueueEntry.Available )\n {\n return;\n }\n\n // CubismExpressionMotion._fadeWeight は廃止予定です。\n // 互換性のために処理は残りますが、実際には使用しておりません。\n FadeWeight = UpdateFadeWeight(motionQueueEntry, userTimeSeconds);\n\n // モデルに適用する値を計算\n for ( var i = 0; i < expressionParameterValues.Count; ++i )\n {\n var expressionParameterValue = expressionParameterValues[i];\n\n if ( expressionParameterValue.ParameterId == null )\n {\n continue;\n }\n\n var currentParameterValue = expressionParameterValue.OverwriteValue =\n model.GetParameterValue(expressionParameterValue.ParameterId);\n\n var expressionParameters = Parameters;\n var parameterIndex = -1;\n for ( var j = 0; j < expressionParameters.Count; ++j )\n {\n if ( expressionParameterValue.ParameterId != expressionParameters[j].ParameterId )\n {\n continue;\n }\n\n parameterIndex = j;\n\n break;\n }\n\n // 再生中のExpressionが参照していないパラメータは初期値を適用\n if ( parameterIndex < 0 )\n {\n if ( expressionIndex == 0 )\n {\n expressionParameterValues[i].AdditiveValue = DefaultAdditiveValue;\n\n expressionParameterValues[i].MultiplyValue = DefaultMultiplyValue;\n\n expressionParameterValues[i].OverwriteValue = currentParameterValue;\n }\n else\n {\n expressionParameterValues[i].AdditiveValue =\n CalculateValue(expressionParameterValue.AdditiveValue, DefaultAdditiveValue, fadeWeight);\n\n expressionParameterValues[i].MultiplyValue =\n CalculateValue(expressionParameterValue.MultiplyValue, DefaultMultiplyValue, fadeWeight);\n\n expressionParameterValues[i].OverwriteValue =\n CalculateValue(expressionParameterValue.OverwriteValue, currentParameterValue, fadeWeight);\n }\n\n continue;\n }\n\n // 値を計算\n var value = expressionParameters[parameterIndex].Value;\n float newAdditiveValue,\n newMultiplyValue,\n newSetValue;\n\n switch ( expressionParameters[parameterIndex].BlendType )\n {\n case ExpressionBlendType.Add:\n newAdditiveValue = value;\n newMultiplyValue = DefaultMultiplyValue;\n newSetValue = currentParameterValue;\n\n break;\n case ExpressionBlendType.Multiply:\n newAdditiveValue = DefaultAdditiveValue;\n newMultiplyValue = value;\n newSetValue = currentParameterValue;\n\n break;\n case ExpressionBlendType.Overwrite:\n newAdditiveValue = DefaultAdditiveValue;\n newMultiplyValue = DefaultMultiplyValue;\n newSetValue = value;\n\n break;\n default:\n return;\n }\n\n if ( expressionIndex == 0 )\n {\n expressionParameterValues[i].AdditiveValue = newAdditiveValue;\n expressionParameterValues[i].MultiplyValue = newMultiplyValue;\n expressionParameterValues[i].OverwriteValue = newSetValue;\n }\n else\n {\n expressionParameterValues[i].AdditiveValue = expressionParameterValue.AdditiveValue * (1.0f - FadeWeight) + newAdditiveValue * FadeWeight;\n expressionParameterValues[i].MultiplyValue = expressionParameterValue.MultiplyValue * (1.0f - FadeWeight) + newMultiplyValue * FadeWeight;\n expressionParameterValues[i].OverwriteValue = expressionParameterValue.OverwriteValue * (1.0f - FadeWeight) + newSetValue * FadeWeight;\n }\n }\n }\n\n private float CalculateValue(float source, float destination, float fadeWeight) { return source * (1.0f - fadeWeight) + destination * fadeWeight; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismExpressionMotionManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// パラメータに適用する表情の値を持たせる構造体\n/// \npublic record ExpressionParameterValue\n{\n /// \n /// 加算値\n /// \n public float AdditiveValue;\n\n /// \n /// 乗算値\n /// \n public float MultiplyValue;\n\n /// \n /// 上書き値\n /// \n public float OverwriteValue;\n\n /// \n /// パラメータID\n /// \n public string ParameterId;\n}\n\npublic class CubismExpressionMotionManager : CubismMotionQueueManager\n{\n // モデルに適用する各パラメータの値\n private readonly List _expressionParameterValues = [];\n\n // 再生中の表情のウェイト\n private readonly List _fadeWeights = [];\n\n /// \n /// 現在再生中のモーションの優先度\n /// \n public MotionPriority CurrentPriority { get; private set; }\n\n /// \n /// 再生予定のモーションの優先度。再生中は0になる。モーションファイルを別スレッドで読み込むときの機能。\n /// \n public MotionPriority ReservePriority { get; set; }\n\n /// \n /// 優先度を設定して表情モーションを開始する。\n /// \n /// モーション\n /// 優先度\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotionPriority(ACubismMotion motion, MotionPriority priority)\n {\n if ( priority == ReservePriority )\n {\n ReservePriority = 0; // 予約を解除\n }\n\n CurrentPriority = priority; // 再生中モーションの優先度を設定\n\n _fadeWeights.Add(0.0f);\n\n return StartMotion(motion, UserTimeSeconds);\n }\n\n /// \n /// 表情モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// \n /// true 更新されている\n /// false 更新されていない\n /// \n public bool UpdateMotion(CubismModel model, float deltaTimeSeconds)\n {\n UserTimeSeconds += deltaTimeSeconds;\n var updated = false;\n var motions = Motions;\n\n var expressionWeight = 0.0f;\n var expressionIndex = 0;\n\n // If there is already a motion, set the end flag\n var list = new List();\n foreach ( var item in motions )\n {\n if ( item.Motion is not CubismExpressionMotion expressionMotion )\n {\n list.Add(item);\n\n continue;\n }\n\n var expressionParameters = expressionMotion.Parameters;\n if ( item.Available )\n {\n // 再生中のExpressionが参照しているパラメータをすべてリストアップ\n for ( var i = 0; i < expressionParameters.Count; ++i )\n {\n if ( expressionParameters[i].ParameterId == null )\n {\n continue;\n }\n\n var index = -1;\n // リストにパラメータIDが存在するか検索\n for ( var j = 0; j < _expressionParameterValues.Count; ++j )\n {\n if ( _expressionParameterValues[j].ParameterId != expressionParameters[i].ParameterId )\n {\n continue;\n }\n\n index = j;\n\n break;\n }\n\n if ( index >= 0 )\n {\n continue;\n }\n\n // If the parameter does not exist in the list, add it.\n ExpressionParameterValue item1 = new() { ParameterId = expressionParameters[i].ParameterId, AdditiveValue = CubismExpressionMotion.DefaultAdditiveValue, MultiplyValue = CubismExpressionMotion.DefaultMultiplyValue };\n item1.OverwriteValue = model.GetParameterValue(item1.ParameterId);\n _expressionParameterValues.Add(item1);\n }\n }\n \n // ------ 値を計算する ------\n expressionMotion.SetupMotionQueueEntry(item, UserTimeSeconds);\n _fadeWeights[expressionIndex] = expressionMotion.UpdateFadeWeight(item, UserTimeSeconds);\n expressionMotion.CalculateExpressionParameters(model, UserTimeSeconds,\n item, _expressionParameterValues, expressionIndex, _fadeWeights[expressionIndex]);\n\n expressionWeight += expressionMotion.FadeInSeconds == 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((UserTimeSeconds - item.FadeInStartTime) / expressionMotion.FadeInSeconds);\n\n updated = true;\n\n if ( item.IsTriggeredFadeOut )\n {\n // フェードアウト開始\n item.StartFadeout(item.FadeOutSeconds, UserTimeSeconds);\n }\n\n ++expressionIndex;\n }\n\n // ----- 最新のExpressionのフェードが完了していればそれ以前を削除する ------\n if ( motions.Count > 1 )\n {\n var latestFadeWeight = _fadeWeights[_fadeWeights.Count - 1];\n if ( latestFadeWeight >= 1.0f )\n {\n // 配列の最後の要素は削除しない\n for ( var i = motions.Count - 2; i >= 0; i-- )\n {\n motions.RemoveAt(i);\n _fadeWeights.RemoveAt(i);\n }\n }\n }\n\n if ( expressionWeight > 1.0f )\n {\n expressionWeight = 1.0f;\n }\n\n // モデルに各値を適用\n for ( var i = 0; i < _expressionParameterValues.Count; ++i )\n {\n model.SetParameterValue(_expressionParameterValues[i].ParameterId,\n (_expressionParameterValues[i].OverwriteValue + _expressionParameterValues[i].AdditiveValue) * _expressionParameterValues[i].MultiplyValue,\n expressionWeight);\n\n _expressionParameterValues[i].AdditiveValue = CubismExpressionMotion.DefaultAdditiveValue;\n _expressionParameterValues[i].MultiplyValue = CubismExpressionMotion.DefaultMultiplyValue;\n }\n\n return updated;\n }\n\n /// \n /// 現在の表情のフェードのウェイト値を取得する。\n /// \n /// 取得する表情モーションのインデックス\n /// 表情のフェードのウェイト値\n public float GetFadeWeight(int index) { return _fadeWeights[index]; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppModel.cs", "using System.Text.Json;\n\nusing PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Effect;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\npublic class LAppModel : CubismUserModel\n{\n /// \n /// 読み込まれている表情のリスト\n /// \n private readonly Dictionary _expressions = [];\n\n /// \n /// モデルに設定されたまばたき機能用パラメータID\n /// \n private readonly List _eyeBlinkIds = [];\n\n private readonly LAppDelegate _lapp;\n\n /// \n /// モデルに設定されたリップシンク機能用パラメータID\n /// \n private readonly List _lipSyncIds = [];\n\n /// \n /// モデルセッティングが置かれたディレクトリ\n /// \n private readonly string _modelHomeDir;\n\n /// \n /// モデルセッティング情報\n /// \n private readonly ModelSettingObj _modelSetting;\n\n /// \n /// 読み込まれているモーションのリスト\n /// \n private readonly Dictionary _motions = [];\n\n private readonly Random _random = new();\n\n /// \n /// wavファイルハンドラ\n /// \n public LAppWavFileHandler _wavFileHandler = new();\n\n public static string GetMotionGroupName(string motionName)\n {\n var underscoreIndex = motionName.LastIndexOf('_');\n if ( underscoreIndex > 0 && int.TryParse(motionName.AsSpan(underscoreIndex + 1), out _) )\n {\n return motionName[..underscoreIndex];\n }\n\n return motionName; // Treat whole name as group if no \"_Number\" suffix\n }\n \n public Action? ValueUpdate;\n\n public LAppModel(LAppDelegate lapp, string dir, string fileName)\n {\n _lapp = lapp;\n\n if ( LAppDefine.MocConsistencyValidationEnable )\n {\n _mocConsistency = true;\n }\n\n IdParamAngleX = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamAngleX);\n\n IdParamAngleY = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamAngleY);\n\n IdParamAngleZ = CubismFramework.CubismIdManager.GetId(CubismDefaultParameterId.ParamAngleZ);\n IdParamBodyAngleX = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamBodyAngleX);\n\n IdParamEyeBallX = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamEyeBallX);\n\n IdParamEyeBallY = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamEyeBallY);\n\n _modelHomeDir = dir;\n\n CubismLog.Debug($\"[Live2D]load model setting: {fileName}\");\n\n using var stream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n\n _modelSetting = JsonSerializer.Deserialize(stream, ModelSettingObjContext.Default.ModelSettingObj)\n ?? throw new Exception(\"model3.json error\");\n\n Updating = true;\n Initialized = false;\n\n //Cubism Model\n var path = _modelSetting.FileReferences?.Moc;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( !File.Exists(path) )\n {\n throw new Exception(\"model is null\");\n }\n\n CubismLog.Debug($\"[Live2D]create model: {path}\");\n\n LoadModel(File.ReadAllBytes(path), _mocConsistency);\n }\n\n //Expression\n if ( _modelSetting.FileReferences?.Expressions?.Count > 0 )\n {\n for ( var i = 0; i < _modelSetting.FileReferences.Expressions.Count; i++ )\n {\n var item = _modelSetting.FileReferences.Expressions[i];\n var name = item.Name;\n path = item.File;\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( !File.Exists(path) )\n {\n continue;\n }\n\n var motion = new CubismExpressionMotion(path);\n\n if ( _expressions.ContainsKey(name) )\n {\n _expressions[name] = motion;\n }\n else\n {\n _expressions.Add(name, motion);\n }\n }\n }\n\n //Physics\n path = _modelSetting.FileReferences?.Physics;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( File.Exists(path) )\n {\n LoadPhysics(path);\n }\n }\n\n //Pose\n path = _modelSetting.FileReferences?.Pose;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( File.Exists(path) )\n {\n LoadPose(path);\n }\n }\n\n //EyeBlink\n if ( _modelSetting.IsExistEyeBlinkParameters() )\n {\n _eyeBlink = new CubismEyeBlink(_modelSetting);\n }\n\n LoadBreath();\n\n //UserData\n path = _modelSetting.FileReferences?.UserData;\n if ( !string.IsNullOrWhiteSpace(path) )\n {\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( File.Exists(path) )\n {\n LoadUserData(path);\n }\n }\n\n // EyeBlinkIds\n if ( _eyeBlink != null )\n {\n _eyeBlinkIds.AddRange(_eyeBlink.ParameterIds);\n }\n\n // LipSyncIds\n if ( _modelSetting.IsExistLipSyncParameters() )\n {\n foreach ( var item in _modelSetting.Groups )\n {\n if ( item.Name == CubismModelSettingJson.LipSync )\n {\n _lipSyncIds.AddRange(item.Ids);\n }\n }\n }\n\n //Layout\n Dictionary layout = [];\n _modelSetting.GetLayoutMap(layout);\n ModelMatrix.SetupFromLayout(layout);\n\n Model.SaveParameters();\n\n if ( _modelSetting.FileReferences?.Motions?.Count > 0 )\n {\n foreach ( var item in _modelSetting.FileReferences.Motions )\n {\n PreloadMotionGroup(item.Key);\n }\n }\n\n _motionManager.StopAllMotions();\n\n Updating = false;\n Initialized = true;\n\n CreateRenderer(new CubismRenderer_OpenGLES2(_lapp.GL, Model));\n\n SetupTextures();\n }\n\n public List Motions => new(_motions.Keys);\n\n public List Expressions => new(_expressions.Keys);\n\n public List<(string, int, float)> Parts\n {\n get\n {\n var list = new List<(string, int, float)>();\n var count = Model.GetPartCount();\n for ( var a = 0; a < count; a++ )\n {\n list.Add((Model.GetPartId(a),\n a, Model.GetPartOpacity(a)));\n }\n\n return list;\n }\n }\n\n public List Parameters => new(Model.ParameterIds);\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n public float UserTimeSeconds { get; set; }\n\n public bool RandomMotion { get; set; } = true;\n\n public bool CustomValueUpdate { get; set; }\n\n /// \n /// パラメータID: ParamAngleX\n /// \n public string IdParamAngleX { get; set; }\n\n /// \n /// パラメータID: ParamAngleY\n /// \n public string IdParamAngleY { get; set; }\n\n /// \n /// パラメータID: ParamAngleZ\n /// \n public string IdParamAngleZ { get; set; }\n\n /// \n /// パラメータID: ParamBodyAngleX\n /// \n public string IdParamBodyAngleX { get; set; }\n\n /// \n /// パラメータID: ParamEyeBallX\n /// \n public string IdParamEyeBallX { get; set; }\n\n /// \n /// パラメータID: ParamEyeBallXY\n /// \n public string IdParamEyeBallY { get; set; }\n\n public string IdParamBreath { get; set; } = CubismFramework.CubismIdManager\n .GetId(CubismDefaultParameterId.ParamBreath);\n\n public event Action? Motion;\n\n public new void Dispose()\n {\n base.Dispose();\n\n _motions.Clear();\n _expressions.Clear();\n\n if ( _modelSetting.FileReferences?.Motions.Count > 0 )\n {\n foreach ( var item in _modelSetting.FileReferences.Motions )\n {\n ReleaseMotionGroup(item.Key);\n }\n }\n }\n\n public void LoadBreath()\n {\n //Breath\n _breath = new CubismBreath {\n Parameters = [\n new BreathParameterData {\n ParameterId = IdParamAngleX,\n Offset = 0.0f,\n Peak = 15.0f,\n Cycle = 6.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamAngleY,\n Offset = 0.0f,\n Peak = 8.0f,\n Cycle = 3.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamAngleZ,\n Offset = 0.0f,\n Peak = 10.0f,\n Cycle = 5.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamBodyAngleX,\n Offset = 0.0f,\n Peak = 4.0f,\n Cycle = 15.5345f,\n Weight = 0.5f\n },\n new BreathParameterData {\n ParameterId = IdParamBreath,\n Offset = 0.5f,\n Peak = 0.5f,\n Cycle = 3.2345f,\n Weight = 0.5f\n }\n ]\n };\n }\n\n /// \n /// レンダラを再構築する\n /// \n public void ReloadRenderer()\n {\n DeleteRenderer();\n\n CreateRenderer(new CubismRenderer_OpenGLES2(_lapp.GL, Model));\n\n SetupTextures();\n }\n\n /// \n /// モデルの更新処理。モデルのパラメータから描画状態を決定する。\n /// \n public void Update()\n {\n var deltaTimeSeconds = LAppPal.DeltaTime;\n UserTimeSeconds += deltaTimeSeconds;\n\n _dragManager.Update(deltaTimeSeconds);\n _dragX = _dragManager.FaceX;\n _dragY = _dragManager.FaceY;\n\n // モーションによるパラメータ更新の有無\n var motionUpdated = false;\n\n //-----------------------------------------------------------------\n Model.LoadParameters(); // 前回セーブされた状態をロード\n if ( _motionManager.IsFinished() && RandomMotion )\n {\n // モーションの再生がない場合、待機モーションの中からランダムで再生する\n StartRandomMotion(LAppDefine.MotionGroupIdle, MotionPriority.PriorityIdle);\n }\n else\n {\n motionUpdated = _motionManager.UpdateMotion(Model, deltaTimeSeconds); // モーションを更新\n }\n\n Model.SaveParameters(); // 状態を保存\n\n //-----------------------------------------------------------------\n\n // 不透明度\n Opacity = Model.GetModelOpacity();\n\n // まばたき\n if ( !motionUpdated )\n {\n // メインモーションの更新がないとき\n // _eyeBlink?.UpdateParameters(Model, deltaTimeSeconds); // 目パチ\n }\n\n _expressionManager?.UpdateMotion(Model, deltaTimeSeconds); // 表情でパラメータ更新(相対変化)\n\n if ( CustomValueUpdate )\n {\n ValueUpdate?.Invoke(this);\n }\n else\n {\n //ドラッグによる変化\n //ドラッグによる顔の向きの調整\n Model.AddParameterValue(IdParamAngleX, _dragX * 30); // -30から30の値を加える\n Model.AddParameterValue(IdParamAngleY, _dragY * 30);\n Model.AddParameterValue(IdParamAngleZ, _dragX * _dragY * -30);\n\n //ドラッグによる体の向きの調整\n Model.AddParameterValue(IdParamBodyAngleX, _dragX * 10); // -10から10の値を加える\n\n //ドラッグによる目の向きの調整\n Model.AddParameterValue(IdParamEyeBallX, _dragX); // -1から1の値を加える\n Model.AddParameterValue(IdParamEyeBallY, _dragY);\n }\n\n // 呼吸など\n // _breath?.UpdateParameters(Model, deltaTimeSeconds);\n\n // 物理演算の設定\n _physics?.Evaluate(Model, deltaTimeSeconds);\n\n // リップシンクの設定\n // if ( _lipSync )\n // {\n // // リアルタイムでリップシンクを行う場合、システムから音量を取得して0〜1の範囲で値を入力します。\n // var value = 0.0f;\n //\n // // 状態更新/RMS値取得\n // _wavFileHandler.Update(deltaTimeSeconds);\n // value = (float)_wavFileHandler.GetRms();\n //\n // var weight = 3f; // Configure it as needed.\n //\n // for ( var i = 0; i < _lipSyncIds.Count; ++i )\n // {\n // Model.SetParameterValue(_lipSyncIds[i], value * weight);\n // }\n // }\n\n // ポーズの設定\n _pose?.UpdateParameters(Model, deltaTimeSeconds);\n\n Model.Update();\n }\n\n /// \n /// モデルを描画する処理。モデルを描画する空間のView-Projection行列を渡す。\n /// \n /// View-Projection行列\n public void Draw(CubismMatrix44 matrix)\n {\n if ( Model == null )\n {\n return;\n }\n\n matrix.MultiplyByMatrix(ModelMatrix);\n if ( Renderer is CubismRenderer_OpenGLES2 ren )\n {\n ren.ClearColor = _lapp.BGColor;\n ren.SetMvpMatrix(matrix);\n }\n\n DoDraw();\n }\n\n /// \n /// Starts playing the motion specified by the argument.\n /// \n /// Motion Group Name\n /// Number in group\n /// Priority\n /// The callback function that is called when the motion playback ends. If NULL, it will not be called.\n /// Returns the identification number of the started motion. Used as an argument for IsFinished() to determine whether an individual motion has finished. Returns \"-1\" if the motion cannot be started.\n public CubismMotionQueueEntry? StartMotion(string name, MotionPriority priority, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n var temp = name.Split(\"_\");\n if ( temp.Length != 2 )\n {\n throw new Exception(\"motion name error\");\n }\n\n return StartMotion(temp[0], int.Parse(temp[1]), priority, onFinishedMotionHandler);\n }\n\n public CubismMotionQueueEntry? StartMotion(string group, int no, MotionPriority priority, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n if ( priority == MotionPriority.PriorityForce )\n {\n _motionManager.ReservePriority = priority;\n }\n else if ( !_motionManager.ReserveMotion(priority) )\n {\n CubismLog.Debug(\"[Live2D]can't start motion.\");\n\n return null;\n }\n\n var item = _modelSetting.FileReferences.Motions[group][no];\n\n //ex) idle_0\n var name = $\"{group}_{no}\";\n\n CubismMotion motion;\n if ( !_motions.TryGetValue(name, out var value) )\n {\n var path = item.File;\n path = Path.GetFullPath(_modelHomeDir + path);\n if ( !File.Exists(path) )\n {\n return null;\n }\n\n motion = new CubismMotion(path, onFinishedMotionHandler);\n var fadeTime = item.FadeInTime;\n if ( fadeTime >= 0.0f )\n {\n motion.FadeInSeconds = fadeTime;\n }\n\n fadeTime = item.FadeOutTime;\n if ( fadeTime >= 0.0f )\n {\n motion.FadeOutSeconds = fadeTime;\n }\n\n motion.SetEffectIds(_eyeBlinkIds, _lipSyncIds);\n }\n else\n {\n motion = (value as CubismMotion)!;\n motion.OnFinishedMotion = onFinishedMotionHandler;\n }\n\n //voice\n var voice = item.Sound;\n if ( !string.IsNullOrWhiteSpace(voice) )\n {\n var path = voice;\n path = _modelHomeDir + path;\n _wavFileHandler.Start(path);\n }\n\n CubismLog.Debug($\"[Live2D]start motion: [{group}_{no}]\");\n\n return _motionManager.StartMotionPriority(motion, priority);\n }\n\n /// \n /// Starts playing a randomly selected motion.\n /// \n /// Motion Group Name\n /// Priority\n /// A callback function that is called when the priority motion playback ends. If NULL, it will not be called.\n /// Returns the identification number of the started motion. Used as an argument for IsFinished() to determine whether an individual motion has finished. Returns \"-1\" if the motion cannot be started.\n public CubismMotionQueueEntry? StartRandomMotion(string group, MotionPriority priority, FinishedMotionCallback? onFinishedMotionHandler = null)\n {\n if ( _modelSetting.FileReferences?.Motions?.ContainsKey(group) == true )\n {\n var no = _random.Next() % _modelSetting.FileReferences.Motions[group].Count;\n\n return StartMotion(group, no, priority, onFinishedMotionHandler);\n }\n\n return null;\n }\n \n public bool IsMotionFinished(CubismMotionQueueEntry entry)\n {\n return _motionManager.IsFinished(entry);\n }\n\n /// \n /// Sets the facial motion specified by the argument.\n /// \n /// Facial expression motion ID\n public void SetExpression(string expressionID)\n {\n var motion = _expressions[expressionID];\n CubismLog.Debug($\"[Live2D]expression: [{expressionID}]\");\n\n if ( motion != null )\n {\n _expressionManager.StartMotionPriority(motion, MotionPriority.PriorityForce);\n }\n else\n {\n CubismLog.Debug($\"[Live2D]expression[{expressionID}] is null \");\n }\n }\n\n /// \n /// Set a randomly selected facial expression motion\n /// \n public void SetRandomExpression()\n {\n if ( _expressions.Count == 0 )\n {\n return;\n }\n\n var no = _random.Next() % _expressions.Count;\n var i = 0;\n foreach ( var item in _expressions )\n {\n if ( i == no )\n {\n SetExpression(item.Key);\n\n return;\n }\n\n i++;\n }\n }\n\n /// \n /// イベントの発火を受け取る\n /// \n /// \n protected override void MotionEventFired(string eventValue)\n {\n CubismLog.Debug($\"[Live2D]{eventValue} is fired on LAppModel!!\");\n Motion?.Invoke(this, eventValue);\n }\n\n /// \n /// 当たり判定テスト。\n /// 指定IDの頂点リストから矩形を計算し、座標が矩形範囲内か判定する。\n /// \n /// 当たり判定をテストする対象のID\n /// 判定を行うX座標\n /// 判定を行うY座標\n /// \n public bool HitTest(string hitAreaName, float x, float y)\n {\n // 透明時は当たり判定なし。\n if ( Opacity < 1 )\n {\n return false;\n }\n\n if ( _modelSetting.HitAreas?.Count > 0 )\n {\n for ( var i = 0; i < _modelSetting.HitAreas?.Count; i++ )\n {\n if ( _modelSetting.HitAreas[i].Name == hitAreaName )\n {\n var id = CubismFramework.CubismIdManager.GetId(_modelSetting.HitAreas[i].Id);\n\n return IsHit(id, x, y);\n }\n }\n }\n\n return false; // 存在しない場合はfalse\n }\n\n /// \n /// モデルを描画する処理。モデルを描画する空間のView-Projection行列を渡す。\n /// \n protected void DoDraw()\n {\n if ( Model == null )\n {\n return;\n }\n\n (Renderer as CubismRenderer_OpenGLES2)?.DrawModel();\n }\n\n /// \n /// モーションデータをグループ名から一括で解放する。\n /// モーションデータの名前は内部でModelSettingから取得する。\n /// \n /// モーションデータのグループ名\n private void ReleaseMotionGroup(string group)\n {\n var list = _modelSetting.FileReferences.Motions[group];\n for ( var i = 0; i < list.Count; i++ )\n {\n var voice = list[i].Sound;\n }\n }\n\n /// \n /// OpenGLのテクスチャユニットにテクスチャをロードする\n /// \n private void SetupTextures()\n {\n if ( _modelSetting.FileReferences?.Textures?.Count > 0 )\n {\n for ( var modelTextureNumber = 0; modelTextureNumber < _modelSetting.FileReferences.Textures.Count; modelTextureNumber++ )\n {\n //OpenGLのテクスチャユニットにテクスチャをロードする\n var texturePath = _modelSetting.FileReferences.Textures[modelTextureNumber];\n if ( string.IsNullOrWhiteSpace(texturePath) )\n {\n continue;\n }\n\n texturePath = Path.GetFullPath(_modelHomeDir + texturePath);\n\n var texture = _lapp.TextureManager.CreateTextureFromPngFile(texturePath);\n var glTextueNumber = texture.ID;\n\n //OpenGL\n (Renderer as CubismRenderer_OpenGLES2)?.BindTexture(modelTextureNumber, glTextueNumber);\n }\n }\n }\n\n /// \n /// モーションデータをグループ名から一括でロードする。\n /// モーションデータの名前は内部でModelSettingから取得する。\n /// \n /// モーションデータのグループ名\n private void PreloadMotionGroup(string group)\n {\n // グループに登録されているモーション数を取得\n var list = _modelSetting.FileReferences.Motions[group];\n\n for ( var i = 0; i < list.Count; i++ )\n {\n var item = list[i];\n //ex) idle_0\n // モーションのファイル名とパスの取得\n var name = $\"{group}_{i}\";\n var path = Path.GetFullPath(_modelHomeDir + item.File);\n\n // モーションデータの読み込み\n var tmpMotion = new CubismMotion(path);\n\n // フェードインの時間を取得\n var fadeTime = item.FadeInTime;\n if ( fadeTime >= 0.0f )\n {\n tmpMotion.FadeInSeconds = fadeTime;\n }\n\n // フェードアウトの時間を取得\n fadeTime = item.FadeOutTime;\n if ( fadeTime >= 0.0f )\n {\n tmpMotion.FadeOutSeconds = fadeTime;\n }\n\n tmpMotion.SetEffectIds(_eyeBlinkIds, _lipSyncIds);\n\n if ( _motions.ContainsKey(name) )\n {\n _motions[name] = tmpMotion;\n }\n else\n {\n _motions.Add(name, tmpMotion);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionQueueManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーション再生の管理用クラス。CubismMotionモーションなどACubismMotionのサブクラスを再生するために使用する。\n/// 再生中に別のモーションが StartMotion()された場合は、新しいモーションに滑らかに変化し旧モーションは中断する。\n/// 表情用モーション、体用モーションなどを分けてモーション化した場合など、\n/// 複数のモーションを同時に再生させる場合は、複数のCubismMotionQueueManagerインスタンスを使用する。\n/// \npublic class CubismMotionQueueManager\n{\n private readonly List _remove = [];\n\n /// \n /// モーション\n /// \n protected readonly List Motions = [];\n\n /// \n /// コールバック関数ポインタ\n /// \n private CubismMotionEventFunction? _eventCallback;\n\n /// \n /// コールバックに戻されるデータ\n /// \n private CubismUserModel? _eventCustomData;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n protected float UserTimeSeconds;\n\n /// \n /// 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。\n /// \n /// 開始するモーション\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotion(ACubismMotion motion)\n {\n CubismMotionQueueEntry motionQueueEntry;\n\n // 既にモーションがあれば終了フラグを立てる\n for ( var i = 0; i < Motions.Count; ++i )\n {\n motionQueueEntry = Motions[0];\n if ( motionQueueEntry == null )\n {\n continue;\n }\n\n motionQueueEntry.SetFadeout(motionQueueEntry.Motion.FadeOutSeconds);\n }\n\n motionQueueEntry = new CubismMotionQueueEntry { Motion = motion };\n\n Motions.Add(motionQueueEntry);\n\n return motionQueueEntry;\n }\n\n /// \n /// 指定したモーションを開始する。同じタイプのモーションが既にある場合は、既存のモーションに終了フラグを立て、フェードアウトを開始させる。\n /// \n /// 開始するモーション\n /// 再生が終了したモーションのインスタンスを削除するなら true\n /// デルタ時間の積算値[秒]\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n [Obsolete(\"Please use StartMotion(ACubismMotion motion\")]\n public CubismMotionQueueEntry StartMotion(ACubismMotion motion, float userTimeSeconds)\n {\n CubismLog.Warning(\"StartMotion(ACubismMotion motion, float userTimeSeconds) is a deprecated function. Please use StartMotion(ACubismMotion motion).\");\n\n CubismMotionQueueEntry motionQueueEntry;\n\n // 既にモーションがあれば終了フラグを立てる\n for ( var i = 0; i < Motions.Count; ++i )\n {\n motionQueueEntry = Motions[i];\n if ( motionQueueEntry == null )\n {\n continue;\n }\n\n motionQueueEntry.SetFadeout(motionQueueEntry.Motion.FadeOutSeconds);\n }\n\n motionQueueEntry = new CubismMotionQueueEntry { Motion = motion }; // 終了時に破棄する\n\n Motions.Add(motionQueueEntry);\n\n return motionQueueEntry;\n }\n\n /// \n /// すべてのモーションが終了しているかどうか。\n /// \n /// \n /// true すべて終了している\n /// false 終了していない\n /// \n public bool IsFinished()\n {\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n foreach ( var item in Motions )\n {\n // ----- 終了済みの処理があれば削除する ------\n if ( !item.Finished )\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// 指定したモーションが終了しているかどうか。\n /// \n /// モーションの識別番号\n /// \n /// true 指定したモーションは終了している\n /// false 終了していない\n /// \n public bool IsFinished(object motionQueueEntryNumber)\n {\n // 既にモーションがあれば終了フラグを立てる\n\n foreach ( var item in Motions )\n {\n if ( item == null )\n {\n continue;\n }\n\n if ( item == motionQueueEntryNumber && !item.Finished )\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// すべてのモーションを停止する。\n /// \n public void StopAllMotions()\n {\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n\n Motions.Clear();\n }\n\n /// \n /// 指定したCubismMotionQueueEntryを取得する。\n /// \n /// モーションの識別番号\n /// \n /// 指定したCubismMotionQueueEntryへのポインタ\n /// NULL 見つからなかった\n /// \n public CubismMotionQueueEntry? GetCubismMotionQueueEntry(object motionQueueEntryNumber)\n {\n //------- 処理を行う --------\n //既にモーションがあれば終了フラグを立てる\n\n foreach ( var item in Motions )\n {\n if ( item == motionQueueEntryNumber )\n {\n return item;\n }\n }\n\n return null;\n }\n\n /// \n /// イベントを受け取るCallbackの登録をする。\n /// \n /// コールバック関数\n /// コールバックに返されるデータ\n public void SetEventCallback(CubismMotionEventFunction callback, CubismUserModel customData)\n {\n _eventCallback = callback;\n _eventCustomData = customData;\n }\n\n /// \n /// モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間の積算値[秒]\n /// \n /// true モデルへパラメータ値の反映あり\n /// false モデルへパラメータ値の反映なし(モーションの変化なし)\n /// \n public virtual bool DoUpdateMotion(CubismModel model, float userTimeSeconds)\n {\n var updated = false;\n\n // ------- 処理を行う --------\n // 既にモーションがあれば終了フラグを立てる\n\n _remove.Clear();\n\n for ( var motionIndex = Motions.Count - 1; motionIndex >= 0; motionIndex-- )\n {\n var item = Motions[motionIndex];\n var motion = item.Motion;\n\n // ------ 値を反映する ------\n motion.UpdateParameters(model, item, userTimeSeconds);\n updated = true;\n\n // ------ ユーザトリガーイベントを検査する ----\n var firedList = motion.GetFiredEvent(\n item.LastEventCheckSeconds - item.StartTime,\n userTimeSeconds - item.StartTime);\n\n for ( var i = 0; i < firedList.Count; ++i )\n {\n _eventCallback?.Invoke(_eventCustomData, firedList[i]);\n }\n\n item.LastEventCheckSeconds = userTimeSeconds;\n\n // ----- 終了済みの処理があれば削除する ------\n if ( item.Finished )\n {\n _remove.Add(item); // 削除\n }\n else\n {\n if ( item.IsTriggeredFadeOut )\n {\n item.StartFadeout(item.FadeOutSeconds, userTimeSeconds);\n }\n }\n }\n\n foreach ( var item in _remove )\n {\n Motions.Remove(item);\n }\n\n return updated;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismClippingManager.cs", "using System.Numerics;\n\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\nusing PersonaEngine.Lib.Live2D.Framework.Type;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic class CubismClippingManager\n{\n /// \n /// 実験時に1チャンネルの場合は1、RGBだけの場合は3、アルファも含める場合は4\n /// \n public const int ColorChannelCount = 4;\n\n /// \n /// 通常のフレームバッファ1枚あたりのマスク最大数\n /// \n public const int ClippingMaskMaxCountOnDefault = 36;\n\n /// \n /// フレームバッファが2枚以上ある場合のフレームバッファ1枚あたりのマスク最大数\n /// \n public const int ClippingMaskMaxCountOnMultiRenderTexture = 32;\n\n private readonly RenderType _renderType;\n\n protected List ChannelColors = [];\n\n /// \n /// マスクのクリアフラグの配列\n /// \n protected List ClearedMaskBufferFlags = [];\n\n /// \n /// マスク用クリッピングコンテキストのリスト\n /// \n protected List ClippingContextListForMask = [];\n\n /// \n /// オフスクリーンサーフェイスのアドレス\n /// \n protected CubismOffscreenSurface_OpenGLES2 CurrentMaskBuffer;\n\n /// \n /// マスク配置計算用の矩形\n /// \n protected RectF TmpBoundsOnModel = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrix = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrixForDraw = new();\n\n /// \n /// マスク計算用の行列\n /// \n protected CubismMatrix44 TmpMatrixForMask = new();\n\n public CubismClippingManager(RenderType render)\n {\n _renderType = render;\n ClippingMaskBufferSize = new Vector2(256, 256);\n\n ChannelColors.Add(new CubismTextureColor(1.0f, 0f, 0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 1.0f, 0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 0f, 1.0f, 0f));\n ChannelColors.Add(new CubismTextureColor(0f, 0f, 0f, 1.0f));\n }\n\n /// \n /// 描画用クリッピングコンテキストのリスト\n /// \n public List ClippingContextListForDraw { get; init; } = [];\n\n /// \n /// クリッピングマスクのバッファサイズ(初期値:256)\n /// \n public Vector2 ClippingMaskBufferSize { get; private set; }\n\n /// \n /// 生成するレンダーテクスチャの枚数\n /// \n public int RenderTextureCount { get; private set; }\n\n public void Close()\n {\n ClippingContextListForDraw.Clear();\n ClippingContextListForMask.Clear();\n ChannelColors.Clear();\n ClearedMaskBufferFlags.Clear();\n }\n\n /// \n /// マネージャの初期化処理\n /// クリッピングマスクを使う描画オブジェクトの登録を行う\n /// \n /// モデルのインスタンス\n /// バッファの生成数\n public unsafe void Initialize(CubismModel model, int maskBufferCount)\n {\n RenderTextureCount = maskBufferCount;\n\n // レンダーテクスチャのクリアフラグの設定\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n\n //クリッピングマスクを使う描画オブジェクトを全て登録する\n //クリッピングマスクは、通常数個程度に限定して使うものとする\n for ( var i = 0; i < model.GetDrawableCount(); i++ )\n {\n if ( model.GetDrawableMaskCounts()[i] <= 0 )\n {\n //クリッピングマスクが使用されていないアートメッシュ(多くの場合使用しない)\n ClippingContextListForDraw.Add(null);\n\n continue;\n }\n\n // 既にあるClipContextと同じかチェックする\n var cc = FindSameClip(model.GetDrawableMasks()[i], model.GetDrawableMaskCounts()[i]);\n if ( cc == null )\n {\n // 同一のマスクが存在していない場合は生成する\n if ( _renderType == RenderType.OpenGL )\n {\n cc = new CubismClippingContext_OpenGLES2(this, model, model.GetDrawableMasks()[i], model.GetDrawableMaskCounts()[i]);\n }\n else\n {\n throw new Exception(\"Only OpenGL\");\n }\n\n ClippingContextListForMask.Add(cc);\n }\n\n cc.AddClippedDrawable(i);\n\n ClippingContextListForDraw.Add(cc);\n }\n }\n\n /// \n /// 既にマスクを作っているかを確認。\n /// 作っているようであれば該当するクリッピングマスクのインスタンスを返す。\n /// 作っていなければNULLを返す\n /// \n /// 描画オブジェクトをマスクする描画オブジェクトのリスト\n /// 描画オブジェクトをマスクする描画オブジェクトの数\n /// 該当するクリッピングマスクが存在すればインスタンスを返し、なければNULLを返す。\n private unsafe CubismClippingContext? FindSameClip(int* drawableMasks, int drawableMaskCounts)\n {\n // 作成済みClippingContextと一致するか確認\n for ( var i = 0; i < ClippingContextListForMask.Count; i++ )\n {\n var cc = ClippingContextListForMask[i];\n var count = cc.ClippingIdCount;\n if ( count != drawableMaskCounts )\n {\n continue; //個数が違う場合は別物\n }\n\n var samecount = 0;\n\n // 同じIDを持つか確認。配列の数が同じなので、一致した個数が同じなら同じ物を持つとする。\n for ( var j = 0; j < count; j++ )\n {\n var clipId = cc.ClippingIdList[j];\n for ( var k = 0; k < count; k++ )\n {\n if ( drawableMasks[k] == clipId )\n {\n samecount++;\n\n break;\n }\n }\n }\n\n if ( samecount == count )\n {\n return cc;\n }\n }\n\n return null; //見つからなかった\n }\n\n /// \n /// 高精細マスク処理用の行列を計算する\n /// \n /// モデルのインスタンス\n /// 処理が右手系であるか\n public void SetupMatrixForHighPrecision(CubismModel model, bool isRightHanded)\n {\n // 全てのクリッピングを用意する\n // 同じクリップ(複数の場合はまとめて1つのクリップ)を使う場合は1度だけ設定する\n var usingClipCount = 0;\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // 1つのクリッピングマスクに関して\n var cc = ClippingContextListForMask[clipIndex];\n\n // このクリップを利用する描画オブジェクト群全体を囲む矩形を計算\n CalcClippedDrawTotalBounds(model, cc);\n\n if ( cc.IsUsing )\n {\n usingClipCount++; //使用中としてカウント\n }\n }\n\n if ( usingClipCount <= 0 )\n {\n return;\n }\n\n // マスク行列作成処理\n SetupLayoutBounds(0);\n\n // サイズがレンダーテクスチャの枚数と合わない場合は合わせる\n if ( ClearedMaskBufferFlags.Count != RenderTextureCount )\n {\n ClearedMaskBufferFlags.Clear();\n\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n }\n else\n {\n // マスクのクリアフラグを毎フレーム開始時に初期化\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags[i] = false;\n }\n }\n\n // 実際にマスクを生成する\n // 全てのマスクをどの様にレイアウトして描くかを決定し、ClipContext , ClippedDrawContext に記憶する\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // --- 実際に1つのマスクを描く ---\n var clipContext = ClippingContextListForMask[clipIndex];\n var allClippedDrawRect = clipContext.AllClippedDrawRect; //このマスクを使う、全ての描画オブジェクトの論理座標上の囲み矩形\n var layoutBoundsOnTex01 = clipContext.LayoutBounds; //この中にマスクを収める\n var MARGIN = 0.05f;\n float scaleX;\n float scaleY;\n var ppu = model.GetPixelsPerUnit();\n var maskPixelWidth = clipContext.Manager.ClippingMaskBufferSize.X;\n var maskPixelHeight = clipContext.Manager.ClippingMaskBufferSize.Y;\n var physicalMaskWidth = layoutBoundsOnTex01.Width * maskPixelWidth;\n var physicalMaskHeight = layoutBoundsOnTex01.Height * maskPixelHeight;\n\n TmpBoundsOnModel.SetRect(allClippedDrawRect);\n if ( TmpBoundsOnModel.Width * ppu > physicalMaskWidth )\n {\n TmpBoundsOnModel.Expand(allClippedDrawRect.Width * MARGIN, 0.0f);\n scaleX = layoutBoundsOnTex01.Width / TmpBoundsOnModel.Width;\n }\n else\n {\n scaleX = ppu / physicalMaskWidth;\n }\n\n if ( TmpBoundsOnModel.Height * ppu > physicalMaskHeight )\n {\n TmpBoundsOnModel.Expand(0.0f, allClippedDrawRect.Height * MARGIN);\n scaleY = layoutBoundsOnTex01.Height / TmpBoundsOnModel.Height;\n }\n else\n {\n scaleY = ppu / physicalMaskHeight;\n }\n\n // マスク生成時に使う行列を求める\n CreateMatrixForMask(isRightHanded, layoutBoundsOnTex01, scaleX, scaleY);\n\n clipContext.MatrixForMask.SetMatrix(TmpMatrixForMask.Tr);\n clipContext.MatrixForDraw.SetMatrix(TmpMatrixForDraw.Tr);\n }\n }\n\n /// \n /// マスク作成・描画用の行列を作成する。\n /// \n /// 座標を右手系として扱うかを指定\n /// マスクを収める領域\n /// 描画オブジェクトの伸縮率\n /// 描画オブジェクトの伸縮率\n protected void CreateMatrixForMask(bool isRightHanded, RectF layoutBoundsOnTex01, float scaleX, float scaleY)\n {\n TmpMatrix.LoadIdentity();\n {\n // Layout0..1 を -1..1に変換\n TmpMatrix.TranslateRelative(-1.0f, -1.0f);\n TmpMatrix.ScaleRelative(2.0f, 2.0f);\n }\n\n {\n // view to Layout0..1\n TmpMatrix.TranslateRelative(layoutBoundsOnTex01.X, layoutBoundsOnTex01.Y); //new = [translate]\n TmpMatrix.ScaleRelative(scaleX, scaleY); //new = [translate][scale]\n TmpMatrix.TranslateRelative(-TmpBoundsOnModel.X, -TmpBoundsOnModel.Y); //new = [translate][scale][translate]\n }\n\n // tmpMatrixForMask が計算結果\n TmpMatrixForMask.SetMatrix(TmpMatrix.Tr);\n\n TmpMatrix.LoadIdentity();\n {\n TmpMatrix.TranslateRelative(layoutBoundsOnTex01.X, layoutBoundsOnTex01.Y * (isRightHanded ? -1.0f : 1.0f)); //new = [translate]\n TmpMatrix.ScaleRelative(scaleX, scaleY * (isRightHanded ? -1.0f : 1.0f)); //new = [translate][scale]\n TmpMatrix.TranslateRelative(-TmpBoundsOnModel.X, -TmpBoundsOnModel.Y); //new = [translate][scale][translate]\n }\n\n TmpMatrixForDraw.SetMatrix(TmpMatrix.Tr);\n }\n\n /// \n /// クリッピングコンテキストを配置するレイアウト。\n /// ひとつのレンダーテクスチャを極力いっぱいに使ってマスクをレイアウトする。\n /// マスクグループの数が4以下ならRGBA各チャンネルに1つずつマスクを配置し、5以上6以下ならRGBAを2,2,1,1と配置する。\n /// \n /// 配置するクリッピングコンテキストの数\n protected void SetupLayoutBounds(int usingClipCount)\n {\n var useClippingMaskMaxCount = RenderTextureCount <= 1\n ? ClippingMaskMaxCountOnDefault\n : ClippingMaskMaxCountOnMultiRenderTexture * RenderTextureCount;\n\n if ( usingClipCount <= 0 || usingClipCount > useClippingMaskMaxCount )\n {\n if ( usingClipCount > useClippingMaskMaxCount )\n {\n // マスクの制限数の警告を出す\n var count = usingClipCount - useClippingMaskMaxCount;\n CubismLog.Error(\"not supported mask count : %d\\n[Details] render texture count: %d\\n, mask count : %d\"\n , count, RenderTextureCount, usingClipCount);\n }\n\n // この場合は一つのマスクターゲットを毎回クリアして使用する\n for ( var index = 0; index < ClippingContextListForMask.Count; index++ )\n {\n var cc = ClippingContextListForMask[index];\n cc.LayoutChannelIndex = 0; // どうせ毎回消すので固定で良い\n cc.LayoutBounds.X = 0.0f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 1.0f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = 0;\n }\n\n return;\n }\n\n // レンダーテクスチャが1枚なら9分割する(最大36枚)\n var layoutCountMaxValue = RenderTextureCount <= 1 ? 9 : 8;\n\n // ひとつのRenderTextureを極力いっぱいに使ってマスクをレイアウトする\n // マスクグループの数が4以下ならRGBA各チャンネルに1つずつマスクを配置し、5以上6以下ならRGBAを2,2,1,1と配置する\n var countPerSheetDiv = (usingClipCount + RenderTextureCount - 1) / RenderTextureCount; // レンダーテクスチャ1枚あたり何枚割り当てるか(切り上げ)\n var reduceLayoutTextureCount = usingClipCount % RenderTextureCount; // レイアウトの数を1枚減らすレンダーテクスチャの数(この数だけのレンダーテクスチャが対象)\n\n // RGBAを順番に使っていく\n var divCount = countPerSheetDiv / ColorChannelCount; //1チャンネルに配置する基本のマスク個数\n var modCount = countPerSheetDiv % ColorChannelCount; //余り、この番号のチャンネルまでに1つずつ配分する\n\n // RGBAそれぞれのチャンネルを用意していく(0:R , 1:G , 2:B, 3:A, )\n var curClipIndex = 0; //順番に設定していく\n\n for ( var renderTextureIndex = 0; renderTextureIndex < RenderTextureCount; renderTextureIndex++ )\n {\n for ( var channelIndex = 0; channelIndex < ColorChannelCount; channelIndex++ )\n {\n // このチャンネルにレイアウトする数\n // NOTE: レイアウト数 = 1チャンネルに配置する基本のマスク + 余りのマスクを置くチャンネルなら1つ追加\n var layoutCount = divCount + (channelIndex < modCount ? 1 : 0);\n\n // レイアウトの数を1枚減らす場合にそれを行うチャンネルを決定\n // divが0の時は正常なインデックスの範囲内になるように調整\n var checkChannelIndex = modCount + (divCount < 1 ? -1 : 0);\n\n // 今回が対象のチャンネルかつ、レイアウトの数を1枚減らすレンダーテクスチャが存在する場合\n if ( channelIndex == checkChannelIndex && reduceLayoutTextureCount > 0 )\n {\n // 現在のレンダーテクスチャが、対象のレンダーテクスチャであればレイアウトの数を1枚減らす\n layoutCount -= !(renderTextureIndex < reduceLayoutTextureCount) ? 1 : 0;\n }\n\n // 分割方法を決定する\n if ( layoutCount == 0 )\n {\n // 何もしない\n }\n else if ( layoutCount == 1 )\n {\n //全てをそのまま使う\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n cc.LayoutBounds.X = 0.0f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 1.0f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = renderTextureIndex;\n }\n else if ( layoutCount == 2 )\n {\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 2;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos * 0.5f;\n cc.LayoutBounds.Y = 0.0f;\n cc.LayoutBounds.Width = 0.5f;\n cc.LayoutBounds.Height = 1.0f;\n cc.BufferIndex = renderTextureIndex;\n //UVを2つに分解して使う\n }\n }\n else if ( layoutCount <= 4 )\n {\n //4分割して使う\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 2;\n var ypos = i / 2;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos * 0.5f;\n cc.LayoutBounds.Y = ypos * 0.5f;\n cc.LayoutBounds.Width = 0.5f;\n cc.LayoutBounds.Height = 0.5f;\n cc.BufferIndex = renderTextureIndex;\n }\n }\n else if ( layoutCount <= layoutCountMaxValue )\n {\n //9分割して使う\n for ( var i = 0; i < layoutCount; i++ )\n {\n var xpos = i % 3;\n var ypos = i / 3;\n\n var cc = ClippingContextListForMask[curClipIndex++];\n cc.LayoutChannelIndex = channelIndex;\n\n cc.LayoutBounds.X = xpos / 3.0f;\n cc.LayoutBounds.Y = ypos / 3.0f;\n cc.LayoutBounds.Width = 1.0f / 3.0f;\n cc.LayoutBounds.Height = 1.0f / 3.0f;\n cc.BufferIndex = renderTextureIndex;\n }\n }\n // マスクの制限枚数を超えた場合の処理\n else\n {\n var count = usingClipCount - useClippingMaskMaxCount;\n\n // 開発モードの場合は停止させる\n throw new Exception($\"not supported mask count : {count}\\n[Details] render texture count: {RenderTextureCount}\\n, mask count : {usingClipCount}\");\n }\n }\n }\n }\n\n /// \n /// マスクされる描画オブジェクト群全体を囲む矩形(モデル座標系)を計算する\n /// \n /// モデルのインスタンス\n /// クリッピングマスクのコンテキスト\n protected unsafe void CalcClippedDrawTotalBounds(CubismModel model, CubismClippingContext clippingContext)\n {\n // 被クリッピングマスク(マスクされる描画オブジェクト)の全体の矩形\n float clippedDrawTotalMinX = float.MaxValue,\n clippedDrawTotalMinY = float.MaxValue;\n\n float clippedDrawTotalMaxX = float.MinValue,\n clippedDrawTotalMaxY = float.MinValue;\n\n // このマスクが実際に必要か判定する\n // このクリッピングを利用する「描画オブジェクト」がひとつでも使用可能であればマスクを生成する必要がある\n\n var clippedDrawCount = clippingContext.ClippedDrawableIndexList.Count;\n for ( var clippedDrawableIndex = 0; clippedDrawableIndex < clippedDrawCount; clippedDrawableIndex++ )\n {\n // マスクを使用する描画オブジェクトの描画される矩形を求める\n var drawableIndex = clippingContext.ClippedDrawableIndexList[clippedDrawableIndex];\n\n var drawableVertexCount = model.GetDrawableVertexCount(drawableIndex);\n var drawableVertexes = model.GetDrawableVertices(drawableIndex);\n\n float minX = float.MaxValue,\n minY = float.MaxValue;\n\n float maxX = float.MinValue,\n maxY = float.MinValue;\n\n var loop = drawableVertexCount * CubismFramework.VertexStep;\n for ( var pi = CubismFramework.VertexOffset; pi < loop; pi += CubismFramework.VertexStep )\n {\n var x = drawableVertexes[pi];\n var y = drawableVertexes[pi + 1];\n if ( x < minX )\n {\n minX = x;\n }\n\n if ( x > maxX )\n {\n maxX = x;\n }\n\n if ( y < minY )\n {\n minY = y;\n }\n\n if ( y > maxY )\n {\n maxY = y;\n }\n }\n\n //\n if ( minX == float.MaxValue )\n {\n continue; //有効な点がひとつも取れなかったのでスキップする\n }\n\n // 全体の矩形に反映\n if ( minX < clippedDrawTotalMinX )\n {\n clippedDrawTotalMinX = minX;\n }\n\n if ( minY < clippedDrawTotalMinY )\n {\n clippedDrawTotalMinY = minY;\n }\n\n if ( maxX > clippedDrawTotalMaxX )\n {\n clippedDrawTotalMaxX = maxX;\n }\n\n if ( maxY > clippedDrawTotalMaxY )\n {\n clippedDrawTotalMaxY = maxY;\n }\n }\n\n if ( clippedDrawTotalMinX == float.MaxValue )\n {\n clippingContext.AllClippedDrawRect.X = 0.0f;\n clippingContext.AllClippedDrawRect.Y = 0.0f;\n clippingContext.AllClippedDrawRect.Width = 0.0f;\n clippingContext.AllClippedDrawRect.Height = 0.0f;\n clippingContext.IsUsing = false;\n }\n else\n {\n clippingContext.IsUsing = true;\n var w = clippedDrawTotalMaxX - clippedDrawTotalMinX;\n var h = clippedDrawTotalMaxY - clippedDrawTotalMinY;\n clippingContext.AllClippedDrawRect.X = clippedDrawTotalMinX;\n clippingContext.AllClippedDrawRect.Y = clippedDrawTotalMinY;\n clippingContext.AllClippedDrawRect.Width = w;\n clippingContext.AllClippedDrawRect.Height = h;\n }\n }\n\n /// \n /// カラーチャンネル(RGBA)のフラグを取得する\n /// \n /// カラーチャンネル(RGBA)の番号(0:R , 1:G , 2:B, 3:A)\n /// \n public CubismTextureColor GetChannelFlagAsColor(int channelNo) { return ChannelColors[channelNo]; }\n\n /// \n /// クリッピングマスクバッファのサイズを設定する\n /// \n /// クリッピングマスクバッファのサイズ\n /// クリッピングマスクバッファのサイズ\n public void SetClippingMaskBufferSize(float width, float height) { ClippingMaskBufferSize = new Vector2(width, height); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/ACubismMotion.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションの抽象基底クラス。MotionQueueManagerによってモーションの再生を管理する。\n/// \npublic abstract class ACubismMotion\n{\n protected readonly List FiredEventValues = [];\n\n /// \n /// コンストラクタ。\n /// \n public ACubismMotion()\n {\n FadeInSeconds = -1.0f;\n FadeOutSeconds = -1.0f;\n Weight = 1.0f;\n }\n\n /// \n /// フェードインにかかる時間[秒]\n /// \n public float FadeInSeconds { get; set; }\n\n /// \n /// フェードアウトにかかる時間[秒]\n /// \n public float FadeOutSeconds { get; set; }\n\n /// \n /// モーションの重み\n /// \n public float Weight { get; set; }\n\n /// \n /// モーション再生の開始時刻[秒]\n /// \n public float OffsetSeconds { get; set; }\n\n // モーション再生終了コールバック関数\n public FinishedMotionCallback? OnFinishedMotion { get; set; }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// CubismMotionQueueManagerで管理されているモーション\n /// デルタ時間の積算値[秒]\n public void UpdateParameters(CubismModel model, CubismMotionQueueEntry motionQueueEntry, float userTimeSeconds)\n {\n if ( !motionQueueEntry.Available || motionQueueEntry.Finished )\n {\n return;\n }\n\n SetupMotionQueueEntry(motionQueueEntry, userTimeSeconds);\n\n var fadeWeight = UpdateFadeWeight(motionQueueEntry, userTimeSeconds);\n\n //---- 全てのパラメータIDをループする ----\n DoUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry);\n\n //後処理\n //終了時刻を過ぎたら終了フラグを立てる(CubismMotionQueueManager)\n if ( motionQueueEntry.EndTime > 0 && motionQueueEntry.EndTime < userTimeSeconds )\n {\n motionQueueEntry.Finished = true; //終了\n }\n }\n\n /// \n /// モーションの再生を開始するためのセットアップを行う。\n /// \n /// CubismMotionQueueManagerによって管理されるモーション\n /// 総再生時間(秒)\n public void SetupMotionQueueEntry(CubismMotionQueueEntry motionQueueEntry, float userTimeSeconds)\n {\n if ( !motionQueueEntry.Available || motionQueueEntry.Finished )\n {\n return;\n }\n\n if ( motionQueueEntry.Started )\n {\n return;\n }\n\n motionQueueEntry.Started = true;\n motionQueueEntry.StartTime = userTimeSeconds - OffsetSeconds; //モーションの開始時刻を記録\n motionQueueEntry.FadeInStartTime = userTimeSeconds; //フェードインの開始時刻\n\n var duration = GetDuration();\n\n if ( motionQueueEntry.EndTime < 0 )\n {\n //開始していないうちに終了設定している場合がある。\n motionQueueEntry.EndTime = duration <= 0 ? -1 : motionQueueEntry.StartTime + duration;\n //duration == -1 の場合はループする\n }\n }\n\n /// \n /// モーションのウェイトを更新する。\n /// \n /// CubismMotionQueueManagerで管理されているモーション\n /// デルタ時間の積算値[秒]\n /// \n /// \n public float UpdateFadeWeight(CubismMotionQueueEntry? motionQueueEntry, float userTimeSeconds)\n {\n if ( motionQueueEntry == null )\n {\n CubismLog.Error(\"motionQueueEntry is null.\");\n\n return 0;\n }\n\n var fadeWeight = Weight; //現在の値と掛け合わせる割合\n\n //---- フェードイン・アウトの処理 ----\n //単純なサイン関数でイージングする\n var fadeIn = FadeInSeconds == 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((userTimeSeconds - motionQueueEntry.FadeInStartTime) / FadeInSeconds);\n\n var fadeOut = FadeOutSeconds == 0.0f || motionQueueEntry.EndTime < 0.0f\n ? 1.0f\n : CubismMath.GetEasingSine((motionQueueEntry.EndTime - userTimeSeconds) / FadeOutSeconds);\n\n fadeWeight = fadeWeight * fadeIn * fadeOut;\n\n motionQueueEntry.SetState(userTimeSeconds, fadeWeight);\n\n if ( 0.0f > fadeWeight || fadeWeight > 1.0f )\n {\n throw new Exception(\"fadeWeight out of range\");\n }\n\n return fadeWeight;\n }\n\n /// \n /// モーションの長さを取得する。\n /// ループのときは「-1」。\n /// ループではない場合は、オーバーライドする。\n /// 正の値の時は取得される時間で終了する。\n /// 「-1」のときは外部から停止命令が無い限り終わらない処理となる。\n /// \n /// モーションの長さ[秒]\n public virtual float GetDuration() { return -1.0f; }\n\n /// \n /// モーションのループ1回分の長さを取得する。\n /// ループしない場合は GetDuration()と同じ値を返す。\n /// ループ一回分の長さが定義できない場合(プログラム的に動き続けるサブクラスなど)の場合は「-1」を返す\n /// \n /// モーションのループ1回分の長さ[秒]\n public virtual float GetLoopDuration() { return -1.0f; }\n\n /// \n /// イベント発火のチェック。\n /// 入力する時間は呼ばれるモーションタイミングを0とした秒数で行う。\n /// \n /// 前回のイベントチェック時間[秒]\n /// 今回の再生時間[秒]\n /// \n public virtual List GetFiredEvent(float beforeCheckTimeSeconds, float motionTimeSeconds) { return FiredEventValues; }\n\n /// \n /// 透明度のカーブが存在するかどうかを確認する\n /// \n /// \n /// true . キーが存在する\n /// false . キーが存在しない\n /// \n public virtual bool IsExistModelOpacity() { return false; }\n\n /// \n /// 透明度のカーブのインデックスを返す\n /// \n /// success:透明度のカーブのインデックス\n public virtual int GetModelOpacityIndex() { return -1; }\n\n /// \n /// 透明度のIdを返す\n /// \n /// 透明度のId\n public virtual string? GetModelOpacityId(int index) { return \"\"; }\n\n public virtual float GetModelOpacityValue() { return 1.0f; }\n\n public abstract void DoUpdateParameters(CubismModel model, float userTimeSeconds, float weight, CubismMotionQueueEntry motionQueueEntry);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismRenderer_OpenGLES2.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic class CubismRenderer_OpenGLES2 : CubismRenderer\n{\n public const int ColorChannelCount = 4; // 実験時に1チャンネルの場合は1、RGBだけの場合は3、アルファも含める場合は4\n\n public const int ClippingMaskMaxCountOnDefault = 36; // 通常のフレームバッファ1枚あたりのマスク最大数\n\n public const int ClippingMaskMaxCountOnMultiRenderTexture = 32; // フレームバッファが2枚以上ある場合のフレームバッファ1枚あたりのマスク最大数\n\n /// \n /// マスク描画用のフレームバッファ\n /// \n private readonly List _offscreenFrameBuffers = [];\n\n /// \n /// OpenGLのステートを保持するオブジェクト\n /// \n private readonly CubismRendererProfile_OpenGLES2 _rendererProfile;\n\n /// \n /// 描画オブジェクトのインデックスを描画順に並べたリスト\n /// \n private readonly int[] _sortedDrawableIndexList;\n\n /// \n /// モデルが参照するテクスチャとレンダラでバインドしているテクスチャとのマップ\n /// \n private readonly Dictionary _textures;\n\n private readonly OpenGLApi GL;\n\n /// \n /// クリッピングマスク管理オブジェクト\n /// \n private CubismClippingManager_OpenGLES2? _clippingManager;\n\n internal CubismShader_OpenGLES2 Shader;\n\n internal VBO[] vbo = new VBO[512];\n\n public CubismRenderer_OpenGLES2(OpenGLApi gl, CubismModel model, int maskBufferCount = 1) : base(model)\n {\n GL = gl;\n Shader = new CubismShader_OpenGLES2(gl);\n _rendererProfile = new CubismRendererProfile_OpenGLES2(gl);\n _textures = new Dictionary(32);\n\n VertexArray = GL.GenVertexArray();\n VertexBuffer = GL.GenBuffer();\n IndexBuffer = GL.GenBuffer();\n\n // 1未満は1に補正する\n if ( maskBufferCount < 1 )\n {\n maskBufferCount = 1;\n CubismLog.Warning(\"[Live2D SDK]The number of render textures must be an integer greater than or equal to 1. Set the number of render textures to 1.\");\n }\n\n if ( model.IsUsingMasking() )\n {\n _clippingManager = new CubismClippingManager_OpenGLES2(GL); //クリッピングマスク・バッファ前処理方式を初期化\n _clippingManager.Initialize(model, maskBufferCount);\n\n _offscreenFrameBuffers.Clear();\n for ( var i = 0; i < maskBufferCount; ++i )\n {\n var offscreenSurface = new CubismOffscreenSurface_OpenGLES2(GL);\n offscreenSurface.CreateOffscreenSurface((int)_clippingManager.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n _offscreenFrameBuffers.Add(offscreenSurface);\n }\n }\n\n _sortedDrawableIndexList = new int[model.GetDrawableCount()];\n }\n\n /// \n /// マスクテクスチャに描画するためのクリッピングコンテキスト\n /// \n internal CubismClippingContext? ClippingContextBufferForMask { get; set; }\n\n /// \n /// 画面上描画するためのクリッピングコンテキスト\n /// \n internal CubismClippingContext? ClippingContextBufferForDraw { get; set; }\n\n internal int VertexArray { get; private set; }\n\n internal int VertexBuffer { get; private set; }\n\n internal int IndexBuffer { get; private set; }\n\n /// \n /// Tegraプロセッサ対応。拡張方式による描画の有効・無効\n /// \n /// trueなら拡張方式で描画する\n /// trueなら拡張方式のPA設定を有効にする\n public void SetExtShaderMode(bool extMode, bool extPAMode = false)\n {\n Shader.SetExtShaderMode(extMode, extPAMode);\n Shader.ReleaseShaderProgram();\n }\n\n /// \n /// OpenGLテクスチャのバインド処理\n /// CubismRendererにテクスチャを設定し、CubismRenderer中でその画像を参照するためのIndex値を戻り値とする\n /// \n /// セットするモデルテクスチャの番号\n /// OpenGLテクスチャの番号\n public void BindTexture(int modelTextureNo, int glTextureNo) { _textures[modelTextureNo] = glTextureNo; }\n\n /// \n /// OpenGLにバインドされたテクスチャのリストを取得する\n /// \n /// テクスチャのアドレスのリスト\n public Dictionary GetBindedTextures() { return _textures; }\n\n /// \n /// クリッピングマスクバッファのサイズを設定する\n /// マスク用のFrameBufferを破棄・再作成するため処理コストは高い。\n /// \n /// クリッピングマスクバッファのサイズ\n /// クリッピングマスクバッファのサイズ\n public void SetClippingMaskBufferSize(float width, float height)\n {\n if ( _clippingManager == null )\n {\n return;\n }\n\n // インスタンス破棄前にレンダーテクスチャの数を保存\n var renderTextureCount = _clippingManager.RenderTextureCount;\n\n _clippingManager = new CubismClippingManager_OpenGLES2(GL);\n\n _clippingManager.SetClippingMaskBufferSize(width, height);\n\n _clippingManager.Initialize(Model, renderTextureCount);\n }\n\n /// \n /// クリッピングマスクのバッファを取得する\n /// \n /// クリッピングマスクのバッファへのポインタ\n public CubismOffscreenSurface_OpenGLES2 GetMaskBuffer(int index) { return _offscreenFrameBuffers[index]; }\n\n internal override unsafe void DrawMesh(int textureNo, int indexCount, int vertexCount\n , ushort* indexArray, float* vertexArray, float* uvArray\n , float opacity, CubismBlendMode colorBlendMode, bool invertedMask)\n {\n throw new Exception(\"[Live2D Core]Use 'DrawMeshOpenGL' function\");\n }\n\n public bool IsGeneratingMask() { return ClippingContextBufferForMask != null; }\n\n /// \n /// [オーバーライド]\n /// 描画オブジェクト(アートメッシュ)を描画する。\n /// ポリゴンメッシュとテクスチャ番号をセットで渡す。\n /// \n /// 描画するテクスチャ番号\n /// 描画オブジェクトのインデックス値\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュのインデックス配列\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 乗算色\n /// スクリーン色\n /// 不透明度\n /// カラー合成タイプ\n /// マスク使用時のマスクの反転使用\n internal unsafe void DrawMeshOpenGL(CubismModel model, int index)\n {\n if ( _textures[model.GetDrawableTextureIndex(index)] == 0 )\n {\n return; // モデルが参照するテクスチャがバインドされていない場合は描画をスキップする\n }\n\n // 裏面描画の有効・無効\n if ( IsCulling )\n {\n GL.Enable(GL.GL_CULL_FACE);\n }\n else\n {\n GL.Disable(GL.GL_CULL_FACE);\n }\n\n GL.FrontFace(GL.GL_CCW); // Cubism SDK OpenGLはマスク・アートメッシュ共にCCWが表面\n\n var vertexCount = model.GetDrawableVertexCount(index);\n var vertexArray = model.GetDrawableVertices(index);\n var uvArray = (float*)model.GetDrawableVertexUvs(index);\n\n GL.BindVertexArray(VertexArray);\n\n if ( vbo == null || vbo.Length < vertexCount )\n {\n vbo = new VBO[vertexCount];\n }\n\n for ( var a = 0; a < vertexCount; a++ )\n {\n vbo[a].ver0 = vertexArray[a * 2];\n vbo[a].ver1 = vertexArray[a * 2 + 1];\n vbo[a].uv0 = uvArray[a * 2];\n vbo[a].uv1 = uvArray[a * 2 + 1];\n }\n\n var indexCount = model.GetDrawableVertexIndexCount(index);\n var indexArray = model.GetDrawableVertexIndices(index);\n\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, VertexBuffer);\n fixed (void* p = vbo)\n {\n GL.BufferData(GL.GL_ARRAY_BUFFER, vertexCount * sizeof(VBO), new IntPtr(p), GL.GL_STATIC_DRAW);\n }\n\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, IndexBuffer);\n GL.BufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(ushort), new IntPtr(indexArray), GL.GL_STATIC_DRAW);\n\n if ( IsGeneratingMask() ) // マスク生成時\n {\n Shader.SetupShaderProgramForMask(this, model, index);\n }\n else\n {\n Shader.SetupShaderProgramForDraw(this, model, index);\n }\n\n // ポリゴンメッシュを描画する\n GL.DrawElements(GL.GL_TRIANGLES, indexCount, GL.GL_UNSIGNED_SHORT, 0);\n\n // 後処理\n GL.UseProgram(0);\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, 0);\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);\n GL.BindVertexArray(0);\n ClippingContextBufferForDraw = null;\n ClippingContextBufferForMask = null;\n }\n\n /// \n /// 描画開始時の追加処理。\n /// モデルを描画する前にクリッピングマスクに必要な処理を実装している。\n /// \n internal void PreDraw()\n {\n GL.Disable(GL.GL_SCISSOR_TEST);\n GL.Disable(GL.GL_STENCIL_TEST);\n GL.Disable(GL.GL_DEPTH_TEST);\n\n GL.Enable(GL.GL_BLEND);\n GL.ColorMask(true, true, true, true);\n\n if ( GL.IsPhoneES2 )\n {\n GL.BindVertexArrayOES(0);\n }\n\n GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);\n GL.BindBuffer(GL.GL_ARRAY_BUFFER, 0); //前にバッファがバインドされていたら破棄する必要がある\n\n //異方性フィルタリング。プラットフォームのOpenGLによっては未対応の場合があるので、未設定のときは設定しない\n if ( Anisotropy > 0.0f )\n {\n for ( var i = 0; i < _textures.Count; i++ )\n {\n GL.BindTexture(GL.GL_TEXTURE_2D, _textures[i]);\n GL.TexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, Anisotropy);\n }\n }\n }\n\n /// \n /// モデル描画直前のOpenGLES2のステートを保持する\n /// \n protected override void SaveProfile() { _rendererProfile.Save(); }\n\n /// \n /// モデル描画直前のOpenGLES2のステートを保持する\n /// \n protected override void RestoreProfile() { _rendererProfile.Restore(); }\n\n protected override unsafe void DoDrawModel()\n {\n //------------ クリッピングマスク・バッファ前処理方式の場合 ------------\n if ( _clippingManager != null )\n {\n PreDraw();\n\n // サイズが違う場合はここで作成しなおし\n for ( var i = 0; i < _clippingManager.RenderTextureCount; ++i )\n {\n if ( _offscreenFrameBuffers[i].BufferWidth != (uint)_clippingManager.ClippingMaskBufferSize.X ||\n _offscreenFrameBuffers[i].BufferHeight != (uint)_clippingManager.ClippingMaskBufferSize.Y )\n {\n _offscreenFrameBuffers[i].CreateOffscreenSurface(\n (int)_clippingManager.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n }\n }\n\n if ( UseHighPrecisionMask )\n {\n _clippingManager.SetupMatrixForHighPrecision(Model, false);\n }\n else\n {\n _clippingManager.SetupClippingContext(Model, this, _rendererProfile.LastFBO, _rendererProfile.LastViewport);\n }\n }\n\n // 上記クリッピング処理内でも一度PreDrawを呼ぶので注意!!\n PreDraw();\n\n var drawableCount = Model.GetDrawableCount();\n var renderOrder = Model.GetDrawableRenderOrders();\n\n // インデックスを描画順でソート\n for ( var i = 0; i < drawableCount; ++i )\n {\n var order = renderOrder[i];\n _sortedDrawableIndexList[order] = i;\n }\n\n if ( GL.AlwaysClear )\n {\n GL.ClearColor(ClearColor.R,\n ClearColor.G,\n ClearColor.B,\n ClearColor.A);\n\n GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n }\n\n // 描画\n for ( var i = 0; i < drawableCount; ++i )\n {\n var drawableIndex = _sortedDrawableIndexList[i];\n\n // Drawableが表示状態でなければ処理をパスする\n if ( !Model.GetDrawableDynamicFlagIsVisible(drawableIndex) )\n {\n continue;\n }\n\n // クリッピングマスク\n var clipContext = _clippingManager?.ClippingContextListForDraw[drawableIndex];\n\n if ( clipContext != null && UseHighPrecisionMask ) // マスクを書く必要がある\n {\n if ( clipContext.IsUsing ) // 書くことになっていた\n {\n // 生成したFrameBufferと同じサイズでビューポートを設定\n GL.Viewport(0, 0, (int)_clippingManager!.ClippingMaskBufferSize.X, (int)_clippingManager.ClippingMaskBufferSize.Y);\n\n PreDraw(); // バッファをクリアする\n\n // ---------- マスク描画処理 ----------\n // マスク用RenderTextureをactiveにセット\n GetMaskBuffer(clipContext.BufferIndex).BeginDraw(_rendererProfile.LastFBO);\n\n // マスクをクリアする\n // 1が無効(描かれない)領域、0が有効(描かれる)領域。(シェーダで Cd*Csで0に近い値をかけてマスクを作る。1をかけると何も起こらない)\n GL.ClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n GL.Clear(GL.GL_COLOR_BUFFER_BIT);\n }\n\n {\n var clipDrawCount = clipContext.ClippingIdCount;\n for ( var index = 0; index < clipDrawCount; index++ )\n {\n var clipDrawIndex = clipContext.ClippingIdList[index];\n\n // 頂点情報が更新されておらず、信頼性がない場合は描画をパスする\n if ( !Model.GetDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex) )\n {\n continue;\n }\n\n IsCulling = Model.GetDrawableCulling(clipDrawIndex);\n\n // 今回専用の変換を適用して描く\n // チャンネルも切り替える必要がある(A,R,G,B)\n ClippingContextBufferForMask = clipContext;\n\n DrawMeshOpenGL(Model, clipDrawIndex);\n }\n }\n\n {\n // --- 後処理 ---\n GetMaskBuffer(clipContext.BufferIndex).EndDraw();\n ClippingContextBufferForMask = null;\n GL.Viewport(_rendererProfile.LastViewport[0], _rendererProfile.LastViewport[1], _rendererProfile.LastViewport[2], _rendererProfile.LastViewport[3]);\n\n PreDraw(); // バッファをクリアする\n }\n }\n\n // クリッピングマスクをセットする\n ClippingContextBufferForDraw = clipContext;\n\n IsCulling = Model.GetDrawableCulling(drawableIndex);\n\n DrawMeshOpenGL(Model, drawableIndex);\n }\n }\n\n public override void Dispose() { Shader.ReleaseShaderProgram(); }\n\n public int GetBindedTextureId(int textureId) { return _textures[textureId] != 0 ? _textures[textureId] : -1; }\n\n [StructLayout(LayoutKind.Sequential, Pack = 4)]\n internal struct VBO\n {\n public float ver0;\n\n public float ver1;\n\n public float uv0;\n\n public float uv1;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysics.cs", "using System.Numerics;\nusing System.Text.Json;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// 物理演算のクラス。\n/// \npublic class CubismPhysics\n{\n /// physics types tags.\n public const string PhysicsTypeTagX = \"X\";\n\n public const string PhysicsTypeTagY = \"Y\";\n\n public const string PhysicsTypeTagAngle = \"Angle\";\n\n /// Constant of air resistance.\n public const float AirResistance = 5.0f;\n\n /// Constant of maximum weight of input and output ratio.\n public const float MaximumWeight = 100.0f;\n\n /// Constant of threshold of movement.\n public const float MovementThreshold = 0.001f;\n\n /// Constant of maximum allowed delta time\n public const float MaxDeltaTime = 5.0f;\n\n /// \n /// 最新の振り子計算の結果\n /// \n private readonly List _currentRigOutputs = [];\n\n /// \n /// 物理演算のデータ\n /// \n private readonly CubismPhysicsRig _physicsRig;\n\n /// \n /// 一つ前の振り子計算の結果\n /// \n private readonly List _previousRigOutputs = [];\n\n /// \n /// 物理演算が処理していない時間\n /// \n private float _currentRemainTime;\n\n /// \n /// Evaluateで利用するパラメータのキャッシュs\n /// \n private float[] _parameterCaches = [];\n\n /// \n /// UpdateParticlesが動くときの入力をキャッシュ\n /// \n private float[] _parameterInputCaches = [];\n\n /// \n /// 重力方向\n /// \n public Vector2 Gravity;\n\n /// \n /// 風の方向\n /// \n public Vector2 Wind;\n\n /// \n /// インスタンスを作成する。\n /// \n /// physics3.jsonが読み込まれいるバッファ\n public CubismPhysics(string buffer)\n {\n // set default options.\n Gravity.Y = -1.0f;\n Gravity.X = 0;\n Wind.X = 0;\n Wind.Y = 0;\n _currentRemainTime = 0.0f;\n\n using var stream = File.Open(buffer, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismPhysicsObjContext.Default.CubismPhysicsObj)\n ?? throw new Exception(\"Load Physics error\");\n\n _physicsRig = new CubismPhysicsRig {\n Gravity = obj.Meta.EffectiveForces.Gravity,\n Wind = obj.Meta.EffectiveForces.Wind,\n SubRigCount = obj.Meta.PhysicsSettingCount,\n Fps = obj.Meta.Fps,\n Settings = new CubismPhysicsSubRig[obj.Meta.PhysicsSettingCount],\n Inputs = new CubismPhysicsInput[obj.Meta.TotalInputCount],\n Outputs = new CubismPhysicsOutput[obj.Meta.TotalOutputCount],\n Particles = new CubismPhysicsParticle[obj.Meta.VertexCount]\n };\n\n _currentRigOutputs.Clear();\n _previousRigOutputs.Clear();\n\n int inputIndex = 0,\n outputIndex = 0,\n particleIndex = 0;\n\n for ( var i = 0; i < _physicsRig.Settings.Length; ++i )\n {\n var set = obj.PhysicsSettings[i];\n _physicsRig.Settings[i] = new CubismPhysicsSubRig {\n NormalizationPosition = new CubismPhysicsNormalization { Minimum = set.Normalization.Position.Minimum, Maximum = set.Normalization.Position.Maximum, Default = set.Normalization.Position.Default },\n NormalizationAngle = new CubismPhysicsNormalization { Minimum = set.Normalization.Angle.Minimum, Maximum = set.Normalization.Angle.Maximum, Default = set.Normalization.Angle.Default },\n // Input\n InputCount = set.Input.Count,\n BaseInputIndex = inputIndex\n };\n\n for ( var j = 0; j < _physicsRig.Settings[i].InputCount; ++j )\n {\n var input = set.Input[j];\n _physicsRig.Inputs[inputIndex + j] = new CubismPhysicsInput { SourceParameterIndex = -1, Weight = input.Weight, Reflect = input.Reflect, Source = new CubismPhysicsParameter { TargetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter, Id = input.Source.Id } };\n\n if ( input.Type == PhysicsTypeTagX )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_X;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputTranslationXFromNormalizedParameterValue;\n }\n else if ( input.Type == PhysicsTypeTagY )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Y;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputTranslationYFromNormalizedParameterValue;\n }\n else if ( input.Type == PhysicsTypeTagAngle )\n {\n _physicsRig.Inputs[inputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Angle;\n _physicsRig.Inputs[inputIndex + j].GetNormalizedParameterValue =\n GetInputAngleFromNormalizedParameterValue;\n }\n }\n\n inputIndex += _physicsRig.Settings[i].InputCount;\n\n // Output\n _physicsRig.Settings[i].OutputCount = set.Output.Count;\n _physicsRig.Settings[i].BaseOutputIndex = outputIndex;\n\n _currentRigOutputs.Add(new float[set.Output.Count]);\n _previousRigOutputs.Add(new float[set.Output.Count]);\n\n for ( var j = 0; j < _physicsRig.Settings[i].OutputCount; ++j )\n {\n var output = set.Output[j];\n _physicsRig.Outputs[outputIndex + j] = new CubismPhysicsOutput {\n DestinationParameterIndex = -1,\n VertexIndex = output.VertexIndex,\n AngleScale = output.Scale,\n Weight = output.Weight,\n Destination = new CubismPhysicsParameter { TargetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter, Id = output.Destination.Id },\n Reflect = output.Reflect\n };\n\n var key = output.Type;\n if ( key == PhysicsTypeTagX )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_X;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputTranslationX;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleTranslationX;\n }\n else if ( key == PhysicsTypeTagY )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Y;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputTranslationY;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleTranslationY;\n }\n else if ( key == PhysicsTypeTagAngle )\n {\n _physicsRig.Outputs[outputIndex + j].Type = CubismPhysicsSource.CubismPhysicsSource_Angle;\n _physicsRig.Outputs[outputIndex + j].GetValue = GetOutputAngle;\n _physicsRig.Outputs[outputIndex + j].GetScale = GetOutputScaleAngle;\n }\n }\n\n outputIndex += _physicsRig.Settings[i].OutputCount;\n\n // Particle\n _physicsRig.Settings[i].ParticleCount = set.Vertices.Count;\n _physicsRig.Settings[i].BaseParticleIndex = particleIndex;\n for ( var j = 0; j < _physicsRig.Settings[i].ParticleCount; ++j )\n {\n var par = set.Vertices[j];\n _physicsRig.Particles[particleIndex + j] = new CubismPhysicsParticle {\n Mobility = par.Mobility,\n Delay = par.Delay,\n Acceleration = par.Acceleration,\n Radius = par.Radius,\n Position = par.Position\n };\n }\n\n particleIndex += _physicsRig.Settings[i].ParticleCount;\n }\n\n Initialize();\n\n _physicsRig.Gravity.Y = 0;\n }\n\n /// \n /// パラメータをリセットする。\n /// \n public void Reset()\n {\n // set default options.\n Gravity.Y = -1.0f;\n Gravity.X = 0.0f;\n Wind.X = 0.0f;\n Wind.Y = 0.0f;\n\n _physicsRig.Gravity.X = 0.0f;\n _physicsRig.Gravity.Y = 0.0f;\n _physicsRig.Wind.X = 0.0f;\n _physicsRig.Wind.Y = 0.0f;\n\n Initialize();\n }\n\n /// \n /// 現在のパラメータ値で物理演算が安定化する状態を演算する。\n /// \n /// 物理演算の結果を適用するモデル\n public unsafe void Stabilization(CubismModel model)\n {\n float totalAngle;\n float weight;\n float radAngle;\n float outputValue;\n Vector2 totalTranslation;\n int i,\n settingIndex,\n particleIndex;\n\n float* parameterValues;\n float* parameterMaximumValues;\n float* parameterMinimumValues;\n float* parameterDefaultValues;\n\n parameterValues = CubismCore.GetParameterValues(model.Model);\n parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n parameterDefaultValues = CubismCore.GetParameterDefaultValues(model.Model);\n\n if ( _parameterCaches.Length < model.GetParameterCount() )\n {\n _parameterCaches = new float[model.GetParameterCount()];\n }\n\n if ( _parameterInputCaches.Length < model.GetParameterCount() )\n {\n _parameterInputCaches = new float[model.GetParameterCount()];\n }\n\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterCaches[j] = parameterValues[j];\n _parameterInputCaches[j] = parameterValues[j];\n }\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n totalAngle = 0.0f;\n totalTranslation.X = 0.0f;\n totalTranslation.Y = 0.0f;\n\n var currentSetting = _physicsRig.Settings[settingIndex];\n var currentInputIndex = currentSetting.BaseInputIndex;\n var currentOutputIndex = currentSetting.BaseOutputIndex;\n var currentParticleIndex = currentSetting.BaseParticleIndex;\n\n // Load input parameters\n for ( i = 0; i < currentSetting.InputCount; ++i )\n {\n weight = _physicsRig.Inputs[i + currentInputIndex].Weight / MaximumWeight;\n\n if ( _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex == -1 )\n {\n _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex = model.GetParameterIndex(_physicsRig.Inputs[i + currentInputIndex].Source.Id);\n }\n\n _physicsRig.Inputs[i + currentInputIndex].GetNormalizedParameterValue(\n ref totalTranslation,\n ref totalAngle,\n parameterValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMinimumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMaximumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterDefaultValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n currentSetting.NormalizationPosition,\n currentSetting.NormalizationAngle,\n _physicsRig.Inputs[i + currentInputIndex].Reflect,\n weight\n );\n\n _parameterCaches[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex] =\n parameterValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex];\n }\n\n radAngle = CubismMath.DegreesToRadian(-totalAngle);\n\n totalTranslation.X = totalTranslation.X * MathF.Cos(radAngle) - totalTranslation.Y * MathF.Sin(radAngle);\n totalTranslation.Y = totalTranslation.X * MathF.Sin(radAngle) + totalTranslation.Y * MathF.Cos(radAngle);\n\n // Calculate particles position.\n UpdateParticlesForStabilization(\n _physicsRig.Particles,\n currentSetting.BaseParticleIndex,\n currentSetting.ParticleCount,\n totalTranslation,\n totalAngle,\n Wind,\n MovementThreshold * currentSetting.NormalizationPosition.Maximum\n );\n\n // Update output parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n particleIndex = _physicsRig.Outputs[i + currentOutputIndex].VertexIndex;\n\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex = model.GetParameterIndex(\n _physicsRig.Outputs[i + currentOutputIndex].Destination.Id);\n }\n\n if ( particleIndex < 1 || particleIndex >= currentSetting.ParticleCount )\n {\n continue;\n }\n\n Vector2 translation = new() { X = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.X - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.X, Y = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.Y - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.Y };\n\n outputValue = _physicsRig.Outputs[i + currentOutputIndex].GetValue(\n translation,\n _physicsRig.Particles,\n currentParticleIndex,\n particleIndex,\n _physicsRig.Outputs[i + currentOutputIndex].Reflect,\n Gravity\n );\n\n _currentRigOutputs[settingIndex][i] = outputValue;\n _previousRigOutputs[settingIndex][i] = outputValue;\n\n UpdateOutputParameterValue(\n ref parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n outputValue,\n _physicsRig.Outputs[i + currentOutputIndex]);\n\n _parameterCaches[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex] = parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex];\n }\n }\n }\n\n /// \n /// 物理演算を評価する。\n /// Pendulum interpolation weights\n /// 振り子の計算結果は保存され、パラメータへの出力は保存された前回の結果で補間されます。\n /// The result of the pendulum calculation is saved and\n /// the output to the parameters is interpolated with the saved previous result of the pendulum calculation.\n /// 図で示すと[1]と[2]で補間されます。\n /// The figure shows the interpolation between [1] and [2].\n /// 補間の重みは最新の振り子計算タイミングと次回のタイミングの間で見た現在時間で決定する。\n /// The weight of the interpolation are determined by the current time seen between\n /// the latest pendulum calculation timing and the next timing.\n /// 図で示すと[2]と[4]の間でみた(3)の位置の重みになる。\n /// Figure shows the weight of position (3) as seen between [2] and [4].\n /// 解釈として振り子計算のタイミングと重み計算のタイミングがズレる。\n /// As an interpretation, the pendulum calculation and weights are misaligned.\n /// physics3.jsonにFPS情報が存在しない場合は常に前の振り子状態で設定される。\n /// If there is no FPS information in physics3.json, it is always set in the previous pendulum state.\n /// この仕様は補間範囲を逸脱したことが原因の震えたような見た目を回避を目的にしている。\n /// The purpose of this specification is to avoid the quivering appearance caused by deviations from the interpolation\n /// range.\n /// ------------ time -------------->\n /// |+++++|------|\n /// <- weight\n /// ==[1]====#=====[2]---(3)----(4)\n /// ^ output contents\n /// \n /// 1 :_previousRigOutputs\n /// 2 :_currentRigOutputs\n /// 3 :_currentRemainTime ( now rendering)\n /// 4 :next particles timing\n /// \n /// @ param model\n /// @ param deltaTimeSeconds rendering delta time.\n /// \n /// 物理演算の結果を適用するモデル\n /// デルタ時間[秒]\n public unsafe void Evaluate(CubismModel model, float deltaTimeSeconds)\n {\n float totalAngle;\n float weight;\n float radAngle;\n float outputValue;\n Vector2 totalTranslation;\n int i,\n settingIndex,\n particleIndex;\n\n if ( 0.0f >= deltaTimeSeconds )\n {\n return;\n }\n\n float physicsDeltaTime;\n _currentRemainTime += deltaTimeSeconds;\n if ( _currentRemainTime > MaxDeltaTime )\n {\n _currentRemainTime = 0.0f;\n }\n\n var parameterValues = CubismCore.GetParameterValues(model.Model);\n var parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n var parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n var parameterDefaultValues = CubismCore.GetParameterDefaultValues(model.Model);\n\n if ( _parameterCaches.Length < model.GetParameterCount() )\n {\n _parameterCaches = new float[model.GetParameterCount()];\n }\n\n if ( _parameterInputCaches.Length < model.GetParameterCount() )\n {\n _parameterInputCaches = new float[model.GetParameterCount()];\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterInputCaches[j] = parameterValues[j];\n }\n }\n\n if ( _physicsRig.Fps > 0.0f )\n {\n physicsDeltaTime = 1.0f / _physicsRig.Fps;\n }\n else\n {\n physicsDeltaTime = deltaTimeSeconds;\n }\n\n CubismPhysicsSubRig currentSetting;\n CubismPhysicsOutput currentOutputs;\n\n while ( _currentRemainTime >= physicsDeltaTime )\n {\n // copyRigOutputs _currentRigOutputs to _previousRigOutputs\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n if ( currentSetting.BaseOutputIndex >= _physicsRig.Outputs.Length )\n {\n continue;\n }\n\n currentOutputs = _physicsRig.Outputs[currentSetting.BaseOutputIndex];\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n _previousRigOutputs[settingIndex][i] = _currentRigOutputs[settingIndex][i];\n }\n }\n\n // 入力キャッシュとパラメータで線形補間してUpdateParticlesするタイミングでの入力を計算する。\n // Calculate the input at the timing to UpdateParticles by linear interpolation with the _parameterInputCaches and parameterValues.\n // _parameterCachesはグループ間での値の伝搬の役割があるので_parameterInputCachesとの分離が必要。\n // _parameterCaches needs to be separated from _parameterInputCaches because of its role in propagating values between groups.\n var inputWeight = physicsDeltaTime / _currentRemainTime;\n for ( var j = 0; j < model.GetParameterCount(); ++j )\n {\n _parameterCaches[j] = _parameterInputCaches[j] * (1.0f - inputWeight) + parameterValues[j] * inputWeight;\n _parameterInputCaches[j] = _parameterCaches[j];\n }\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n totalAngle = 0.0f;\n totalTranslation.X = 0.0f;\n totalTranslation.Y = 0.0f;\n currentSetting = _physicsRig.Settings[settingIndex];\n var currentInputIndex = currentSetting.BaseInputIndex;\n var currentOutputIndex = currentSetting.BaseOutputIndex;\n var currentParticleIndex = currentSetting.BaseParticleIndex;\n\n // Load input parameters.\n for ( i = 0; i < currentSetting.InputCount; ++i )\n {\n weight = _physicsRig.Inputs[i + currentInputIndex].Weight / MaximumWeight;\n\n if ( _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex == -1 )\n {\n _physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex = model.GetParameterIndex(_physicsRig.Inputs[i + currentInputIndex].Source.Id);\n }\n\n _physicsRig.Inputs[i + currentInputIndex].GetNormalizedParameterValue(\n ref totalTranslation,\n ref totalAngle,\n _parameterCaches[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMinimumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterMaximumValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n parameterDefaultValues[_physicsRig.Inputs[i + currentInputIndex].SourceParameterIndex],\n currentSetting.NormalizationPosition,\n currentSetting.NormalizationAngle,\n _physicsRig.Inputs[i + currentInputIndex].Reflect,\n weight\n );\n }\n\n radAngle = CubismMath.DegreesToRadian(-totalAngle);\n\n totalTranslation.X = totalTranslation.X * MathF.Cos(radAngle) - totalTranslation.Y * MathF.Sin(radAngle);\n totalTranslation.Y = totalTranslation.X * MathF.Sin(radAngle) + totalTranslation.Y * MathF.Cos(radAngle);\n\n // Calculate particles position.\n UpdateParticles(\n _physicsRig.Particles,\n currentParticleIndex,\n currentSetting.ParticleCount,\n totalTranslation,\n totalAngle,\n Wind,\n MovementThreshold * currentSetting.NormalizationPosition.Maximum,\n physicsDeltaTime,\n AirResistance\n );\n\n // Update output parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n particleIndex = _physicsRig.Outputs[i + currentOutputIndex].VertexIndex;\n\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex = model.GetParameterIndex(_physicsRig.Outputs[i + currentOutputIndex].Destination.Id);\n }\n\n if ( particleIndex < 1 || particleIndex >= currentSetting.ParticleCount )\n {\n continue;\n }\n\n Vector2 translation;\n translation.X = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.X - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.X;\n translation.Y = _physicsRig.Particles[particleIndex + currentParticleIndex].Position.Y - _physicsRig.Particles[particleIndex - 1 + currentParticleIndex].Position.Y;\n\n outputValue = _physicsRig.Outputs[i + currentOutputIndex].GetValue(\n translation,\n _physicsRig.Particles,\n currentParticleIndex,\n particleIndex,\n _physicsRig.Outputs[i + currentOutputIndex].Reflect,\n Gravity\n );\n\n _currentRigOutputs[settingIndex][i] = outputValue;\n\n UpdateOutputParameterValue(\n ref _parameterCaches[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n outputValue,\n _physicsRig.Outputs[i + currentOutputIndex]);\n }\n }\n\n _currentRemainTime -= physicsDeltaTime;\n }\n\n var alpha = _currentRemainTime / physicsDeltaTime;\n Interpolate(model, alpha);\n }\n\n /// \n /// オプションを設定する。\n /// \n public void SetOptions(Vector2 gravity, Vector2 wind)\n {\n Gravity = gravity;\n Wind = wind;\n }\n\n /// \n /// オプションを取得する。\n /// \n /// オプション\n public (Vector2 Gravity, Vector2 Wind) GetOptions() { return (Gravity, Wind); }\n\n /// \n /// 初期化する。\n /// \n private void Initialize()\n {\n CubismPhysicsSubRig currentSetting;\n int i,\n settingIndex;\n\n Vector2 radius;\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n var index = currentSetting.BaseParticleIndex;\n\n // Initialize the top of particle.\n _physicsRig.Particles[index].InitialPosition = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[index].LastPosition = _physicsRig.Particles[index].InitialPosition;\n _physicsRig.Particles[index].LastGravity = new Vector2(0.0f, -1.0f);\n _physicsRig.Particles[index].LastGravity.Y *= -1.0f;\n _physicsRig.Particles[index].Velocity = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[index].Force = new Vector2(0.0f, 0.0f);\n\n // Initialize particles.\n for ( i = 1; i < currentSetting.ParticleCount; ++i )\n {\n radius = new Vector2(0.0f, _physicsRig.Particles[i + index].Radius);\n _physicsRig.Particles[i + index].InitialPosition = _physicsRig.Particles[i - 1 + index].InitialPosition + radius;\n _physicsRig.Particles[i + index].Position = _physicsRig.Particles[i + index].InitialPosition;\n _physicsRig.Particles[i + index].LastPosition = _physicsRig.Particles[i + index].InitialPosition;\n _physicsRig.Particles[i + index].LastGravity = new Vector2(0.0f, -1.0f);\n _physicsRig.Particles[i + index].LastGravity.Y *= -1.0f;\n _physicsRig.Particles[i + index].Velocity = new Vector2(0.0f, 0.0f);\n _physicsRig.Particles[i + index].Force = new Vector2(0.0f, 0.0f);\n }\n }\n }\n\n /// \n /// 振り子演算の最新の結果と一つ前の結果から指定した重みで適用する。\n /// \n /// 物理演算の結果を適用するモデル\n /// 最新結果の重み\n private unsafe void Interpolate(CubismModel model, float weight)\n {\n int i,\n settingIndex;\n\n float* parameterValues;\n float* parameterMaximumValues;\n float* parameterMinimumValues;\n\n int currentOutputIndex;\n CubismPhysicsSubRig currentSetting;\n\n parameterValues = CubismCore.GetParameterValues(model.Model);\n parameterMaximumValues = CubismCore.GetParameterMaximumValues(model.Model);\n parameterMinimumValues = CubismCore.GetParameterMinimumValues(model.Model);\n\n for ( settingIndex = 0; settingIndex < _physicsRig.SubRigCount; ++settingIndex )\n {\n currentSetting = _physicsRig.Settings[settingIndex];\n currentOutputIndex = currentSetting.BaseOutputIndex;\n\n // Load input parameters.\n for ( i = 0; i < currentSetting.OutputCount; ++i )\n {\n if ( _physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex == -1 )\n {\n continue;\n }\n\n var value = _previousRigOutputs[settingIndex][i] * (1 - weight) + _currentRigOutputs[settingIndex][i] * weight;\n\n UpdateOutputParameterValue(\n ref parameterValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMinimumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n parameterMaximumValues[_physicsRig.Outputs[i + currentOutputIndex].DestinationParameterIndex],\n value,\n _physicsRig.Outputs[i + currentOutputIndex]\n );\n }\n }\n }\n\n private float GetRangeValue(float min, float max)\n {\n var maxValue = CubismMath.Max(min, max);\n var minValue = CubismMath.Min(min, max);\n\n return MathF.Abs(maxValue - minValue);\n }\n\n /// Gets sign.\n /// \n /// @param value Evaluation target value.\n /// \n /// @return Sign of value.\n private static int Sign(float value)\n {\n var ret = 0;\n\n if ( value > 0.0f )\n {\n ret = 1;\n }\n else if ( value < 0.0f )\n {\n ret = -1;\n }\n\n return ret;\n }\n\n private float GetDefaultValue(float min, float max)\n {\n var minValue = CubismMath.Min(min, max);\n\n return minValue + GetRangeValue(min, max) / 2.0f;\n }\n\n private float NormalizeParameterValue(\n float value,\n float parameterMinimum,\n float parameterMaximum,\n float parameterDefault,\n float normalizedMinimum,\n float normalizedMaximum,\n float normalizedDefault,\n bool isInverted)\n {\n var result = 0.0f;\n\n var maxValue = CubismMath.Max(parameterMaximum, parameterMinimum);\n\n if ( maxValue < value )\n {\n value = maxValue;\n }\n\n var minValue = CubismMath.Min(parameterMaximum, parameterMinimum);\n\n if ( minValue > value )\n {\n value = minValue;\n }\n\n var minNormValue = CubismMath.Min(normalizedMinimum, normalizedMaximum);\n var maxNormValue = CubismMath.Max(normalizedMinimum, normalizedMaximum);\n var middleNormValue = normalizedDefault;\n\n var middleValue = GetDefaultValue(minValue, maxValue);\n var paramValue = value - middleValue;\n\n switch ( Sign(paramValue) )\n {\n case 1:\n {\n var nLength = maxNormValue - middleNormValue;\n var pLength = maxValue - middleValue;\n if ( pLength != 0.0f )\n {\n result = paramValue * (nLength / pLength);\n result += middleNormValue;\n }\n\n break;\n }\n case -1:\n {\n var nLength = minNormValue - middleNormValue;\n var pLength = minValue - middleValue;\n if ( pLength != 0.0f )\n {\n result = paramValue * (nLength / pLength);\n result += middleNormValue;\n }\n\n break;\n }\n case 0:\n {\n result = middleNormValue;\n\n break;\n }\n }\n\n return isInverted ? result : result * -1.0f;\n }\n\n private void GetInputTranslationXFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle, bool isInverted,\n float weight)\n {\n targetTranslation.X += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationPosition.Minimum,\n normalizationPosition.Maximum,\n normalizationPosition.Default,\n isInverted\n ) * weight;\n }\n\n private void GetInputTranslationYFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted, float weight)\n {\n targetTranslation.Y += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationPosition.Minimum,\n normalizationPosition.Maximum,\n normalizationPosition.Default,\n isInverted\n ) * weight;\n }\n\n private void GetInputAngleFromNormalizedParameterValue(ref Vector2 targetTranslation, ref float targetAngle, float value,\n float parameterMinimumValue, float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted, float weight)\n {\n targetAngle += NormalizeParameterValue(\n value,\n parameterMinimumValue,\n parameterMaximumValue,\n parameterDefaultValue,\n normalizationAngle.Minimum,\n normalizationAngle.Maximum,\n normalizationAngle.Default,\n isInverted\n ) * weight;\n }\n\n private float GetOutputTranslationX(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n var outputValue = translation.X;\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputTranslationY(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n var outputValue = translation.Y;\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputAngle(Vector2 translation, CubismPhysicsParticle[] particles, int start,\n int particleIndex, bool isInverted, Vector2 parentGravity)\n {\n float outputValue;\n\n if ( particleIndex >= 2 )\n {\n parentGravity = particles[particleIndex - 1 + start].Position - particles[particleIndex - 2 + start].Position;\n }\n else\n {\n parentGravity *= -1.0f;\n }\n\n outputValue = CubismMath.DirectionToRadian(parentGravity, translation);\n\n if ( isInverted )\n {\n outputValue *= -1.0f;\n }\n\n return outputValue;\n }\n\n private float GetOutputScaleTranslationX(Vector2 translationScale, float angleScale) { return translationScale.X; }\n\n private float GetOutputScaleTranslationY(Vector2 translationScale, float angleScale) { return translationScale.Y; }\n\n private float GetOutputScaleAngle(Vector2 translationScale, float angleScale) { return angleScale; }\n\n /// Updates particles.\n /// \n /// @param strand Target array of particle.\n /// @param strandCount Count of particle.\n /// @param totalTranslation Total translation value.\n /// @param totalAngle Total angle.\n /// @param windDirection Direction of wind.\n /// @param thresholdValue Threshold of movement.\n /// @param deltaTimeSeconds Delta time.\n /// @param airResistance Air resistance.\n private static void UpdateParticles(CubismPhysicsParticle[] strand, int start, int strandCount, Vector2 totalTranslation, float totalAngle,\n Vector2 windDirection, float thresholdValue, float deltaTimeSeconds, float airResistance)\n {\n int i;\n float totalRadian;\n float delay;\n float radian;\n Vector2 currentGravity;\n Vector2 direction;\n Vector2 velocity;\n Vector2 force;\n Vector2 newDirection;\n\n strand[start].Position = totalTranslation;\n\n totalRadian = CubismMath.DegreesToRadian(totalAngle);\n currentGravity = CubismMath.RadianToDirection(totalRadian);\n currentGravity = Vector2.Normalize(currentGravity);\n\n for ( i = 1; i < strandCount; ++i )\n {\n strand[i + start].Force = currentGravity * strand[i + start].Acceleration + windDirection;\n\n strand[i + start].LastPosition = strand[i + start].Position;\n\n delay = strand[i + start].Delay * deltaTimeSeconds * 30.0f;\n\n direction.X = strand[i + start].Position.X - strand[i - 1 + start].Position.X;\n direction.Y = strand[i + start].Position.Y - strand[i - 1 + start].Position.Y;\n\n radian = CubismMath.DirectionToRadian(strand[i + start].LastGravity, currentGravity) / airResistance;\n\n direction.X = MathF.Cos(radian) * direction.X - direction.Y * MathF.Sin(radian);\n direction.Y = MathF.Sin(radian) * direction.X + direction.Y * MathF.Cos(radian);\n\n strand[i + start].Position = strand[i - 1 + start].Position + direction;\n\n velocity.X = strand[i + start].Velocity.X * delay;\n velocity.Y = strand[i + start].Velocity.Y * delay;\n force = strand[i + start].Force * delay * delay;\n\n strand[i + start].Position = strand[i + start].Position + velocity + force;\n\n newDirection = strand[i + start].Position - strand[i - 1 + start].Position;\n\n newDirection = Vector2.Normalize(newDirection);\n\n strand[i + start].Position = strand[i - 1 + start].Position + newDirection * strand[i + start].Radius;\n\n if ( MathF.Abs(strand[i + start].Position.X) < thresholdValue )\n {\n strand[i + start].Position.X = 0.0f;\n }\n\n if ( delay != 0.0f )\n {\n strand[i + start].Velocity.X = strand[i + start].Position.X - strand[i + start].LastPosition.X;\n strand[i + start].Velocity.Y = strand[i + start].Position.Y - strand[i + start].LastPosition.Y;\n strand[i + start].Velocity /= delay;\n strand[i + start].Velocity *= strand[i + start].Mobility;\n }\n\n strand[i + start].Force = new Vector2(0.0f, 0.0f);\n strand[i + start].LastGravity = currentGravity;\n }\n }\n\n /**\n * Updates particles for stabilization.\n * \n * @param strand Target array of particle.\n * @param strandCount Count of particle.\n * @param totalTranslation Total translation value.\n * @param totalAngle Total angle.\n * @param windDirection Direction of Wind.\n * @param thresholdValue Threshold of movement.\n */\n private static void UpdateParticlesForStabilization(CubismPhysicsParticle[] strand, int start, int strandCount, Vector2 totalTranslation, float totalAngle,\n Vector2 windDirection, float thresholdValue)\n {\n int i;\n float totalRadian;\n Vector2 currentGravity;\n Vector2 force;\n\n strand[start].Position = totalTranslation;\n\n totalRadian = CubismMath.DegreesToRadian(totalAngle);\n currentGravity = CubismMath.RadianToDirection(totalRadian);\n currentGravity = Vector2.Normalize(currentGravity);\n\n for ( i = 1; i < strandCount; ++i )\n {\n strand[i + start].Force = currentGravity * strand[i + start].Acceleration + windDirection;\n\n strand[i + start].LastPosition = strand[i + start].Position;\n\n strand[i + start].Velocity = new Vector2(0.0f, 0.0f);\n\n force = strand[i + start].Force;\n force = Vector2.Normalize(force);\n\n force *= strand[i + start].Radius;\n strand[i + start].Position = strand[i - 1].Position + force;\n\n if ( MathF.Abs(strand[i + start].Position.X) < thresholdValue )\n {\n strand[i + start].Position.X = 0.0f;\n }\n\n strand[i + start].Force = new Vector2(0.0f, 0.0f);\n strand[i + start].LastGravity = currentGravity;\n }\n }\n\n /// Updates output parameter value.\n /// \n /// @param parameterValue Target parameter value.\n /// @param parameterValueMinimum Minimum of parameter value.\n /// @param parameterValueMaximum Maximum of parameter value.\n /// @param translation Translation value.\n private static void UpdateOutputParameterValue(ref float parameterValue, float parameterValueMinimum, float parameterValueMaximum,\n float translation, CubismPhysicsOutput output)\n {\n float outputScale;\n float value;\n float weight;\n\n outputScale = output.GetScale(output.TranslationScale, output.AngleScale);\n\n value = translation * outputScale;\n\n if ( value < parameterValueMinimum )\n {\n if ( value < output.ValueBelowMinimum )\n {\n output.ValueBelowMinimum = value;\n }\n\n value = parameterValueMinimum;\n }\n else if ( value > parameterValueMaximum )\n {\n if ( value > output.ValueExceededMaximum )\n {\n output.ValueExceededMaximum = value;\n }\n\n value = parameterValueMaximum;\n }\n\n weight = output.Weight / MaximumWeight;\n\n if ( weight >= 1.0f )\n {\n parameterValue = value;\n }\n else\n {\n value = parameterValue * (1.0f - weight) + value * weight;\n parameterValue = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismClippingManager_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\npublic class CubismClippingManager_OpenGLES2(OpenGLApi gl) : CubismClippingManager(RenderType.OpenGL)\n{\n /// \n /// クリッピングコンテキストを作成する。モデル描画時に実行する。\n /// \n /// モデルのインスタンス\n /// レンダラのインスタンス\n /// フレームバッファ\n /// ビューポート\n internal unsafe void SetupClippingContext(CubismModel model, CubismRenderer_OpenGLES2 renderer, int lastFBO, int[] lastViewport)\n {\n // 全てのクリッピングを用意する\n // 同じクリップ(複数の場合はまとめて1つのクリップ)を使う場合は1度だけ設定する\n var usingClipCount = 0;\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // 1つのクリッピングマスクに関して\n var cc = ClippingContextListForMask[clipIndex];\n\n // このクリップを利用する描画オブジェクト群全体を囲む矩形を計算\n CalcClippedDrawTotalBounds(model, cc!);\n\n if ( cc!.IsUsing )\n {\n usingClipCount++; //使用中としてカウント\n }\n }\n\n if ( usingClipCount <= 0 )\n {\n return;\n }\n\n // マスク作成処理\n // 生成したOffscreenSurfaceと同じサイズでビューポートを設定\n gl.Viewport(0, 0, (int)ClippingMaskBufferSize.X, (int)ClippingMaskBufferSize.Y);\n\n // 後の計算のためにインデックスの最初をセット\n CurrentMaskBuffer = renderer.GetMaskBuffer(0);\n // ----- マスク描画処理 -----\n CurrentMaskBuffer.BeginDraw(lastFBO);\n\n renderer.PreDraw(); // バッファをクリアする\n\n // 各マスクのレイアウトを決定していく\n SetupLayoutBounds(usingClipCount);\n\n // サイズがレンダーテクスチャの枚数と合わない場合は合わせる\n if ( ClearedMaskBufferFlags.Count != RenderTextureCount )\n {\n ClearedMaskBufferFlags.Clear();\n\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags.Add(false);\n }\n }\n else\n {\n // マスクのクリアフラグを毎フレーム開始時に初期化\n for ( var i = 0; i < RenderTextureCount; ++i )\n {\n ClearedMaskBufferFlags[i] = false;\n }\n }\n\n // 実際にマスクを生成する\n // 全てのマスクをどの様にレイアウトして描くかを決定し、ClipContext , ClippedDrawContext に記憶する\n for ( var clipIndex = 0; clipIndex < ClippingContextListForMask.Count; clipIndex++ )\n {\n // --- 実際に1つのマスクを描く ---\n var clipContext = ClippingContextListForMask[clipIndex];\n var allClippedDrawRect = clipContext!.AllClippedDrawRect; //このマスクを使う、全ての描画オブジェクトの論理座標上の囲み矩形\n var layoutBoundsOnTex01 = clipContext.LayoutBounds; //この中にマスクを収める\n var MARGIN = 0.05f;\n\n // clipContextに設定したオフスクリーンサーフェイスをインデックスで取得\n var clipContextOffscreenSurface = renderer.GetMaskBuffer(clipContext.BufferIndex);\n\n // 現在のオフスクリーンサーフェイスがclipContextのものと異なる場合\n if ( CurrentMaskBuffer != clipContextOffscreenSurface )\n {\n CurrentMaskBuffer.EndDraw();\n CurrentMaskBuffer = clipContextOffscreenSurface;\n // マスク用RenderTextureをactiveにセット\n CurrentMaskBuffer.BeginDraw(lastFBO);\n\n // バッファをクリアする。\n renderer.PreDraw();\n }\n\n // モデル座標上の矩形を、適宜マージンを付けて使う\n TmpBoundsOnModel.SetRect(allClippedDrawRect);\n TmpBoundsOnModel.Expand(allClippedDrawRect.Width * MARGIN, allClippedDrawRect.Height * MARGIN);\n //########## 本来は割り当てられた領域の全体を使わず必要最低限のサイズがよい\n // シェーダ用の計算式を求める。回転を考慮しない場合は以下のとおり\n // movePeriod' = movePeriod * scaleX + offX [[ movePeriod' = (movePeriod - tmpBoundsOnModel.movePeriod)*scale + layoutBoundsOnTex01.movePeriod ]]\n var scaleX = layoutBoundsOnTex01.Width / TmpBoundsOnModel.Width;\n var scaleY = layoutBoundsOnTex01.Height / TmpBoundsOnModel.Height;\n\n // マスク生成時に使う行列を求める\n CreateMatrixForMask(false, layoutBoundsOnTex01, scaleX, scaleY);\n\n clipContext.MatrixForMask.SetMatrix(TmpMatrixForMask.Tr);\n clipContext.MatrixForDraw.SetMatrix(TmpMatrixForDraw.Tr);\n\n // 実際の描画を行う\n var clipDrawCount = clipContext.ClippingIdCount;\n for ( var i = 0; i < clipDrawCount; i++ )\n {\n var clipDrawIndex = clipContext.ClippingIdList[i];\n\n // 頂点情報が更新されておらず、信頼性がない場合は描画をパスする\n if ( !model.GetDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex) )\n {\n continue;\n }\n\n renderer.IsCulling = model.GetDrawableCulling(clipDrawIndex);\n\n // マスクがクリアされていないなら処理する\n if ( !ClearedMaskBufferFlags[clipContext.BufferIndex] )\n {\n // マスクをクリアする\n // 1が無効(描かれない)領域、0が有効(描かれる)領域。(シェーダーCd*Csで0に近い値をかけてマスクを作る。1をかけると何も起こらない)\n gl.ClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n gl.Clear(gl.GL_COLOR_BUFFER_BIT);\n ClearedMaskBufferFlags[clipContext.BufferIndex] = true;\n }\n\n // 今回専用の変換を適用して描く\n // チャンネルも切り替える必要がある(A,R,G,B)\n renderer.ClippingContextBufferForMask = clipContext;\n\n renderer.DrawMeshOpenGL(model, clipDrawIndex);\n }\n }\n\n // --- 後処理 ---\n CurrentMaskBuffer.EndDraw();\n renderer.ClippingContextBufferForMask = null;\n gl.Viewport(lastViewport[0], lastViewport[1], lastViewport[2], lastViewport[3]);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismEyeBlink.cs", "//IDで指定された目のパラメータが、0のときに閉じるなら true 、1の時に閉じるなら false 。\n//#define CloseIfZero\n\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 自動まばたき機能を提供する。\n/// \npublic class CubismEyeBlink\n{\n private readonly Random _random = new();\n\n /// \n /// 操作対象のパラメータのIDのリスト\n /// \n public readonly List ParameterIds = [];\n\n /// \n /// まばたきの間隔[秒]\n /// \n private float _blinkingIntervalSeconds;\n\n /// \n /// 現在の状態\n /// \n private EyeState _blinkingState;\n\n /// \n /// まぶたを閉じている動作の所要時間[秒]\n /// \n private float _closedSeconds;\n\n /// \n /// まぶたを閉じる動作の所要時間[秒]\n /// \n private float _closingSeconds;\n\n /// \n /// 次のまばたきの時刻[秒]\n /// \n private float _nextBlinkingTime;\n\n /// \n /// まぶたを開く動作の所要時間[秒]\n /// \n private float _openingSeconds;\n\n /// \n /// 現在の状態が開始した時刻[秒]\n /// \n private float _stateStartTimeSeconds;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n private float _userTimeSeconds;\n\n /// \n /// インスタンスを作成する。\n /// \n /// モデルの設定情報\n public CubismEyeBlink(ModelSettingObj modelSetting)\n {\n _blinkingState = EyeState.First;\n _blinkingIntervalSeconds = 4.0f;\n _closingSeconds = 0.1f;\n _closedSeconds = 0.05f;\n _openingSeconds = 0.15f;\n\n foreach ( var item in modelSetting.Groups )\n {\n if ( item.Name == CubismModelSettingJson.EyeBlink )\n {\n foreach ( var item1 in item.Ids )\n {\n if ( item1 == null )\n {\n continue;\n }\n\n var item2 = CubismFramework.CubismIdManager.GetId(item1);\n ParameterIds.Add(item2);\n }\n\n break;\n }\n }\n }\n\n /// \n /// まばたきの間隔を設定する。\n /// \n /// まばたきの間隔の時間[秒]\n public void SetBlinkingInterval(float blinkingInterval) { _blinkingIntervalSeconds = blinkingInterval; }\n\n /// \n /// まばたきのモーションの詳細設定を行う。\n /// \n /// まぶたを閉じる動作の所要時間[秒]\n /// まぶたを閉じている動作の所要時間[秒]\n /// まぶたを開く動作の所要時間[秒]\n public void SetBlinkingSettings(float closing, float closed, float opening)\n {\n _closingSeconds = closing;\n _closedSeconds = closed;\n _openingSeconds = opening;\n }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n _userTimeSeconds += deltaTimeSeconds;\n float parameterValue;\n float t;\n switch ( _blinkingState )\n {\n case EyeState.Closing:\n t = (_userTimeSeconds - _stateStartTimeSeconds) / _closingSeconds;\n\n if ( t >= 1.0f )\n {\n t = 1.0f;\n _blinkingState = EyeState.Closed;\n _stateStartTimeSeconds = _userTimeSeconds;\n }\n\n parameterValue = 1.0f - t;\n\n break;\n case EyeState.Closed:\n t = (_userTimeSeconds - _stateStartTimeSeconds) / _closedSeconds;\n\n if ( t >= 1.0f )\n {\n _blinkingState = EyeState.Opening;\n _stateStartTimeSeconds = _userTimeSeconds;\n }\n\n parameterValue = 0.0f;\n\n break;\n case EyeState.Opening:\n t = (_userTimeSeconds - _stateStartTimeSeconds) / _openingSeconds;\n\n if ( t >= 1.0f )\n {\n t = 1.0f;\n _blinkingState = EyeState.Interval;\n _nextBlinkingTime = DetermineNextBlinkingTiming();\n }\n\n parameterValue = t;\n\n break;\n case EyeState.Interval:\n if ( _nextBlinkingTime < _userTimeSeconds )\n {\n _blinkingState = EyeState.Closing;\n _stateStartTimeSeconds = _userTimeSeconds;\n }\n\n parameterValue = 1.0f;\n\n break;\n case EyeState.First:\n default:\n _blinkingState = EyeState.Interval;\n _nextBlinkingTime = DetermineNextBlinkingTiming();\n\n parameterValue = 1.0f;\n\n break;\n }\n#if CloseIfZero\n parameterValue = -parameterValue;\n#endif\n\n foreach ( var item in ParameterIds )\n {\n model.SetParameterValue(item, parameterValue);\n }\n }\n\n /// \n /// 次のまばたきのタイミングを決定する。\n /// \n /// 次のまばたきを行う時刻[秒]\n private float DetermineNextBlinkingTiming()\n {\n float r = _random.Next() / int.MaxValue;\n\n return _userTimeSeconds + r * (2.0f * _blinkingIntervalSeconds - 1.0f);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppLive2DManager.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// サンプルアプリケーションにおいてCubismModelを管理するクラス\n/// モデル生成と破棄、タップイベントの処理、モデル切り替えを行う。\n/// \n/// \n/// コンストラクタ\n/// \npublic class LAppLive2DManager(LAppDelegate lapp) : IDisposable\n{\n /// \n /// モデルインスタンスのコンテナ\n /// \n private readonly List _models = [];\n\n private readonly CubismMatrix44 _projection = new();\n\n /// \n /// モデル描画に用いるView行列\n /// \n public CubismMatrix44 ViewMatrix { get; } = new();\n\n public void Dispose() { ReleaseAllModel(); }\n\n public event Action? MotionFinished;\n\n /// \n /// 現在のシーンで保持しているモデルを返す\n /// \n /// モデルリストのインデックス値\n /// モデルのインスタンスを返す。インデックス値が範囲外の場合はNULLを返す。\n public LAppModel GetModel(int no) { return _models[no]; }\n\n /// \n /// 現在のシーンで保持しているすべてのモデルを解放する\n /// \n public void ReleaseAllModel()\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n _models[i].Dispose();\n }\n\n _models.Clear();\n }\n\n /// \n /// 画面をドラッグしたときの処理\n /// \n /// 画面のX座標\n /// 画面のY座標\n public void OnDrag(float x, float y)\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n var model = GetModel(i);\n\n model.SetDragging(x, y);\n }\n }\n\n /// \n /// 画面をタップしたときの処理\n /// \n /// 画面のX座標\n /// 画面のY座標\n public void OnTap(float x, float y)\n {\n CubismLog.Debug($\"[Live2D]tap point: x:{x:0.00} y:{y:0.00}\");\n\n for ( var i = 0; i < _models.Count; i++ )\n {\n if ( _models[i].HitTest(LAppDefine.HitAreaNameHead, x, y) )\n {\n CubismLog.Debug($\"[Live2D]hit area: [{LAppDefine.HitAreaNameHead}]\");\n _models[i].SetRandomExpression();\n }\n else if ( _models[i].HitTest(LAppDefine.HitAreaNameBody, x, y) )\n {\n CubismLog.Debug($\"[Live2D]hit area: [{LAppDefine.HitAreaNameBody}]\");\n _models[i].StartRandomMotion(LAppDefine.MotionGroupTapBody, MotionPriority.PriorityNormal, OnFinishedMotion);\n }\n }\n }\n\n private void OnFinishedMotion(CubismModel model, ACubismMotion self)\n {\n CubismLog.Info($\"[Live2D]Motion Finished: {self}\");\n MotionFinished?.Invoke(model, self);\n }\n\n /// \n /// 画面を更新するときの処理\n /// モデルの更新処理および描画処理を行う\n /// \n public void OnUpdate()\n {\n lapp.GL.GetWindowSize(out var width, out var height);\n\n var modelCount = _models.Count;\n foreach ( var model in _models )\n {\n _projection.LoadIdentity();\n\n if ( model.Model.GetCanvasWidth() > 1.0f && width < height )\n {\n // 横に長いモデルを縦長ウィンドウに表示する際モデルの横サイズでscaleを算出する\n model.ModelMatrix.SetWidth(2.0f);\n _projection.Scale(1.0f, (float)width / height);\n }\n else\n {\n _projection.Scale((float)height / width, 1.0f);\n }\n\n // 必要があればここで乗算\n if ( ViewMatrix != null )\n {\n _projection.MultiplyByMatrix(ViewMatrix);\n }\n\n model.Update();\n model.Draw(_projection); // 参照渡しなのでprojectionは変質する\n }\n }\n\n public LAppModel LoadModel(string dir, string name)\n {\n CubismLog.Debug($\"[Live2D]model load: {name}\");\n\n // ModelDir[]に保持したディレクトリ名から\n // model3.jsonのパスを決定する.\n // ディレクトリ名とmodel3.jsonの名前を一致させておくこと.\n if ( !dir.EndsWith('\\\\') && !dir.EndsWith('/') )\n {\n dir = Path.GetFullPath(dir + '/');\n }\n\n var modelJsonName = Path.GetFullPath($\"{dir}{name}\");\n if ( !File.Exists(modelJsonName) )\n {\n modelJsonName = Path.GetFullPath($\"{dir}{name}.model3.json\");\n }\n\n if ( !File.Exists(modelJsonName) )\n {\n dir = Path.GetFullPath(dir + name + '/');\n modelJsonName = Path.GetFullPath($\"{dir}{name}.model3.json\");\n }\n\n if ( !File.Exists(modelJsonName) )\n {\n throw new Exception($\"[Live2D]File not found: {modelJsonName}\");\n }\n\n var model = new LAppModel(lapp, dir, modelJsonName);\n _models.Add(model);\n\n return model;\n }\n\n public void RemoveModel(int index)\n {\n if ( _models.Count > index )\n {\n var model = _models[index];\n _models.RemoveAt(index);\n model.Dispose();\n }\n }\n\n /// \n /// モデル個数を得る\n /// \n /// 所持モデル個数\n public int GetModelNum() { return _models.Count; }\n\n public async void StartSpeaking(string filePath)\n {\n for ( var i = 0; i < _models.Count; i++ )\n {\n _models[i]._wavFileHandler.Start(filePath);\n await _models[i]._wavFileHandler.LoadWavFile(filePath);\n _models[i].StartMotion(LAppDefine.MotionGroupIdle, 0, MotionPriority.PriorityIdle, OnFinishedMotion);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismRenderer.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\n/// \n/// モデル描画を処理するレンダラ\n/// サブクラスに環境依存の描画命令を記述する\n/// \npublic abstract class CubismRenderer : IDisposable\n{\n /// \n /// Model-View-Projection 行列\n /// \n private readonly CubismMatrix44 _mvpMatrix4x4 = new();\n\n public CubismTextureColor ClearColor = new(0, 0, 0, 0);\n\n /// \n /// モデル自体のカラー(RGBA)\n /// \n public CubismTextureColor ModelColor = new();\n\n /// \n /// レンダラのインスタンスを生成して取得する\n /// \n public CubismRenderer(CubismModel model)\n {\n _mvpMatrix4x4.LoadIdentity();\n Model = model ?? throw new Exception(\"model is null\");\n }\n\n /// \n /// テクスチャの異方性フィルタリングのパラメータ\n /// \n public float Anisotropy { get; set; }\n\n /// \n /// レンダリング対象のモデル\n /// \n public CubismModel Model { get; private set; }\n\n /// \n /// 乗算済みαならtrue\n /// \n public bool IsPremultipliedAlpha { get; set; }\n\n /// \n /// カリングが有効ならtrue\n /// \n public bool IsCulling { get; set; }\n\n /// \n /// falseの場合、マスクを纏めて描画する trueの場合、マスクはパーツ描画ごとに書き直す\n /// \n public bool UseHighPrecisionMask { get; set; }\n\n /// \n /// レンダラのインスタンスを解放する\n /// \n public abstract void Dispose();\n\n /// \n /// モデルを描画する\n /// \n public void DrawModel()\n {\n /**\n * DoDrawModelの描画前と描画後に以下の関数を呼んでください。\n * ・SaveProfile();\n * ・RestoreProfile();\n * これはレンダラの描画設定を保存・復帰させることで、\n * モデル描画直前の状態に戻すための処理です。\n */\n\n SaveProfile();\n\n DoDrawModel();\n\n RestoreProfile();\n }\n\n /// \n /// Model-View-Projection 行列をセットする\n /// 配列は複製されるので元の配列は外で破棄して良い\n /// \n /// Model-View-Projection 行列\n public void SetMvpMatrix(CubismMatrix44 matrix4x4) { _mvpMatrix4x4.SetMatrix(matrix4x4.Tr); }\n\n /// \n /// Model-View-Projection 行列を取得する\n /// \n /// Model-View-Projection 行列\n public CubismMatrix44 GetMvpMatrix() { return _mvpMatrix4x4; }\n\n /// \n /// 透明度を考慮したモデルの色を計算する。\n /// \n /// 透明度\n /// RGBAのカラー情報\n public CubismTextureColor GetModelColorWithOpacity(float opacity)\n {\n CubismTextureColor modelColorRGBA = new(ModelColor);\n modelColorRGBA.A *= opacity;\n if ( IsPremultipliedAlpha )\n {\n modelColorRGBA.R *= modelColorRGBA.A;\n modelColorRGBA.G *= modelColorRGBA.A;\n modelColorRGBA.B *= modelColorRGBA.A;\n }\n\n return modelColorRGBA;\n }\n\n /// \n /// モデルの色をセットする。\n /// 各色0.0f~1.0fの間で指定する(1.0fが標準の状態)。\n /// \n /// 赤チャンネルの値\n /// 緑チャンネルの値\n /// 青チャンネルの値\n /// αチャンネルの値\n public void SetModelColor(float red, float green, float blue, float alpha)\n {\n if ( red < 0.0f )\n {\n red = 0.0f;\n }\n else if ( red > 1.0f )\n {\n red = 1.0f;\n }\n\n if ( green < 0.0f )\n {\n green = 0.0f;\n }\n else if ( green > 1.0f )\n {\n green = 1.0f;\n }\n\n if ( blue < 0.0f )\n {\n blue = 0.0f;\n }\n else if ( blue > 1.0f )\n {\n blue = 1.0f;\n }\n\n if ( alpha < 0.0f )\n {\n alpha = 0.0f;\n }\n else if ( alpha > 1.0f )\n {\n alpha = 1.0f;\n }\n\n ModelColor.R = red;\n ModelColor.G = green;\n ModelColor.B = blue;\n ModelColor.A = alpha;\n }\n\n /// \n /// モデル描画の実装\n /// \n protected abstract void DoDrawModel();\n\n /// \n /// 描画オブジェクト(アートメッシュ)を描画する。\n /// ポリゴンメッシュとテクスチャ番号をセットで渡す。\n /// \n /// 描画するテクスチャ番号\n /// 描画オブジェクトのインデックス値\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュ頂点のインデックス配列\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 不透明度\n /// カラーブレンディングのタイプ\n /// マスク使用時のマスクの反転使用\n internal abstract unsafe void DrawMesh(int textureNo, int indexCount, int vertexCount\n , ushort* indexArray, float* vertexArray, float* uvArray\n , float opacity, CubismBlendMode colorBlendMode, bool invertedMask);\n\n /// \n /// モデル描画直前のレンダラのステートを保持する\n /// \n protected abstract void SaveProfile();\n\n /// \n /// モデル描画直前のレンダラのステートを復帰させる\n /// \n protected abstract void RestoreProfile();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismUserModel.cs", "using PersonaEngine.Lib.Live2D.Framework.Effect;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\nusing PersonaEngine.Lib.Live2D.Framework.Physics;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// ユーザーが実際に使用するモデルの基底クラス。これを継承してユーザーが実装する。\n/// \npublic abstract class CubismUserModel : IDisposable\n{\n /// \n /// X軸方向の加速度\n /// \n protected float _accelerationX;\n\n /// \n /// Y軸方向の加速度\n /// \n protected float _accelerationY;\n\n /// \n /// Z軸方向の加速度\n /// \n protected float _accelerationZ;\n\n /// \n /// 呼吸\n /// \n protected CubismBreath _breath;\n\n /// \n /// マウスドラッグ\n /// \n protected CubismTargetPoint _dragManager;\n\n /// \n /// マウスドラッグのX位置\n /// \n protected float _dragX;\n\n /// \n /// マウスドラッグのY位置\n /// \n protected float _dragY;\n\n /// \n /// 表情管理\n /// \n protected CubismExpressionMotionManager _expressionManager;\n\n /// \n /// 自動まばたき\n /// \n protected CubismEyeBlink? _eyeBlink;\n\n /// \n /// 最後のリップシンクの制御値\n /// \n protected float _lastLipSyncValue;\n\n /// \n /// リップシンクするかどうか\n /// \n protected bool _lipSync;\n\n /// \n /// Mocデータ\n /// \n protected CubismMoc _moc;\n\n /// \n /// MOC3整合性検証するかどうか\n /// \n protected bool _mocConsistency;\n\n /// \n /// ユーザデータ\n /// \n protected CubismModelUserData? _modelUserData;\n\n /// \n /// モーション管理\n /// \n protected CubismMotionManager _motionManager;\n\n /// \n /// 物理演算\n /// \n protected CubismPhysics? _physics;\n\n /// \n /// ポーズ管理\n /// \n protected CubismPose? _pose;\n\n /// \n /// コンストラクタ。\n /// \n public CubismUserModel()\n {\n _lipSync = true;\n\n Opacity = 1.0f;\n\n // モーションマネージャーを作成\n // MotionQueueManagerクラスからの継承なので使い方は同じ\n _motionManager = new CubismMotionManager();\n _motionManager.SetEventCallback(CubismDefaultMotionEventCallback, this);\n\n // 表情モーションマネージャを作成\n _expressionManager = new CubismExpressionMotionManager();\n\n // ドラッグによるアニメーション\n _dragManager = new CubismTargetPoint();\n }\n\n /// \n /// レンダラ\n /// \n public CubismRenderer? Renderer { get; private set; }\n\n /// \n /// モデル行列\n /// \n public CubismModelMatrix ModelMatrix { get; protected set; }\n\n /// \n /// Modelインスタンス\n /// \n public CubismModel Model => _moc.Model;\n\n /// \n /// 初期化されたかどうか\n /// \n public bool Initialized { get; set; }\n\n /// \n /// 更新されたかどうか\n /// \n public bool Updating { get; set; }\n\n /// \n /// 不透明度\n /// \n public float Opacity { get; set; }\n\n public void Dispose()\n {\n _moc.Dispose();\n\n DeleteRenderer();\n }\n\n /// \n /// CubismMotionQueueManagerにイベント用に登録するためのCallback。\n /// CubismUserModelの継承先のEventFiredを呼ぶ。\n /// \n /// 発火したイベントの文字列データ\n /// CubismUserModelを継承したインスタンスを想定\n public static void CubismDefaultMotionEventCallback(CubismUserModel? customData, string eventValue) { customData?.MotionEventFired(eventValue); }\n\n /// \n /// マウスドラッグの情報を設定する。\n /// \n /// ドラッグしているカーソルのX位置\n /// ドラッグしているカーソルのY位置\n public void SetDragging(float x, float y) { _dragManager.Set(x, y); }\n\n /// \n /// 加速度の情報を設定する。\n /// \n /// X軸方向の加速度\n /// Y軸方向の加速度\n /// Z軸方向の加速度\n protected void SetAcceleration(float x, float y, float z)\n {\n _accelerationX = x;\n _accelerationY = y;\n _accelerationZ = z;\n }\n\n /// \n /// モデルデータを読み込む。\n /// \n /// moc3ファイルが読み込まれているバッファ\n /// MOCの整合性チェックフラグ(初期値 : false)\n protected void LoadModel(byte[] buffer, bool shouldCheckMocConsistency = false)\n {\n _moc = new CubismMoc(buffer, shouldCheckMocConsistency);\n Model.SaveParameters();\n ModelMatrix = new CubismModelMatrix(Model.GetCanvasWidth(), Model.GetCanvasHeight());\n }\n\n /// \n /// ポーズデータを読み込む。\n /// \n /// pose3.jsonが読み込まれているバッファ\n protected void LoadPose(string buffer) { _pose = new CubismPose(buffer); }\n\n /// \n /// 物理演算データを読み込む。\n /// \n /// physics3.jsonが読み込まれているバッファ\n protected void LoadPhysics(string buffer) { _physics = new CubismPhysics(buffer); }\n\n /// \n /// ユーザーデータを読み込む。\n /// \n /// userdata3.jsonが読み込まれているバッファ\n protected void LoadUserData(string buffer) { _modelUserData = new CubismModelUserData(buffer); }\n\n /// \n /// 指定した位置にDrawableがヒットしているかどうかを取得する。\n /// \n /// 検証したいDrawableのID\n /// X位置\n /// Y位置\n /// \n /// true ヒットしている\n /// false ヒットしていない\n /// \n public unsafe bool IsHit(string drawableId, float pointX, float pointY)\n {\n var drawIndex = Model.GetDrawableIndex(drawableId);\n\n if ( drawIndex < 0 )\n {\n return false; // 存在しない場合はfalse\n }\n\n var count = Model.GetDrawableVertexCount(drawIndex);\n var vertices = Model.GetDrawableVertices(drawIndex);\n\n var left = vertices[0];\n var right = vertices[0];\n var top = vertices[1];\n var bottom = vertices[1];\n\n for ( var j = 1; j < count; ++j )\n {\n var x = vertices[CubismFramework.VertexOffset + j * CubismFramework.VertexStep];\n var y = vertices[CubismFramework.VertexOffset + j * CubismFramework.VertexStep + 1];\n\n if ( x < left )\n {\n left = x; // Min x\n }\n\n if ( x > right )\n {\n right = x; // Max x\n }\n\n if ( y < top )\n {\n top = y; // Min y\n }\n\n if ( y > bottom )\n {\n bottom = y; // Max y\n }\n }\n\n var tx = ModelMatrix.InvertTransformX(pointX);\n var ty = ModelMatrix.InvertTransformY(pointY);\n\n return left <= tx && tx <= right && top <= ty && ty <= bottom;\n }\n\n /// \n /// レンダラを生成して初期化を実行する。\n /// \n protected void CreateRenderer(CubismRenderer renderer)\n {\n if ( Renderer != null )\n {\n DeleteRenderer();\n }\n\n Renderer = renderer;\n }\n\n /// \n /// レンダラを解放する。\n /// \n protected void DeleteRenderer()\n {\n if ( Renderer != null )\n {\n Renderer.Dispose();\n Renderer = null;\n }\n }\n\n /// \n /// Eventが再生処理時にあった場合の処理をする。\n /// 継承で上書きすることを想定している。\n /// 上書きしない場合はログ出力をする。\n /// \n /// 発火したイベントの文字列データ\n protected abstract void MotionEventFired(string eventValue);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismTargetPoint.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 顔の向きの制御機能を提供するクラス。\n/// \npublic class CubismTargetPoint\n{\n public const int FrameRate = 30;\n\n public const float Epsilon = 0.01f;\n\n /// \n /// 顔の向きのX目標値(この値に近づいていく)\n /// \n private float _faceTargetX;\n\n /// \n /// 顔の向きのY目標値(この値に近づいていく)\n /// \n private float _faceTargetY;\n\n /// \n /// 顔の向きの変化速度X\n /// \n private float _faceVX;\n\n /// \n /// 顔の向きの変化速度Y\n /// \n private float _faceVY;\n\n /// \n /// 最後の実行時間[秒]\n /// \n private float _lastTimeSeconds;\n\n /// \n /// デルタ時間の積算値[秒]\n /// \n private float _userTimeSeconds;\n\n /// \n /// 顔の向きX(-1.0 - 1.0)\n /// \n public float FaceX { get; private set; }\n\n /// \n /// 顔の向きY(-1.0 - 1.0)\n /// \n public float FaceY { get; private set; }\n\n /// \n /// 更新処理を行う。\n /// \n /// デルタ時間[秒]\n public void Update(float deltaTimeSeconds)\n {\n // デルタ時間を加算する\n _userTimeSeconds += deltaTimeSeconds;\n\n // 首を中央から左右に振るときの平均的な早さは 秒程度。加速・減速を考慮して、その2倍を最高速度とする\n // 顔のふり具合を、中央(0.0)から、左右は(+-1.0)とする\n var FaceParamMaxV = 40.0f / 10.0f; // 7.5秒間に40分移動(5.3/sc)\n var MaxV = FaceParamMaxV * 1.0f / FrameRate; // 1frameあたりに変化できる速度の上限\n\n if ( _lastTimeSeconds == 0.0f )\n {\n _lastTimeSeconds = _userTimeSeconds;\n\n return;\n }\n\n var deltaTimeWeight = (_userTimeSeconds - _lastTimeSeconds) * FrameRate;\n _lastTimeSeconds = _userTimeSeconds;\n\n // 最高速度になるまでの時間を\n var TimeToMaxSpeed = 0.15f;\n var FrameToMaxSpeed = TimeToMaxSpeed * FrameRate; // sec * frame/sec\n var MaxA = deltaTimeWeight * MaxV / FrameToMaxSpeed; // 1frameあたりの加速度\n\n // 目指す向きは、(dx, dy)方向のベクトルとなる\n var dx = _faceTargetX - FaceX;\n var dy = _faceTargetY - FaceY;\n\n if ( MathF.Abs(dx) <= Epsilon && MathF.Abs(dy) <= Epsilon )\n {\n return; // 変化なし\n }\n\n // 速度の最大よりも大きい場合は、速度を落とす\n var d = MathF.Sqrt(dx * dx + dy * dy);\n\n // 進行方向の最大速度ベクトル\n var vx = MaxV * dx / d;\n var vy = MaxV * dy / d;\n\n // 現在の速度から、新規速度への変化(加速度)を求める\n var ax = vx - _faceVX;\n var ay = vy - _faceVY;\n\n var a = MathF.Sqrt(ax * ax + ay * ay);\n\n // 加速のとき\n if ( a < -MaxA || a > MaxA )\n {\n ax *= MaxA / a;\n ay *= MaxA / a;\n }\n\n // 加速度を元の速度に足して、新速度とする\n _faceVX += ax;\n _faceVY += ay;\n\n // 目的の方向に近づいたとき、滑らかに減速するための処理\n // 設定された加速度で止まることのできる距離と速度の関係から\n // 現在とりうる最高速度を計算し、それ以上のときは速度を落とす\n // ※本来、人間は筋力で力(加速度)を調整できるため、より自由度が高いが、簡単な処理ですませている\n {\n // 加速度、速度、距離の関係式。\n // 2 6 2 3\n // sqrt(a t + 16 a h t - 8 a h) - a t\n // v = --------------------------------------\n // 2\n // 4 t - 2\n // (t=1)\n // 時刻tは、あらかじめ加速度、速度を1/60(フレームレート、単位なし)で\n // 考えているので、t=1として消してよい(※未検証)\n\n var maxV = 0.5f * (MathF.Sqrt(MaxA * MaxA + 16.0f * MaxA * d - 8.0f * MaxA * d) - MaxA);\n var curV = MathF.Sqrt(_faceVX * _faceVX + _faceVY * _faceVY);\n\n if ( curV > maxV )\n {\n // 現在の速度 > 最高速度のとき、最高速度まで減速\n _faceVX *= maxV / curV;\n _faceVY *= maxV / curV;\n }\n }\n\n FaceX += _faceVX;\n FaceY += _faceVY;\n }\n\n /// \n /// 顔の向きの目標値を設定する。\n /// \n /// X軸の顔の向きの値(-1.0 - 1.0)\n /// Y軸の顔の向きの値(-1.0 - 1.0)\n public void Set(float x, float y)\n {\n _faceTargetX = x;\n _faceTargetY = y;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/CubismBreath.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// 呼吸機能を提供する。\n/// \npublic class CubismBreath\n{\n /// \n /// 積算時間[秒]\n /// \n private float _currentTime;\n\n /// \n /// 呼吸にひもづいているパラメータのリスト\n /// \n public required List Parameters { get; init; }\n\n /// \n /// モデルのパラメータを更新する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n public void UpdateParameters(CubismModel model, float deltaTimeSeconds)\n {\n _currentTime += deltaTimeSeconds;\n\n var t = _currentTime * 2.0f * 3.14159f;\n\n foreach ( var item in Parameters )\n {\n model.AddParameterValue(item.ParameterId, item.Offset +\n item.Peak * MathF.Sin(t / item.Cycle), item.Weight);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismShader_OpenGLES2.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal class CubismShader_OpenGLES2(OpenGLApi gl)\n{\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_HIGH = \"highp\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_MID = \"mediump\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION_LOW = \"lowp\";\n\n public const string CSM_FRAGMENT_SHADER_FP_PRECISION = CSM_FRAGMENT_SHADER_FP_PRECISION_HIGH;\n\n private const string GLES2 = \"#version 100\\n\";\n\n private const string GLES2C = GLES2 + \"precision \" + CSM_FRAGMENT_SHADER_FP_PRECISION + \" float;\";\n\n private const string Normal = \"#version 120\\n\";\n\n private const string Tegra = \"#version 100\\n\" +\n \"#extension GL_NV_shader_framebuffer_fetch : enable\\n\" +\n \"precision \" + CSM_FRAGMENT_SHADER_FP_PRECISION + \" float;\";\n\n // SetupMask\n public const string VertShaderSrcSetupMask_ES2 =\n GLES2 + VertShaderSrcSetupMask_Base;\n\n public const string VertShaderSrcSetupMask_Normal =\n Normal + VertShaderSrcSetupMask_Base;\n\n private const string VertShaderSrcSetupMask_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nvarying vec4 v_myPos;\nuniform mat4 u_clipMatrix;\nvoid main()\n{\ngl_Position = u_clipMatrix * a_position;\nv_myPos = u_clipMatrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n public const string FragShaderSrcSetupMask_ES2 = GLES2C + FragShaderSrcSetupMask_Base;\n\n public const string FragShaderSrcSetupMask_Normal = Normal + FragShaderSrcSetupMask_Base;\n\n private const string FragShaderSrcSetupMask_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_myPos;\nuniform sampler2D s_texture0;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nvoid main()\n{\nfloat isInside = \n step(u_baseColor.x, v_myPos.x/v_myPos.w)\n* step(u_baseColor.y, v_myPos.y/v_myPos.w)\n* step(v_myPos.x/v_myPos.w, u_baseColor.z)\n* step(v_myPos.y/v_myPos.w, u_baseColor.w);\ngl_FragColor = u_channelFlag * texture2D(s_texture0 , v_texCoord).a * isInside;\n}\";\n\n public const string FragShaderSrcSetupMaskTegra =\n Tegra + FragShaderSrcSetupMask_Base;\n\n //----- バーテックスシェーダプログラム -----\n // Normal & Add & Mult 共通\n public const string VertShaderSrc_ES2 = GLES2 + VertShaderSrc_Base;\n\n public const string VertShaderSrc_Normal = Normal + VertShaderSrc_Base;\n\n private const string VertShaderSrc_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nuniform mat4 u_matrix;\nvoid main()\n{\ngl_Position = u_matrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用)\n public const string VertShaderSrcMasked_ES2 = GLES2 + VertShaderSrcMasked_Base;\n\n public const string VertShaderSrcMasked_Normal = Normal + VertShaderSrcMasked_Base;\n\n private const string VertShaderSrcMasked_Base =\n @\"attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform mat4 u_matrix;\nuniform mat4 u_clipMatrix;\nvoid main()\n{\ngl_Position = u_matrix * a_position;\nv_clipPos = u_clipMatrix * a_position;\nv_texCoord = a_texCoord;\nv_texCoord.y = 1.0 - v_texCoord.y;\n}\";\n\n //----- フラグメントシェーダプログラム -----\n // Normal & Add & Mult 共通\n public const string FragShaderSrc_ES2 = GLES2C + FragShaderSrc_Base;\n\n public const string FragShaderSrc_Normal = Normal + FragShaderSrc_Base;\n\n public const string FragShaderSrc_Base =\n @\"varying vec2 v_texCoord;\nuniform sampler2D s_texture0;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 color = texColor * u_baseColor;\ngl_FragColor = vec4(color.rgb * color.a, color.a);\n}\";\n\n public const string FragShaderSrcTegra = Tegra + FragShaderSrc_Base;\n\n // Normal & Add & Mult 共通 (PremultipliedAlpha)\n public const string FragShaderSrcPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcPremultipliedAlpha_Base;\n\n public const string FragShaderSrcPremultipliedAlpha_Normal = Normal + FragShaderSrcPremultipliedAlpha_Base;\n\n public const string FragShaderSrcPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\nuniform sampler2D s_texture0;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\ngl_FragColor = texColor * u_baseColor;\n}\";\n\n public const string FragShaderSrcPremultipliedAlphaTegra = Tegra + FragShaderSrcPremultipliedAlpha_Base;\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用)\n public const string FragShaderSrcMask_ES2 = GLES2C + FragShaderSrcMask_Base;\n\n public const string FragShaderSrcMask_Normal = Normal + FragShaderSrcMask_Base;\n\n public const string FragShaderSrcMask_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\ncol_formask.rgb = col_formask.rgb * col_formask.a ;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * maskVal;\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskTegra = Tegra + FragShaderSrcMask_Base;\n\n // Normal & Add & Mult 共通(クリッピングされて反転使用の描画用)\n public const string FragShaderSrcMaskInverted_ES2 = GLES2C + FragShaderSrcMaskInverted_Base;\n\n public const string FragShaderSrcMaskInverted_Normal = Normal + FragShaderSrcMaskInverted_Base;\n\n public const string FragShaderSrcMaskInverted_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = texColor.rgb + u_screenColor.rgb - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\ncol_formask.rgb = col_formask.rgb * col_formask.a ;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * (1.0 - maskVal);\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskInvertedTegra = Tegra + FragShaderSrcMaskInverted_Base;\n\n // Normal & Add & Mult 共通(クリッピングされたものの描画用、PremultipliedAlphaの場合)\n public const string FragShaderSrcMaskPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskPremultipliedAlpha_Normal = Normal + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\n varying vec4 v_clipPos;\n uniform sampler2D s_texture0;\n uniform sampler2D s_texture1;\n uniform vec4 u_channelFlag;\n uniform vec4 u_baseColor;\n uniform vec4 u_multiplyColor;\n uniform vec4 u_screenColor;\n void main()\n {\n vec4 texColor = texture2D(s_texture0 , v_texCoord);\n texColor.rgb = texColor.rgb * u_multiplyColor.rgb;\n texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\n vec4 col_formask = texColor * u_baseColor;\n vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\n float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\n col_formask = col_formask * maskVal;\n gl_FragColor = col_formask;\n }\";\n\n public const string FragShaderSrcMaskPremultipliedAlphaTegra = Tegra + FragShaderSrcMaskPremultipliedAlpha_Base;\n\n // Normal & Add & Mult 共通(クリッピングされて反転使用の描画用、PremultipliedAlphaの場合)\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_ES2 = GLES2C + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_Normal = Normal + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlpha_Base =\n @\"varying vec2 v_texCoord;\nvarying vec4 v_clipPos;\nuniform sampler2D s_texture0;\nuniform sampler2D s_texture1;\nuniform vec4 u_channelFlag;\nuniform vec4 u_baseColor;\nuniform vec4 u_multiplyColor;\nuniform vec4 u_screenColor;\nvoid main()\n{\nvec4 texColor = texture2D(s_texture0 , v_texCoord);\ntexColor.rgb = texColor.rgb * u_multiplyColor.rgb;\ntexColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb);\nvec4 col_formask = texColor * u_baseColor;\nvec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;\nfloat maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;\ncol_formask = col_formask * (1.0 - maskVal);\ngl_FragColor = col_formask;\n}\";\n\n public const string FragShaderSrcMaskInvertedPremultipliedAlphaTegra = Tegra + FragShaderSrcMaskInvertedPremultipliedAlpha_Base;\n\n public const int ShaderCount = 19; // シェーダの数 = マスク生成用 + (通常 + 加算 + 乗算) * (マスク無 + マスク有 + マスク有反転 + マスク無の乗算済アルファ対応版 + マスク有の乗算済アルファ対応版 + マスク有反転の乗算済アルファ対応版)\n\n /// \n /// ロードしたシェーダプログラムを保持する変数\n /// \n private readonly List _shaderSets = [];\n\n /// \n /// Tegra対応.拡張方式で描画\n /// \n internal bool s_extMode;\n\n /// \n /// 拡張方式のPA設定用の変数\n /// \n internal bool s_extPAMode;\n\n /// \n /// シェーダプログラムの一連のセットアップを実行する\n /// \n /// レンダラのインスタンス\n /// GPUのテクスチャID\n /// ポリゴンメッシュの頂点数\n /// ポリゴンメッシュの頂点配列\n /// uv配列\n /// 不透明度\n /// カラーブレンディングのタイプ\n /// ベースカラー\n /// \n /// \n /// 乗算済みアルファかどうか\n /// Model-View-Projection行列\n /// マスクを反転して使用するフラグ\n internal void SetupShaderProgramForDraw(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index)\n {\n if ( _shaderSets.Count == 0 )\n {\n GenerateShaders();\n }\n\n // Blending\n int SRC_COLOR;\n int DST_COLOR;\n int SRC_ALPHA;\n int DST_ALPHA;\n\n // _shaderSets用のオフセット計算\n var masked = renderer.ClippingContextBufferForDraw != null; // この描画オブジェクトはマスク対象か\n var invertedMask = model.GetDrawableInvertedMask(index);\n var isPremultipliedAlpha = renderer.IsPremultipliedAlpha;\n var offset = (masked ? invertedMask ? 2 : 1 : 0) + (isPremultipliedAlpha ? 3 : 0);\n\n CubismShaderSet shaderSet;\n switch ( model.GetDrawableBlendMode(index) )\n {\n case CubismBlendMode.Normal:\n default:\n shaderSet = _shaderSets[(int)ShaderNames.Normal + offset];\n SRC_COLOR = gl.GL_ONE;\n DST_COLOR = gl.GL_ONE_MINUS_SRC_ALPHA;\n SRC_ALPHA = gl.GL_ONE;\n DST_ALPHA = gl.GL_ONE_MINUS_SRC_ALPHA;\n\n break;\n\n case CubismBlendMode.Additive:\n shaderSet = _shaderSets[(int)ShaderNames.Add + offset];\n SRC_COLOR = gl.GL_ONE;\n DST_COLOR = gl.GL_ONE;\n SRC_ALPHA = gl.GL_ZERO;\n DST_ALPHA = gl.GL_ONE;\n\n break;\n\n case CubismBlendMode.Multiplicative:\n shaderSet = _shaderSets[(int)ShaderNames.Mult + offset];\n SRC_COLOR = gl.GL_DST_COLOR;\n DST_COLOR = gl.GL_ONE_MINUS_SRC_ALPHA;\n SRC_ALPHA = gl.GL_ZERO;\n DST_ALPHA = gl.GL_ONE;\n\n break;\n }\n\n gl.UseProgram(shaderSet.ShaderProgram);\n\n // 頂点配列の設定\n SetupTexture(renderer, model, index, shaderSet);\n\n // テクスチャ頂点の設定\n SetVertexAttributes(shaderSet);\n\n if ( masked )\n {\n gl.ActiveTexture(gl.GL_TEXTURE1);\n\n var draw = renderer.ClippingContextBufferForDraw!;\n\n // frameBufferに書かれたテクスチャ\n var tex = renderer.GetMaskBuffer(draw.BufferIndex).ColorBuffer;\n\n gl.BindTexture(gl.GL_TEXTURE_2D, tex);\n gl.Uniform1i(shaderSet.SamplerTexture1Location, 1);\n\n // View座標をClippingContextの座標に変換するための行列を設定\n gl.UniformMatrix4fv(shaderSet.UniformClipMatrixLocation, 1, false, draw.MatrixForDraw.Tr);\n\n // 使用するカラーチャンネルを設定\n SetColorChannelUniformVariables(shaderSet, renderer.ClippingContextBufferForDraw!);\n }\n\n //座標変換\n gl.UniformMatrix4fv(shaderSet.UniformMatrixLocation, 1, false, renderer.GetMvpMatrix().Tr);\n\n // ユニフォーム変数設定\n var baseColor = renderer.GetModelColorWithOpacity(model.GetDrawableOpacity(index));\n var multiplyColor = model.GetMultiplyColor(index);\n var screenColor = model.GetScreenColor(index);\n SetColorUniformVariables(shaderSet, baseColor, multiplyColor, screenColor);\n\n gl.BlendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);\n }\n\n internal void SetupShaderProgramForMask(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index)\n {\n if ( _shaderSets.Count == 0 )\n {\n GenerateShaders();\n }\n\n // Blending\n var SRC_COLOR = gl.GL_ZERO;\n var DST_COLOR = gl.GL_ONE_MINUS_SRC_COLOR;\n var SRC_ALPHA = gl.GL_ZERO;\n var DST_ALPHA = gl.GL_ONE_MINUS_SRC_ALPHA;\n\n var shaderSet = _shaderSets[(int)ShaderNames.SetupMask];\n gl.UseProgram(shaderSet.ShaderProgram);\n\n var draw = renderer.ClippingContextBufferForMask!;\n\n //テクスチャ設定\n SetupTexture(renderer, model, index, shaderSet);\n\n // 頂点配列の設定\n SetVertexAttributes(shaderSet);\n\n // 使用するカラーチャンネルを設定\n SetColorChannelUniformVariables(shaderSet, draw);\n\n gl.UniformMatrix4fv(shaderSet.UniformClipMatrixLocation, 1, false, draw.MatrixForMask.Tr);\n\n var rect = draw.LayoutBounds;\n CubismTextureColor baseColor = new(rect.X * 2.0f - 1.0f, rect.Y * 2.0f - 1.0f, rect.GetRight() * 2.0f - 1.0f, rect.GetBottom() * 2.0f - 1.0f);\n var multiplyColor = model.GetMultiplyColor(index);\n var screenColor = model.GetScreenColor(index);\n SetColorUniformVariables(shaderSet, baseColor, multiplyColor, screenColor);\n\n gl.BlendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);\n }\n\n /// \n /// シェーダプログラムを解放する\n /// \n internal void ReleaseShaderProgram()\n {\n for ( var i = 0; i < _shaderSets.Count; i++ )\n {\n if ( _shaderSets[i].ShaderProgram != 0 )\n {\n gl.DeleteProgram(_shaderSets[i].ShaderProgram);\n _shaderSets[i].ShaderProgram = 0;\n }\n }\n }\n\n /// \n /// シェーダプログラムを初期化する\n /// \n internal void GenerateShaders()\n {\n for ( var i = 0; i < ShaderCount; i++ )\n {\n _shaderSets.Add(new CubismShaderSet());\n }\n\n if ( gl.IsES2 )\n {\n if ( s_extMode )\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_ES2, FragShaderSrcSetupMaskTegra);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcTegra);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskTegra);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedTegra);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcPremultipliedAlphaTegra);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskPremultipliedAlphaTegra);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedPremultipliedAlphaTegra);\n }\n else\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_ES2, FragShaderSrcSetupMask_ES2);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrc_ES2);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMask_ES2);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInverted_ES2);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_ES2, FragShaderSrcPremultipliedAlpha_ES2);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskPremultipliedAlpha_ES2);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_ES2, FragShaderSrcMaskInvertedPremultipliedAlpha_ES2);\n }\n\n // 加算も通常と同じシェーダーを利用する\n _shaderSets[7].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[8].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[9].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[10].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[11].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[12].ShaderProgram = _shaderSets[6].ShaderProgram;\n\n // 乗算も通常と同じシェーダーを利用する\n _shaderSets[13].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[14].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[15].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[16].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[17].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[18].ShaderProgram = _shaderSets[6].ShaderProgram;\n }\n else\n {\n _shaderSets[0].ShaderProgram = LoadShaderProgram(VertShaderSrcSetupMask_Normal, FragShaderSrcSetupMask_Normal);\n\n _shaderSets[1].ShaderProgram = LoadShaderProgram(VertShaderSrc_Normal, FragShaderSrc_Normal);\n _shaderSets[2].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMask_Normal);\n _shaderSets[3].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskInverted_Normal);\n _shaderSets[4].ShaderProgram = LoadShaderProgram(VertShaderSrc_Normal, FragShaderSrcPremultipliedAlpha_Normal);\n _shaderSets[5].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskPremultipliedAlpha_Normal);\n _shaderSets[6].ShaderProgram = LoadShaderProgram(VertShaderSrcMasked_Normal, FragShaderSrcMaskInvertedPremultipliedAlpha_Normal);\n\n // 加算も通常と同じシェーダーを利用する\n _shaderSets[7].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[8].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[9].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[10].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[11].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[12].ShaderProgram = _shaderSets[6].ShaderProgram;\n\n // 乗算も通常と同じシェーダーを利用する\n _shaderSets[13].ShaderProgram = _shaderSets[1].ShaderProgram;\n _shaderSets[14].ShaderProgram = _shaderSets[2].ShaderProgram;\n _shaderSets[15].ShaderProgram = _shaderSets[3].ShaderProgram;\n _shaderSets[16].ShaderProgram = _shaderSets[4].ShaderProgram;\n _shaderSets[17].ShaderProgram = _shaderSets[5].ShaderProgram;\n _shaderSets[18].ShaderProgram = _shaderSets[6].ShaderProgram;\n }\n\n // SetupMask\n _shaderSets[0].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[0].ShaderProgram, \"a_position\");\n _shaderSets[0].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[0].ShaderProgram, \"a_texCoord\");\n _shaderSets[0].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"s_texture0\");\n _shaderSets[0].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[0].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_channelFlag\");\n _shaderSets[0].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_baseColor\");\n _shaderSets[0].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[0].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[0].ShaderProgram, \"u_screenColor\");\n\n // 通常\n _shaderSets[1].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[1].ShaderProgram, \"a_position\");\n _shaderSets[1].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[1].ShaderProgram, \"a_texCoord\");\n _shaderSets[1].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"s_texture0\");\n _shaderSets[1].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_matrix\");\n _shaderSets[1].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_baseColor\");\n _shaderSets[1].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[1].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[1].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング)\n _shaderSets[2].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[2].ShaderProgram, \"a_position\");\n _shaderSets[2].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[2].ShaderProgram, \"a_texCoord\");\n _shaderSets[2].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"s_texture0\");\n _shaderSets[2].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"s_texture1\");\n _shaderSets[2].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_matrix\");\n _shaderSets[2].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[2].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_channelFlag\");\n _shaderSets[2].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_baseColor\");\n _shaderSets[2].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[2].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[2].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング・反転)\n _shaderSets[3].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[3].ShaderProgram, \"a_position\");\n _shaderSets[3].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[3].ShaderProgram, \"a_texCoord\");\n _shaderSets[3].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"s_texture0\");\n _shaderSets[3].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"s_texture1\");\n _shaderSets[3].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_matrix\");\n _shaderSets[3].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[3].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_channelFlag\");\n _shaderSets[3].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_baseColor\");\n _shaderSets[3].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[3].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[3].ShaderProgram, \"u_screenColor\");\n\n // 通常(PremultipliedAlpha)\n _shaderSets[4].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[4].ShaderProgram, \"a_position\");\n _shaderSets[4].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[4].ShaderProgram, \"a_texCoord\");\n _shaderSets[4].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"s_texture0\");\n _shaderSets[4].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_matrix\");\n _shaderSets[4].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_baseColor\");\n _shaderSets[4].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[4].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[4].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング、PremultipliedAlpha)\n _shaderSets[5].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[5].ShaderProgram, \"a_position\");\n _shaderSets[5].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[5].ShaderProgram, \"a_texCoord\");\n _shaderSets[5].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"s_texture0\");\n _shaderSets[5].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"s_texture1\");\n _shaderSets[5].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_matrix\");\n _shaderSets[5].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[5].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_channelFlag\");\n _shaderSets[5].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_baseColor\");\n _shaderSets[5].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[5].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[5].ShaderProgram, \"u_screenColor\");\n\n // 通常(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[6].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[6].ShaderProgram, \"a_position\");\n _shaderSets[6].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[6].ShaderProgram, \"a_texCoord\");\n _shaderSets[6].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"s_texture0\");\n _shaderSets[6].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"s_texture1\");\n _shaderSets[6].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_matrix\");\n _shaderSets[6].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[6].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_channelFlag\");\n _shaderSets[6].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_baseColor\");\n _shaderSets[6].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[6].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[6].ShaderProgram, \"u_screenColor\");\n\n // 加算\n _shaderSets[7].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[7].ShaderProgram, \"a_position\");\n _shaderSets[7].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[7].ShaderProgram, \"a_texCoord\");\n _shaderSets[7].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"s_texture0\");\n _shaderSets[7].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_matrix\");\n _shaderSets[7].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_baseColor\");\n _shaderSets[7].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[7].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[7].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング)\n _shaderSets[8].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[8].ShaderProgram, \"a_position\");\n _shaderSets[8].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[8].ShaderProgram, \"a_texCoord\");\n _shaderSets[8].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"s_texture0\");\n _shaderSets[8].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"s_texture1\");\n _shaderSets[8].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_matrix\");\n _shaderSets[8].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[8].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_channelFlag\");\n _shaderSets[8].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_baseColor\");\n _shaderSets[8].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[8].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[8].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング・反転)\n _shaderSets[9].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[9].ShaderProgram, \"a_position\");\n _shaderSets[9].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[9].ShaderProgram, \"a_texCoord\");\n _shaderSets[9].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"s_texture0\");\n _shaderSets[9].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"s_texture1\");\n _shaderSets[9].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_matrix\");\n _shaderSets[9].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[9].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_channelFlag\");\n _shaderSets[9].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_baseColor\");\n _shaderSets[9].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[9].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[9].ShaderProgram, \"u_screenColor\");\n\n // 加算(PremultipliedAlpha)\n _shaderSets[10].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[10].ShaderProgram, \"a_position\");\n _shaderSets[10].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[10].ShaderProgram, \"a_texCoord\");\n _shaderSets[10].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"s_texture0\");\n _shaderSets[10].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_matrix\");\n _shaderSets[10].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_baseColor\");\n _shaderSets[10].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[10].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[10].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング、PremultipliedAlpha)\n _shaderSets[11].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[11].ShaderProgram, \"a_position\");\n _shaderSets[11].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[11].ShaderProgram, \"a_texCoord\");\n _shaderSets[11].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"s_texture0\");\n _shaderSets[11].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"s_texture1\");\n _shaderSets[11].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_matrix\");\n _shaderSets[11].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[11].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_channelFlag\");\n _shaderSets[11].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_baseColor\");\n _shaderSets[11].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[11].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[11].ShaderProgram, \"u_screenColor\");\n\n // 加算(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[12].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[12].ShaderProgram, \"a_position\");\n _shaderSets[12].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[12].ShaderProgram, \"a_texCoord\");\n _shaderSets[12].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"s_texture0\");\n _shaderSets[12].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"s_texture1\");\n _shaderSets[12].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_matrix\");\n _shaderSets[12].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[12].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_channelFlag\");\n _shaderSets[12].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_baseColor\");\n _shaderSets[12].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[12].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[12].ShaderProgram, \"u_screenColor\");\n\n // 乗算\n _shaderSets[13].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[13].ShaderProgram, \"a_position\");\n _shaderSets[13].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[13].ShaderProgram, \"a_texCoord\");\n _shaderSets[13].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"s_texture0\");\n _shaderSets[13].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_matrix\");\n _shaderSets[13].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_baseColor\");\n _shaderSets[13].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[13].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[13].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング)\n _shaderSets[14].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[14].ShaderProgram, \"a_position\");\n _shaderSets[14].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[14].ShaderProgram, \"a_texCoord\");\n _shaderSets[14].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"s_texture0\");\n _shaderSets[14].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"s_texture1\");\n _shaderSets[14].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_matrix\");\n _shaderSets[14].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[14].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_channelFlag\");\n _shaderSets[14].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_baseColor\");\n _shaderSets[14].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[14].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[14].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング・反転)\n _shaderSets[15].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[15].ShaderProgram, \"a_position\");\n _shaderSets[15].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[15].ShaderProgram, \"a_texCoord\");\n _shaderSets[15].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"s_texture0\");\n _shaderSets[15].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"s_texture1\");\n _shaderSets[15].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_matrix\");\n _shaderSets[15].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[15].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_channelFlag\");\n _shaderSets[15].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_baseColor\");\n _shaderSets[15].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[15].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[15].ShaderProgram, \"u_screenColor\");\n\n // 乗算(PremultipliedAlpha)\n _shaderSets[16].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[16].ShaderProgram, \"a_position\");\n _shaderSets[16].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[16].ShaderProgram, \"a_texCoord\");\n _shaderSets[16].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"s_texture0\");\n _shaderSets[16].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_matrix\");\n _shaderSets[16].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_baseColor\");\n _shaderSets[16].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[16].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[16].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング、PremultipliedAlpha)\n _shaderSets[17].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[17].ShaderProgram, \"a_position\");\n _shaderSets[17].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[17].ShaderProgram, \"a_texCoord\");\n _shaderSets[17].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"s_texture0\");\n _shaderSets[17].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"s_texture1\");\n _shaderSets[17].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_matrix\");\n _shaderSets[17].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[17].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_channelFlag\");\n _shaderSets[17].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_baseColor\");\n _shaderSets[17].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[17].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[17].ShaderProgram, \"u_screenColor\");\n\n // 乗算(クリッピング・反転、PremultipliedAlpha)\n _shaderSets[18].AttributePositionLocation = gl.GetAttribLocation(_shaderSets[18].ShaderProgram, \"a_position\");\n _shaderSets[18].AttributeTexCoordLocation = gl.GetAttribLocation(_shaderSets[18].ShaderProgram, \"a_texCoord\");\n _shaderSets[18].SamplerTexture0Location = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"s_texture0\");\n _shaderSets[18].SamplerTexture1Location = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"s_texture1\");\n _shaderSets[18].UniformMatrixLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_matrix\");\n _shaderSets[18].UniformClipMatrixLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_clipMatrix\");\n _shaderSets[18].UnifromChannelFlagLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_channelFlag\");\n _shaderSets[18].UniformBaseColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_baseColor\");\n _shaderSets[18].UniformMultiplyColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_multiplyColor\");\n _shaderSets[18].UniformScreenColorLocation = gl.GetUniformLocation(_shaderSets[18].ShaderProgram, \"u_screenColor\");\n }\n\n /// \n /// シェーダプログラムをロードしてアドレス返す。\n /// \n /// 頂点シェーダのソース\n /// フラグメントシェーダのソース\n /// シェーダプログラムのアドレス\n internal int LoadShaderProgram(string vertShaderSrc, string fragShaderSrc)\n {\n // Create shader program.\n var shaderProgram = gl.CreateProgram();\n\n if ( !CompileShaderSource(out var vertShader, gl.GL_VERTEX_SHADER, vertShaderSrc) )\n {\n CubismLog.Error(\"[Live2D SDK]Vertex shader compile error!\");\n\n return 0;\n }\n\n // Create and compile fragment shader.\n if ( !CompileShaderSource(out var fragShader, gl.GL_FRAGMENT_SHADER, fragShaderSrc) )\n {\n CubismLog.Error(\"[Live2D SDK]Fragment shader compile error!\");\n\n return 0;\n }\n\n // Attach vertex shader to program.\n gl.AttachShader(shaderProgram, vertShader);\n\n // Attach fragment shader to program.\n gl.AttachShader(shaderProgram, fragShader);\n\n // Link program.\n if ( !LinkProgram(shaderProgram) )\n {\n CubismLog.Error(\"[Live2D SDK]Failed to link program: %d\", shaderProgram);\n\n if ( vertShader != 0 )\n {\n gl.DeleteShader(vertShader);\n }\n\n if ( fragShader != 0 )\n {\n gl.DeleteShader(fragShader);\n }\n\n if ( shaderProgram != 0 )\n {\n gl.DeleteProgram(shaderProgram);\n }\n\n return 0;\n }\n\n // Release vertex and fragment shaders.\n if ( vertShader != 0 )\n {\n gl.DetachShader(shaderProgram, vertShader);\n gl.DeleteShader(vertShader);\n }\n\n if ( fragShader != 0 )\n {\n gl.DetachShader(shaderProgram, fragShader);\n gl.DeleteShader(fragShader);\n }\n\n return shaderProgram;\n }\n\n /// \n /// シェーダプログラムをコンパイルする\n /// \n /// コンパイルされたシェーダプログラムのアドレス\n /// シェーダタイプ(Vertex/Fragment)\n /// シェーダソースコード\n /// \n /// true . コンパイル成功\n /// false . コンパイル失敗\n /// \n internal unsafe bool CompileShaderSource(out int outShader, int shaderType, string shaderSource)\n {\n int status;\n\n outShader = gl.CreateShader(shaderType);\n gl.ShaderSource(outShader, shaderSource);\n gl.CompileShader(outShader);\n\n int logLength;\n gl.GetShaderiv(outShader, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetShaderInfoLog(outShader, out var log);\n CubismLog.Error($\"[Live2D SDK]Shader compile log: {log}\");\n }\n\n gl.GetShaderiv(outShader, gl.GL_COMPILE_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n gl.DeleteShader(outShader);\n\n return false;\n }\n\n return true;\n }\n\n /// \n /// シェーダプログラムをリンクする\n /// \n /// リンクするシェーダプログラムのアドレス\n /// \n /// true . リンク成功\n /// false . リンク失敗\n /// \n internal unsafe bool LinkProgram(int shaderProgram)\n {\n int status;\n gl.LinkProgram(shaderProgram);\n\n int logLength;\n gl.GetProgramiv(shaderProgram, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetProgramInfoLog(shaderProgram, out var log);\n CubismLog.Error($\"[Live2D SDK]Program link log: {log}\");\n }\n\n gl.GetProgramiv(shaderProgram, gl.GL_LINK_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n return false;\n }\n\n return true;\n }\n\n /// \n /// シェーダプログラムを検証する\n /// \n /// 検証するシェーダプログラムのアドレス\n /// \n /// true . 正常\n /// false . 異常\n /// \n internal unsafe bool ValidateProgram(int shaderProgram)\n {\n int logLength,\n status;\n\n gl.ValidateProgram(shaderProgram);\n gl.GetProgramiv(shaderProgram, gl.GL_INFO_LOG_LENGTH, &logLength);\n if ( logLength > 0 )\n {\n gl.GetProgramInfoLog(shaderProgram, out var log);\n CubismLog.Error($\"[Live2D SDK]Validate program log: {log}\");\n }\n\n gl.GetProgramiv(shaderProgram, gl.GL_VALIDATE_STATUS, &status);\n if ( status == gl.GL_FALSE )\n {\n return false;\n }\n\n return true;\n }\n\n /// \n /// Tegraプロセッサ対応。拡張方式による描画の有効・無効\n /// \n /// trueなら拡張方式で描画する\n /// trueなら拡張方式のPA設定を有効にする\n internal void SetExtShaderMode(bool extMode, bool extPAMode)\n {\n s_extMode = extMode;\n s_extPAMode = extPAMode;\n }\n\n /// \n /// 必要な頂点属性を設定する\n /// \n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n public void SetVertexAttributes(CubismShaderSet shaderSet)\n {\n // 頂点位置属性の設定\n gl.EnableVertexAttribArray(shaderSet.AttributePositionLocation);\n gl.VertexAttribPointer(shaderSet.AttributePositionLocation, 2, gl.GL_FLOAT, false, 4 * sizeof(float), 0);\n\n // テクスチャ座標属性の設定\n gl.EnableVertexAttribArray(shaderSet.AttributeTexCoordLocation);\n gl.VertexAttribPointer(shaderSet.AttributeTexCoordLocation, 2, gl.GL_FLOAT, false, 4 * sizeof(float), 2 * sizeof(float));\n }\n\n /// \n /// テクスチャの設定を行う\n /// \n /// レンダラー\n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n public void SetupTexture(CubismRenderer_OpenGLES2 renderer, CubismModel model, int index, CubismShaderSet shaderSet)\n {\n var textureIndex = model.GetDrawableTextureIndex(index);\n var textureId = renderer.GetBindedTextureId(textureIndex);\n gl.ActiveTexture(gl.GL_TEXTURE0);\n gl.BindTexture(gl.GL_TEXTURE_2D, textureId);\n gl.Uniform1i(shaderSet.SamplerTexture0Location, 0);\n }\n\n /// \n /// 色関連のユニフォーム変数の設定を行う\n /// \n /// レンダラー\n /// 描画対象のモデル\n /// 描画対象のメッシュのインデックス\n /// シェーダープログラムのセット\n /// ベースカラー\n /// 乗算カラー\n /// スクリーンカラー\n public void SetColorUniformVariables(CubismShaderSet shaderSet,\n CubismTextureColor baseColor, CubismTextureColor multiplyColor, CubismTextureColor screenColor)\n {\n gl.Uniform4f(shaderSet.UniformBaseColorLocation, baseColor.R, baseColor.G, baseColor.B, baseColor.A);\n gl.Uniform4f(shaderSet.UniformMultiplyColorLocation, multiplyColor.R, multiplyColor.G, multiplyColor.B, multiplyColor.A);\n gl.Uniform4f(shaderSet.UniformScreenColorLocation, screenColor.R, screenColor.G, screenColor.B, screenColor.A);\n }\n\n /// \n /// カラーチャンネル関連のユニフォーム変数の設定を行う\n /// \n /// シェーダープログラムのセット\n /// 描画コンテクスト\n public void SetColorChannelUniformVariables(CubismShaderSet shaderSet, CubismClippingContext contextBuffer)\n {\n var channelIndex = contextBuffer.LayoutChannelIndex;\n var colorChannel = contextBuffer.Manager.GetChannelFlagAsColor(channelIndex);\n gl.Uniform4f(shaderSet.UnifromChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionManager.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーションの管理を行うクラス。\n/// \npublic class CubismMotionManager : CubismMotionQueueManager\n{\n /// \n /// 現在再生中のモーションの優先度\n /// \n public MotionPriority CurrentPriority { get; private set; }\n\n /// \n /// 再生予定のモーションの優先度。再生中は0になる。モーションファイルを別スレッドで読み込むときの機能。\n /// \n public MotionPriority ReservePriority { get; set; }\n\n /// \n /// 優先度を設定してモーションを開始する。\n /// \n /// モーション\n /// 再生が終了したモーションのインスタンスを削除するならtrue\n /// 優先度\n /// 開始したモーションの識別番号を返す。個別のモーションが終了したか否かを判定するIsFinished()の引数で使用する。開始できない時は「-1」\n public CubismMotionQueueEntry StartMotionPriority(ACubismMotion motion, MotionPriority priority)\n {\n if ( priority == ReservePriority )\n {\n ReservePriority = 0; // 予約を解除\n }\n\n CurrentPriority = priority; // 再生中モーションの優先度を設定\n\n return StartMotion(motion);\n }\n\n /// \n /// モーションを更新して、モデルにパラメータ値を反映する。\n /// \n /// 対象のモデル\n /// デルタ時間[秒]\n /// \n /// true 更新されている\n /// false 更新されていない\n /// \n public bool UpdateMotion(CubismModel model, float deltaTimeSeconds)\n {\n UserTimeSeconds += deltaTimeSeconds;\n\n var updated = DoUpdateMotion(model, UserTimeSeconds);\n\n if ( IsFinished() )\n {\n CurrentPriority = 0; // 再生中モーションの優先度を解除\n }\n\n return updated;\n }\n\n /// \n /// モーションを予約する。\n /// \n /// 優先度\n /// \n /// true 予約できた\n /// false 予約できなかった\n /// \n public bool ReserveMotion(MotionPriority priority)\n {\n if ( priority <= ReservePriority || priority <= CurrentPriority )\n {\n return false;\n }\n\n ReservePriority = priority;\n\n return true;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/IdleBlinkingAnimationService.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour;\n\n/// \n/// Manages Live2D model idle animations and custom automatic blinking.\n/// Ensures a random idle animation from the 'Idle' group is playing if available\n/// and handles periodic blinking by directly manipulating eye parameters.\n/// Blinking operates independently of the main animation system.\n/// \npublic sealed class IdleBlinkingAnimationService : ILive2DAnimationService\n{\n private const string IDLE_MOTION_GROUP = \"Idle\";\n\n private const MotionPriority IDLE_MOTION_PRIORITY = MotionPriority.PriorityIdle;\n\n private const string PARAM_EYE_L_OPEN = \"ParamEyeLOpen\";\n\n private const string PARAM_EYE_R_OPEN = \"ParamEyeROpen\";\n\n private const float BLINK_INTERVAL_MIN_SECONDS = 1.5f;\n\n private const float BLINK_INTERVAL_MAX_SECONDS = 6.0f;\n\n private const float BLINK_CLOSING_DURATION = 0.06f;\n\n private const float BLINK_CLOSED_DURATION = 0.05f;\n\n private const float BLINK_OPENING_DURATION = 0.10f;\n\n private const float EYE_OPEN_VALUE = 1.0f;\n\n private const float EYE_CLOSED_VALUE = 0.0f;\n\n private readonly ILogger _logger;\n\n private readonly Random _random = new();\n\n private float _blinkPhaseTimer = 0.0f;\n\n private BlinkState _currentBlinkState = BlinkState.Idle;\n\n private CubismMotionQueueEntry? _currentIdleMotionEntry;\n\n private bool _disposed = false;\n\n private bool _eyeParamsValid = false;\n\n private bool _isBlinking = false;\n\n private bool _isIdleAnimationAvailable = false;\n\n private bool _isStarted = false;\n\n private LAppModel? _model;\n\n private float _timeUntilNextBlink = 0.0f;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logger instance for logging messages.\n public IdleBlinkingAnimationService(ILogger logger)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n SetNextBlinkInterval();\n }\n\n #region Asset Validation\n\n /// \n /// Checks if the required assets (idle motion group, eye parameters) are available in the model.\n /// Sets the internal flags `_isIdleAnimationAvailable` and `_eyeParamsValid`.\n /// \n private void ValidateModelAssets()\n {\n if ( _model == null )\n {\n return;\n }\n\n _logger.LogDebug(\"Validating configured idle/blinking mappings against model assets...\");\n\n _isIdleAnimationAvailable = false;\n foreach ( var motionKey in _model.Motions )\n {\n var groupName = LAppModel.GetMotionGroupName(motionKey);\n if ( groupName == IDLE_MOTION_GROUP )\n {\n _isIdleAnimationAvailable = true;\n }\n }\n\n if ( _isIdleAnimationAvailable )\n {\n _logger.LogDebug(\"Idle motion group '{IdleGroup}' is configured and available in the model.\", IDLE_MOTION_GROUP);\n }\n else\n {\n _logger.LogWarning(\"Configured IDLE_MOTION_GROUP ('{IdleGroup}') not found in model! Idle animations disabled.\", IDLE_MOTION_GROUP);\n }\n\n _eyeParamsValid = false;\n\n try\n {\n // An invalid index (usually -1) means the parameter doesn't exist.\n var leftEyeIndex = _model.Model.GetParameterIndex(PARAM_EYE_L_OPEN);\n var rightEyeIndex = _model.Model.GetParameterIndex(PARAM_EYE_R_OPEN);\n\n if ( leftEyeIndex >= 0 && rightEyeIndex >= 0 )\n {\n _eyeParamsValid = true;\n _logger.LogDebug(\"Required eye parameters found: '{ParamL}' (Index: {IndexL}), '{ParamR}' (Index: {IndexR}).\",\n PARAM_EYE_L_OPEN, leftEyeIndex, PARAM_EYE_R_OPEN, rightEyeIndex);\n }\n else\n {\n if ( leftEyeIndex < 0 )\n {\n _logger.LogWarning(\"Eye parameter '{ParamL}' not found in the model.\", PARAM_EYE_L_OPEN);\n }\n\n if ( rightEyeIndex < 0 )\n {\n _logger.LogWarning(\"Eye parameter '{ParamR}' not found in the model.\", PARAM_EYE_R_OPEN);\n }\n\n _logger.LogWarning(\"Automatic blinking disabled because one or both eye parameters are missing.\");\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error occurred while validating eye parameters. Blinking disabled.\");\n _eyeParamsValid = false;\n }\n }\n\n #endregion\n\n private enum BlinkState\n {\n Idle,\n\n Closing,\n\n Closed,\n\n Opening\n }\n\n #region ILive2DAnimationService Implementation\n\n /// \n /// Starts the service with the specified Live2D model.\n /// Validates required assets (idle motion group, eye parameters) and initializes state.\n /// \n /// The Live2D model instance to animate.\n /// Thrown if model is null.\n /// Thrown if the service has been disposed.\n public void Start(LAppModel model)\n {\n ObjectDisposedException.ThrowIf(_disposed, typeof(IdleBlinkingAnimationService));\n\n if ( _isStarted )\n {\n _logger.LogWarning(\"Service already started. Call Stop() first if reconfiguration is needed.\");\n\n return;\n }\n\n _model = model ?? throw new ArgumentNullException(nameof(model));\n\n ValidateModelAssets();\n\n SetNextBlinkInterval();\n _currentBlinkState = BlinkState.Idle;\n _isBlinking = false;\n _blinkPhaseTimer = 0f;\n ResetEyesToOpenState();\n\n _currentIdleMotionEntry = null;\n\n _isStarted = true;\n _logger.LogInformation(\"IdleBlinkingAnimationService started. Idle animations: {IdleStatus}, Blinking: {BlinkStatus}.\",\n _isIdleAnimationAvailable ? \"Enabled\" : \"Disabled\",\n _eyeParamsValid ? \"Enabled\" : \"Disabled\");\n\n if ( _isIdleAnimationAvailable && _currentIdleMotionEntry == null )\n {\n TryStartIdleMotion();\n }\n }\n\n /// \n /// Stops the service, resetting blinking and clearing the tracked idle motion.\n /// Attempts to leave the eyes in an open state.\n /// \n public void Stop()\n {\n if ( !_isStarted || _disposed )\n {\n return;\n }\n\n _isStarted = false;\n\n ResetEyesToOpenState();\n\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n _blinkPhaseTimer = 0f;\n\n _currentIdleMotionEntry = null;\n // Note: The motion itself isn't forcibly stopped here; Instead we\n // rely on the model's lifecycle management to handle it.\n\n _logger.LogInformation(\"IdleBlinkingAnimationService stopped.\");\n }\n\n /// \n /// Updates the idle animation and blinking state based on elapsed time.\n /// Should be called once per frame.\n /// \n /// The time elapsed since the last update call, in seconds.\n public void Update(float deltaTime)\n {\n if ( !_isStarted || _model?.Model == null || _disposed || deltaTime <= 0.0f )\n {\n return;\n }\n\n UpdateIdleMotion();\n\n if ( _eyeParamsValid )\n {\n UpdateBlinking(deltaTime);\n }\n }\n\n #endregion\n\n #region Core Logic: Idle\n\n private void UpdateIdleMotion()\n {\n if ( _currentIdleMotionEntry is { Finished: true } )\n {\n _logger.LogTrace(\"Tracked idle motion finished.\");\n _currentIdleMotionEntry = null;\n }\n\n if ( _isIdleAnimationAvailable && _currentIdleMotionEntry == null )\n {\n TryStartIdleMotion();\n }\n }\n\n private void TryStartIdleMotion()\n {\n if ( _model == null )\n {\n return;\n }\n\n _logger.LogTrace(\"Attempting to start a new idle motion for group '{IdleGroup}'.\", IDLE_MOTION_GROUP);\n\n try\n {\n var newEntry = _model.StartRandomMotion(IDLE_MOTION_GROUP, IDLE_MOTION_PRIORITY);\n\n _currentIdleMotionEntry = newEntry;\n\n if ( _currentIdleMotionEntry != null )\n {\n _logger.LogDebug(\"Successfully started idle motion.\");\n }\n // _logger.LogWarning(\"Failed to start idle motion for group '{IdleGroup}'. The group might be empty or invalid.\", IDLE_MOTION_GROUP);\n // Optionally disable idle animations if it fails consistently?\n // We don't because sometimes this occurs when another animation with the same or higher priority is also playing.\n // _isIdleAnimationAvailable = false;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Exception occurred while trying to start idle motion for group '{IdleGroup}'. Disabling idle animations.\", IDLE_MOTION_GROUP);\n _isIdleAnimationAvailable = false;\n _currentIdleMotionEntry = null;\n }\n }\n\n #endregion\n\n #region Core Logic: Blinking\n\n private void UpdateBlinking(float deltaTime)\n {\n try\n {\n if ( _isBlinking )\n {\n _blinkPhaseTimer += deltaTime;\n float eyeValue;\n\n switch ( _currentBlinkState )\n {\n case BlinkState.Closing:\n // Calculate progress towards closed state (1.0 -> 0.0)\n eyeValue = Math.Max(EYE_CLOSED_VALUE, EYE_OPEN_VALUE - _blinkPhaseTimer / BLINK_CLOSING_DURATION);\n if ( _blinkPhaseTimer >= BLINK_CLOSING_DURATION )\n {\n _currentBlinkState = BlinkState.Closed;\n _blinkPhaseTimer = 0f;\n eyeValue = EYE_CLOSED_VALUE;\n _logger.LogTrace(\"Blink phase: Closed\");\n }\n\n break;\n\n case BlinkState.Closed:\n eyeValue = EYE_CLOSED_VALUE;\n if ( _blinkPhaseTimer >= BLINK_CLOSED_DURATION )\n {\n _currentBlinkState = BlinkState.Opening;\n _blinkPhaseTimer = 0f;\n _logger.LogTrace(\"Blink phase: Opening\");\n }\n\n break;\n\n case BlinkState.Opening:\n // Calculate progress towards open state (0.0 -> 1.0)\n eyeValue = Math.Min(EYE_OPEN_VALUE, EYE_CLOSED_VALUE + _blinkPhaseTimer / BLINK_OPENING_DURATION);\n if ( _blinkPhaseTimer >= BLINK_OPENING_DURATION )\n {\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n SetNextBlinkInterval();\n eyeValue = EYE_OPEN_VALUE;\n _logger.LogTrace(\"Blink finished. Next blink in {Interval:F2}s\", _timeUntilNextBlink);\n SetEyeParameters(eyeValue);\n\n return; // Exit early as state is reset\n }\n\n break;\n\n case BlinkState.Idle:\n default:\n _logger.LogWarning(\"Invalid blink state detected while _isBlinking was true. Resetting blink state.\");\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n SetNextBlinkInterval();\n ResetEyesToOpenState();\n\n return; // Exit early\n }\n\n SetEyeParameters(eyeValue);\n }\n else\n {\n _timeUntilNextBlink -= deltaTime;\n if ( _timeUntilNextBlink <= 0f )\n {\n // Start a new blink cycle\n _isBlinking = true;\n _currentBlinkState = BlinkState.Closing;\n _blinkPhaseTimer = 0f;\n _logger.LogTrace(\"Starting blink.\");\n // Set initial closing value immediately? Or wait for next frame?\n // Current logic waits for the next frame's update. This is usually fine.\n }\n // IMPORTANT: Do not call SetEyeParameters here when idle.\n // Other animations (like facial expressions) might be controlling the eyes.\n // We only take control during the blink itself.\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during blinking update. Disabling blinking for safety.\");\n _eyeParamsValid = false; // Prevent further blinking attempts\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n ResetEyesToOpenState();\n }\n }\n\n /// \n /// Sets the values for the left and right eye openness parameters.\n /// Includes error handling to disable blinking if parameters become invalid.\n /// \n /// The value to set (typically between 0.0 and 1.0).\n private void SetEyeParameters(float value)\n {\n // Redundant checks, but safe:\n if ( _model?.Model == null || !_eyeParamsValid )\n {\n return;\n }\n\n try\n {\n _model.Model.SetParameterValue(PARAM_EYE_L_OPEN, value);\n _model.Model.SetParameterValue(PARAM_EYE_R_OPEN, value);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to set eye parameters (L:'{ParamL}', R:'{ParamR}') to value {Value}. Disabling blinking.\",\n PARAM_EYE_L_OPEN, PARAM_EYE_R_OPEN, value);\n\n _eyeParamsValid = false;\n _isBlinking = false;\n _currentBlinkState = BlinkState.Idle;\n // Don't try to reset eyes here, as the SetParameterValue call itself failed.\n }\n }\n\n private void ResetEyesToOpenState()\n {\n if ( _model?.Model != null && _eyeParamsValid )\n {\n _logger.LogTrace(\"Attempting to reset eyes to open state.\");\n SetEyeParameters(EYE_OPEN_VALUE);\n }\n else\n {\n _logger.LogTrace(\"Skipping reset eyes to open state (Model null or eye params invalid).\");\n }\n }\n\n /// \n /// Calculates and sets the random time interval until the next blink should start.\n /// \n private void SetNextBlinkInterval()\n {\n _timeUntilNextBlink = (float)(_random.NextDouble() *\n (BLINK_INTERVAL_MAX_SECONDS - BLINK_INTERVAL_MIN_SECONDS) +\n BLINK_INTERVAL_MIN_SECONDS);\n }\n\n #endregion\n\n #region IDisposable Implementation\n\n public void Dispose() { Dispose(true); }\n\n private void Dispose(bool disposing)\n {\n if ( !_disposed )\n {\n if ( disposing )\n {\n _logger.LogDebug(\"Disposing IdleBlinkingAnimationService...\");\n Stop();\n _model = null;\n _logger.LogInformation(\"IdleBlinkingAnimationService disposed.\");\n }\n\n _disposed = true;\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismMatrix44.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 4x4行列の便利クラス。\n/// \npublic record CubismMatrix44\n{\n private readonly float[] _mpt1 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n private readonly float[] _mpt2 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n private readonly float[] Ident = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ];\n\n public float[] _mpt = new float[16];\n\n /// \n /// 4x4行列データ\n /// \n protected float[] _tr = new float[16];\n\n /// \n /// コンストラクタ。\n /// \n public CubismMatrix44() { LoadIdentity(); }\n\n public float[] Tr => _tr;\n\n /// \n /// 単位行列に初期化する。\n /// \n public void LoadIdentity() { SetMatrix(Ident); }\n\n /// \n /// 行列を設定する。\n /// \n /// 16個の浮動小数点数で表される4x4の行列\n public void SetMatrix(float[] tr) { Array.Copy(tr, _tr, 16); }\n\n public void SetMatrix(CubismMatrix44 tr) { SetMatrix(tr.Tr); }\n\n /// \n /// X軸の拡大率を取得する。\n /// \n /// X軸の拡大率\n public float GetScaleX() { return _tr[0]; }\n\n /// \n /// Y軸の拡大率を取得する。\n /// \n /// Y軸の拡大率\n public float GetScaleY() { return _tr[5]; }\n\n /// \n /// X軸の移動量を取得する。\n /// \n /// X軸の移動量\n public float GetTranslateX() { return _tr[12]; }\n\n /// \n /// Y軸の移動量を取得する。\n /// \n /// Y軸の移動量\n public float GetTranslateY() { return _tr[13]; }\n\n /// \n /// X軸の値を現在の行列で計算する。\n /// \n /// X軸の値\n /// 現在の行列で計算されたX軸の値\n public float TransformX(float src) { return _tr[0] * src + _tr[12]; }\n\n /// \n /// Y軸の値を現在の行列で計算する。\n /// \n /// Y軸の値\n /// 現在の行列で計算されたY軸の値\n public float TransformY(float src) { return _tr[5] * src + _tr[13]; }\n\n /// \n /// X軸の値を現在の行列で逆計算する。\n /// \n /// X軸の値\n /// 現在の行列で逆計算されたX軸の値\n public float InvertTransformX(float src) { return (src - _tr[12]) / _tr[0]; }\n\n /// \n /// Y軸の値を現在の行列で逆計算する。\n /// \n /// Y軸の値\n /// 現在の行列で逆計算されたY軸の値\n public float InvertTransformY(float src) { return (src - _tr[13]) / _tr[5]; }\n\n /// \n /// 現在の行列の位置を起点にして相対的に移動する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void TranslateRelative(float x, float y)\n {\n _mpt1[12] = x;\n _mpt1[13] = y;\n MultiplyByMatrix(_mpt1);\n }\n\n /// \n /// 現在の行列の位置を指定した位置へ移動する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void Translate(float x, float y)\n {\n _tr[12] = x;\n _tr[13] = y;\n }\n\n /// \n /// 現在の行列のX軸の位置を指定した位置へ移動する。\n /// \n /// X軸の移動量\n public void TranslateX(float x) { _tr[12] = x; }\n\n /// \n /// 現在の行列のY軸の位置を指定した位置へ移動する。\n /// \n /// Y軸の移動量\n public void TranslateY(float y) { _tr[13] = y; }\n\n /// \n /// 現在の行列の拡大率を相対的に設定する。\n /// \n /// X軸の拡大率\n /// Y軸の拡大率\n public void ScaleRelative(float x, float y)\n {\n _mpt2[0] = x;\n _mpt2[5] = y;\n MultiplyByMatrix(_mpt2);\n }\n\n /// \n /// 現在の行列の拡大率を指定した倍率に設定する。\n /// \n /// X軸の拡大率\n /// Y軸の拡大率\n public void Scale(float x, float y)\n {\n _tr[0] = x;\n _tr[5] = y;\n }\n\n public void MultiplyByMatrix(float[] a)\n {\n Array.Fill(_mpt, 0);\n\n var n = 4;\n\n for ( var i = 0; i < n; ++i )\n {\n for ( var j = 0; j < n; ++j )\n {\n for ( var k = 0; k < n; ++k )\n {\n _mpt[j + i * 4] += a[k + i * 4] * _tr[j + k * 4];\n }\n }\n }\n\n Array.Copy(_mpt, _tr, 16);\n }\n\n /// \n /// 現在の行列に行列を乗算する。\n /// \n /// 行列\n public void MultiplyByMatrix(CubismMatrix44 m) { MultiplyByMatrix(m.Tr); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppWavFileHandler.cs", "using System.Text;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\npublic class WavFileInfo\n{\n public int _bitsPerSample;\n\n public string _fileName;\n\n public int _numberOfChannels;\n\n public int _samplePerChannel;\n\n public int _samplingRate;\n}\n\npublic class LAppWavFileHandler\n{\n private readonly ByteReader _byteReader;\n\n private readonly WavFileInfo _wavFileInfo;\n\n private double _lastRms;\n\n private float[] _pcmData;\n\n private double _sampleOffset;\n\n private double _userTimeSeconds;\n\n public LAppWavFileHandler()\n {\n _pcmData = Array.Empty();\n _userTimeSeconds = 0.0;\n _lastRms = 0.0;\n _sampleOffset = 0.0;\n _wavFileInfo = new WavFileInfo();\n _byteReader = new ByteReader();\n }\n\n public bool Update(float deltaTimeSeconds)\n {\n double goalOffset;\n float rms;\n\n // データロード前/ファイル末尾に達した場合は更新しない\n if ( _pcmData == null || _sampleOffset >= _wavFileInfo._samplePerChannel )\n {\n _lastRms = 0.0f;\n\n return false;\n }\n\n // 経過時間後の状態を保持\n _userTimeSeconds += deltaTimeSeconds;\n goalOffset = Math.Floor(_userTimeSeconds * _wavFileInfo._samplingRate);\n if ( goalOffset > _wavFileInfo._samplePerChannel )\n {\n goalOffset = _wavFileInfo._samplePerChannel;\n }\n\n // RMS計測\n rms = 0.0f;\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n for ( var sampleCount = (int)_sampleOffset; sampleCount < goalOffset; sampleCount++ )\n {\n var index = sampleCount * _wavFileInfo._numberOfChannels + channelCount;\n if ( index >= _pcmData.Length )\n {\n // Ensure we do not go out of bounds\n break;\n }\n\n var pcm = _pcmData[index];\n rms += pcm * pcm;\n }\n }\n\n rms = (float)Math.Sqrt(rms / (_wavFileInfo._numberOfChannels * (goalOffset - _sampleOffset)));\n\n _lastRms = rms;\n _sampleOffset = goalOffset;\n\n return true;\n }\n\n public void Start(string filePath)\n {\n // サンプル位参照位置を初期化\n _sampleOffset = 0;\n _userTimeSeconds = 0.0f;\n\n // RMS値をリセット\n _lastRms = 0.0f;\n }\n\n public double GetRms() { return _lastRms; }\n\n public async Task LoadWavFile(string filePath)\n {\n if ( _pcmData != null )\n {\n ReleasePcmData();\n }\n\n // ファイルロード\n var response = await FetchAsync(filePath);\n if ( response != null )\n {\n // Process the response to load PCM data\n return await AsyncWavFileManager(filePath);\n }\n\n return false;\n }\n\n private async Task FetchAsync(string filePath) { return await Task.Run(() => File.ReadAllBytes(filePath)); }\n\n public async Task AsyncWavFileManager(string filePath)\n {\n var ret = false;\n _byteReader._fileByte = await FetchAsync(filePath);\n _byteReader._fileDataView = new MemoryStream(_byteReader._fileByte);\n _byteReader._fileSize = _byteReader._fileByte.Length;\n _byteReader._readOffset = 0;\n\n // Check if file load failed or if there is not enough size for the signature \"RIFF\"\n if ( _byteReader._fileByte == null || _byteReader._fileSize < 4 )\n {\n return false;\n }\n\n // File name\n _wavFileInfo._fileName = filePath;\n\n try\n {\n // Signature \"RIFF\"\n if ( !_byteReader.GetCheckSignature(\"RIFF\") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'RIFF'.\");\n }\n\n // File size - 8 (skip)\n _byteReader.Get32LittleEndian();\n // Signature \"WAVE\"\n if ( !_byteReader.GetCheckSignature(\"WAVE\") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'WAVE'.\");\n }\n\n // Signature \"fmt \"\n if ( !_byteReader.GetCheckSignature(\"fmt \") )\n {\n ret = false;\n\n throw new Exception(\"Cannot find Signature 'fmt'.\");\n }\n\n // fmt chunk size\n var fmtChunkSize = (int)_byteReader.Get32LittleEndian();\n // Format ID must be 1 (linear PCM)\n if ( _byteReader.Get16LittleEndian() != 1 )\n {\n ret = false;\n\n throw new Exception(\"File is not linear PCM.\");\n }\n\n // Number of channels\n _wavFileInfo._numberOfChannels = (int)_byteReader.Get16LittleEndian();\n // Sampling rate\n _wavFileInfo._samplingRate = (int)_byteReader.Get32LittleEndian();\n // Data rate [byte/sec] (skip)\n _byteReader.Get32LittleEndian();\n // Block size (skip)\n _byteReader.Get16LittleEndian();\n // Bits per sample\n _wavFileInfo._bitsPerSample = (int)_byteReader.Get16LittleEndian();\n // Skip the extended part of the fmt chunk\n if ( fmtChunkSize > 16 )\n {\n _byteReader._readOffset += fmtChunkSize - 16;\n }\n\n // Skip until \"data\" chunk appears\n while ( !_byteReader.GetCheckSignature(\"data\") && _byteReader._readOffset < _byteReader._fileSize )\n {\n _byteReader._readOffset += (int)_byteReader.Get32LittleEndian() + 4;\n }\n\n // \"data\" chunk not found in the file\n if ( _byteReader._readOffset >= _byteReader._fileSize )\n {\n ret = false;\n\n throw new Exception(\"Cannot find 'data' Chunk.\");\n }\n\n // Number of samples\n {\n var dataChunkSize = (int)_byteReader.Get32LittleEndian();\n _wavFileInfo._samplePerChannel = dataChunkSize * 8 / (_wavFileInfo._bitsPerSample * _wavFileInfo._numberOfChannels);\n }\n\n // Allocate memory\n _pcmData = new float[_wavFileInfo._numberOfChannels * _wavFileInfo._samplePerChannel];\n // Retrieve waveform data\n for ( var sampleCount = 0; sampleCount < _wavFileInfo._samplePerChannel; sampleCount++ )\n {\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n _pcmData[sampleCount * _wavFileInfo._numberOfChannels + channelCount] = GetPcmSample();\n }\n }\n\n ret = true;\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n\n return ret;\n }\n\n public float GetPcmSample()\n {\n int pcm32;\n\n // Expand to 32-bit width and round to the range -1 to 1\n switch ( _wavFileInfo._bitsPerSample )\n {\n case 8:\n pcm32 = _byteReader.Get8() - 128;\n pcm32 <<= 24;\n\n break;\n case 16:\n pcm32 = (int)_byteReader.Get16LittleEndian() << 16;\n\n break;\n case 24:\n pcm32 = (int)_byteReader.Get24LittleEndian() << 8;\n\n break;\n default:\n // Unsupported bit width\n pcm32 = 0;\n\n break;\n }\n\n return pcm32 / 2147483647f; // float.MaxValue;\n }\n\n private void ReleasePcmData()\n {\n for ( var channelCount = 0; channelCount < _wavFileInfo._numberOfChannels; channelCount++ )\n {\n for ( var sampleCount = 0; sampleCount < _wavFileInfo._samplePerChannel; sampleCount++ )\n {\n _pcmData[sampleCount * _wavFileInfo._numberOfChannels + channelCount] = 0.0f;\n }\n }\n\n _pcmData = Array.Empty();\n }\n}\n\npublic class ByteReader\n{\n public byte[] _fileByte;\n\n public MemoryStream _fileDataView;\n\n public int _fileSize;\n\n public int _readOffset;\n\n public int Get8()\n {\n var returnValue = _fileDataView.ReadByte();\n _readOffset++;\n\n return returnValue;\n }\n\n /**\n * @brief 16ビット読み込み(リトルエンディアン)\n * @return Csm::csmUint16 読み取った16ビット値\n */\n public uint Get16LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8);\n\n return ret;\n }\n\n /// \n /// 24ビット読み込み(リトルエンディアン)\n /// \n /// 読み取った24ビット値(下位24ビットに設定)\n public uint Get24LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8) |\n (uint)(Get8() << 16);\n\n return ret;\n }\n\n /// \n /// 32ビット読み込み(リトルエンディアン)\n /// \n /// 読み取った32ビット値\n public uint Get32LittleEndian()\n {\n var ret =\n (uint)(Get8() << 0) |\n (uint)(Get8() << 8) |\n (uint)(Get8() << 16) |\n (uint)(Get8() << 24);\n\n return ret;\n }\n\n /// \n /// シグネチャの取得と参照文字列との一致チェック\n /// \n /// 検査対象のシグネチャ文字列\n /// true 一致している, false 一致していない\n public bool GetCheckSignature(string reference)\n {\n if ( reference.Length != 4 )\n {\n return false;\n }\n\n var getSignature = new byte[4];\n var referenceString = Encoding.UTF8.GetBytes(reference);\n\n for ( var signatureOffset = 0; signatureOffset < 4; signatureOffset++ )\n {\n getSignature[signatureOffset] = (byte)Get8();\n }\n\n return getSignature[0] == referenceString[0] &&\n getSignature[1] == referenceString[1] &&\n getSignature[2] == referenceString[2] &&\n getSignature[3] == referenceString[3];\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Audio/BlacklistAudioFilter.cs", "using System.Globalization;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nusing PersonaEngine.Lib.TTS.Profanity;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.Audio;\n\n/// \n/// Audio filter that censors profane content by replacing it with a beep tone.\n/// \npublic class BlacklistAudioFilter : IAudioFilter\n{\n // Configuration constants\n private const float DEFAULT_BEEP_FREQUENCY = 880; // Changed from 400Hz to 1000Hz (standard censor beep)\n\n private const float DEFAULT_BEEP_VOLUME = 0.35f; // Slightly increased for better audibility\n\n private const int REFERENCE_SAMPLE_RATE = 24000;\n\n // Common suffixes to check when matching profanity\n private static readonly string[] COMMON_SUFFIXES = { \"s\", \"es\", \"ed\", \"ing\", \"er\", \"ers\" };\n\n // Pre-calculated beep tone samples\n private readonly float[] _beepCycle;\n\n private readonly float _beepFrequency;\n\n private readonly float _beepVolume;\n\n private readonly ProfanityDetector _profanityDetector;\n\n private readonly HashSet _profanityDictionary;\n\n // Cache for previously checked words to improve performance\n private readonly Dictionary _wordCheckCache = new(StringComparer.OrdinalIgnoreCase);\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The profanity detector service.\n public BlacklistAudioFilter(ProfanityDetector profanityDetector)\n : this(profanityDetector, DEFAULT_BEEP_FREQUENCY) { }\n\n /// \n /// Initializes a new instance of the class with custom audio parameters.\n /// \n /// The profanity detector service.\n /// The frequency of the beep tone in Hz.\n /// The volume of the beep tone (0.0-1.0).\n /// Thrown when profanityDetector is null.\n public BlacklistAudioFilter(\n ProfanityDetector profanityDetector,\n float beepFrequency = DEFAULT_BEEP_FREQUENCY,\n float beepVolume = DEFAULT_BEEP_VOLUME)\n {\n _profanityDetector = profanityDetector ?? throw new ArgumentNullException(nameof(profanityDetector));\n _beepFrequency = beepFrequency;\n _beepVolume = Math.Clamp(beepVolume, 0.0f, 1.0f);\n\n // Load profanity dictionary\n var profanityListPath = ModelUtils.GetModelPath(ModelType.BadWords);\n _profanityDictionary = LoadProfanityDictionary(profanityListPath);\n\n // Pre-calculate one cycle of the beep tone for efficient reuse\n // Using a square wave instead of sine wave for a more traditional censorship beep\n var samplesPerCycle = (int)(REFERENCE_SAMPLE_RATE / _beepFrequency);\n _beepCycle = new float[samplesPerCycle];\n\n for ( var i = 0; i < samplesPerCycle; i++ )\n {\n // Generate square wave (values are either +volume or -volume)\n _beepCycle[i] = i < samplesPerCycle / 2 ? _beepVolume : -_beepVolume;\n }\n }\n\n /// \n /// Processes an audio segment to censor profane content with beep tones.\n /// \n /// The audio segment to process.\n public void Process(AudioSegment segment)\n {\n if ( segment == null || segment.AudioData.IsEmpty || segment.Tokens == null || segment.Tokens.Count == 0 )\n {\n return; // Early exit for invalid segments\n }\n\n var tokens = segment.Tokens;\n var audioSpan = segment.AudioData.Span;\n var sampleRate = segment.SampleRate;\n\n // First step: Identify and mark profane tokens\n MarkProfaneTokens(tokens);\n\n // Second step: Apply beep sound to marked tokens\n foreach ( var (token, index) in tokens.Select((t, i) => (t, i)) )\n {\n if ( token is not { Text: \"[REDACTED]\" } )\n {\n continue; // Skip null or non-redacted tokens\n }\n\n // Determine valid time boundaries for the audio replacement\n var (startTime, endTime) = DetermineTimeBoundaries(token, tokens, index);\n\n // Convert timestamps to sample indices\n var startIndex = (int)(startTime * sampleRate);\n var endIndex = (int)(endTime * sampleRate);\n\n // Validate indices to prevent out-of-bounds access\n startIndex = Math.Max(0, startIndex);\n endIndex = Math.Min(audioSpan.Length, endIndex);\n\n if ( startIndex >= endIndex || startIndex >= audioSpan.Length )\n {\n continue; // Invalid range\n }\n\n // Apply beep tone to the segment\n ApplyBeepTone(audioSpan, startIndex, endIndex, sampleRate);\n }\n }\n\n public int Priority => -100;\n\n /// \n /// Marks tokens containing profanity based on the overall severity level.\n /// \n /// The list of tokens to process.\n /// The tolerance level for profanity.\n private void MarkProfaneTokens(IReadOnlyList tokens, ProfanitySeverity tolerance = ProfanitySeverity.Clean)\n {\n if ( tokens.Count == 0 )\n {\n return;\n }\n\n // Build the full sentence from tokens for overall evaluation\n var sentence = BuildSentenceFromTokens(tokens);\n\n // Evaluate overall profanity severity\n var overallSeverity = _profanityDetector.EvaluateProfanity(sentence);\n\n // If the overall severity is within tolerance, no need to censor\n if ( overallSeverity <= tolerance )\n {\n return;\n }\n\n // Mark individual profane tokens\n foreach ( var token in tokens )\n {\n if ( token == null || string.IsNullOrWhiteSpace(token.Text) )\n {\n continue;\n }\n\n // Split the token into words to check each individually\n var words = SplitIntoWords(token.Text);\n\n foreach ( var word in words )\n {\n if ( IsProfaneWord(word) )\n {\n token.Text = \"[REDACTED]\";\n\n break; // Break once we find any profanity in the token\n }\n }\n }\n }\n\n /// \n /// Splits text into individual words, preserving only alphanumeric characters.\n /// \n private static IEnumerable SplitIntoWords(string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n yield break;\n }\n\n // Use regex to split text into words (sequences of letters)\n var matches = Regex.Matches(text, @\"\\b[a-zA-Z]+\\b\");\n\n foreach ( Match match in matches )\n {\n yield return match.Value;\n }\n }\n\n /// \n /// Builds a complete sentence from a list of tokens.\n /// \n private static string BuildSentenceFromTokens(IReadOnlyList tokens)\n {\n if ( tokens.Count == 0 )\n {\n return string.Empty;\n }\n\n var builder = new StringBuilder();\n\n // Add all tokens except the last one with their whitespace\n for ( var i = 0; i < tokens.Count - 1; i++ )\n {\n if ( tokens[i] == null || tokens[i].Text == null )\n {\n continue;\n }\n\n builder.Append(tokens[i].Text);\n if ( tokens[i].Whitespace == \" \" )\n {\n builder.Append(' ');\n }\n }\n\n // Add the last token\n if ( tokens[^1] != null && tokens[^1].Text != null )\n {\n builder.Append(tokens[^1].Text);\n }\n\n return builder.ToString();\n }\n\n /// \n /// Determines the start and end time boundaries for audio replacement.\n /// \n private (double Start, double End) DetermineTimeBoundaries(Token token, IReadOnlyList allTokens, int tokenIndex)\n {\n if ( token == null )\n {\n return (0, 0); // Default for null tokens\n }\n\n double startTime,\n endTime;\n\n // Handle the case where this is the first token with missing timestamps\n if ( tokenIndex == 0 && (!token.StartTs.HasValue || !token.EndTs.HasValue) )\n {\n startTime = 0;\n\n // For end time, use token's end time if available, otherwise use a reasonable default\n endTime = token.EndTs ?? EstimateTokenDuration(token);\n }\n else\n {\n // Determine start time\n if ( !token.StartTs.HasValue )\n {\n // If no start time is available, use previous token's end time if possible\n if ( tokenIndex > 0 && allTokens[tokenIndex - 1] != null )\n {\n var prevToken = allTokens[tokenIndex - 1];\n startTime = prevToken.EndTs ?? prevToken.StartTs ?? 0;\n }\n else\n {\n startTime = 0;\n }\n }\n else\n {\n startTime = token.StartTs.Value;\n }\n\n // Determine end time\n if ( !token.EndTs.HasValue )\n {\n // If no end time is available, check if we can use the next token's start time\n if ( tokenIndex < allTokens.Count - 1 && allTokens[tokenIndex + 1] != null )\n {\n var nextToken = allTokens[tokenIndex + 1];\n endTime = nextToken.StartTs ?? startTime + EstimateTokenDuration(token);\n }\n else\n {\n // For the last token, estimate a reasonable duration\n endTime = startTime + EstimateTokenDuration(token);\n }\n }\n else\n {\n endTime = token.EndTs.Value;\n }\n }\n\n // Ensure we always have a positive duration\n if ( endTime <= startTime )\n {\n endTime = startTime + 0.1; // Add minimal duration if times are invalid\n }\n\n return (startTime, endTime);\n }\n\n /// \n /// Estimates a reasonable duration for a token based on its content length.\n /// \n private double EstimateTokenDuration(Token token)\n {\n if ( token == null )\n {\n return 0.1; // Default for null tokens\n }\n\n // Average speaking rate is roughly 5-6 characters per second\n const double charsPerSecond = 5.5;\n\n // Minimum duration to ensure even single characters get enough time\n const double minimumDuration = 0.1;\n\n return Math.Max(minimumDuration, (token.Text?.Length ?? 0) / charsPerSecond);\n }\n\n /// \n /// Applies a beep tone to a section of audio with smooth fade-in and fade-out.\n /// \n private void ApplyBeepTone(Span audioData, int startIndex, int endIndex, int sampleRate)\n {\n var length = endIndex - startIndex;\n if ( length <= 0 )\n {\n return;\n }\n\n // Calculate how to map our pre-calculated beep cycle to the current sample rate\n var cycleScaleFactor = (double)sampleRate / REFERENCE_SAMPLE_RATE;\n\n // Number of samples for one complete cycle at the current sample rate\n var samplesPerCycle = (int)(_beepCycle.Length * cycleScaleFactor);\n\n // Make sure we have at least one sample per cycle\n samplesPerCycle = Math.Max(1, samplesPerCycle);\n\n // Apply a short fade-in and fade-out to avoid clicks\n // 5ms fade at current sample rate or 1/4 of segment length, whichever is smaller\n var fadeLength = Math.Min((int)(0.005 * sampleRate), length / 4);\n fadeLength = Math.Max(1, fadeLength); // Ensure at least 1 sample for fade\n\n for ( var i = 0; i < length; i++ )\n {\n // Calculate the position in the beep cycle\n var cycleIndex = (int)(i % samplesPerCycle / cycleScaleFactor) % _beepCycle.Length;\n\n // Get beep sample from pre-calculated cycle (with bounds check)\n var beepSample = _beepCycle[Math.Max(0, Math.Min(cycleIndex, _beepCycle.Length - 1))];\n\n // Apply fade-in and fade-out for smoother audio transitions\n var fadeMultiplier = 1.0f;\n if ( i < fadeLength )\n {\n fadeMultiplier = (float)i / fadeLength; // Linear fade-in\n }\n else if ( i > length - fadeLength )\n {\n fadeMultiplier = (float)(length - i) / fadeLength; // Linear fade-out\n }\n\n // Replace the original sample with the beep\n audioData[startIndex + i] = beepSample * fadeMultiplier;\n }\n }\n\n /// \n /// Checks if the given word is profane, including checking for variations.\n /// \n private bool IsProfaneWord(string word)\n {\n if ( string.IsNullOrWhiteSpace(word) )\n {\n return false;\n }\n\n // Check cache first to avoid redundant processing\n if ( _wordCheckCache.TryGetValue(word, out var result) )\n {\n return result;\n }\n\n // Normalize the word\n var normalized = NormalizeText(word);\n\n // Direct match check\n if ( _profanityDictionary.Contains(normalized) )\n {\n _wordCheckCache[word] = true;\n\n return true;\n }\n\n // Check for variations with common suffixes\n foreach ( var suffix in COMMON_SUFFIXES )\n {\n if ( normalized.EndsWith(suffix, StringComparison.OrdinalIgnoreCase) )\n {\n // Try removing the suffix and check if the base word is profane\n var baseWord = normalized.Substring(0, normalized.Length - suffix.Length);\n\n // Only check non-empty base words\n if ( !string.IsNullOrEmpty(baseWord) && _profanityDictionary.Contains(baseWord) )\n {\n _wordCheckCache[word] = true;\n\n return true;\n }\n }\n }\n\n // Word not found to be profane after all checks\n _wordCheckCache[word] = false;\n\n return false;\n }\n\n /// \n /// Normalizes text by removing diacritics, punctuation, and converting to lowercase.\n /// \n private static string NormalizeText(string text)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return string.Empty;\n }\n\n // Convert to lowercase and normalize diacritics\n var normalized = text.ToLowerInvariant().Normalize(NormalizationForm.FormD);\n\n // Remove diacritical marks and punctuation in a single pass for efficiency\n var sb = new StringBuilder(normalized.Length);\n foreach ( var c in normalized )\n {\n // Keep only characters that are not diacritics or punctuation\n if ( CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark && !char.IsPunctuation(c) )\n {\n sb.Append(c);\n }\n }\n\n return sb.ToString().Trim();\n }\n\n /// \n /// Loads the profanity dictionary from a file with error handling.\n /// \n private static HashSet LoadProfanityDictionary(string filePath)\n {\n try\n {\n if ( string.IsNullOrEmpty(filePath) || !File.Exists(filePath) )\n {\n Console.Error.WriteLine($\"Warning: Profanity list file not found at: {filePath}\");\n\n return new HashSet(StringComparer.OrdinalIgnoreCase);\n }\n\n return new HashSet(\n File.ReadAllLines(filePath)\n .Where(line => !string.IsNullOrWhiteSpace(line))\n .Select(word => NormalizeText(word.Trim())),\n StringComparer.OrdinalIgnoreCase\n );\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Error loading profanity dictionary: {ex.Message}\");\n\n return new HashSet(StringComparer.OrdinalIgnoreCase);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismMath.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// 数値計算などに使用するユーティリティクラス\n/// \npublic static class CubismMath\n{\n public const float Pi = 3.1415926535897932384626433832795f;\n\n public const float Epsilon = 0.00001f;\n\n /// \n /// 第一引数の値を最小値と最大値の範囲に収めた値を返す\n /// \n /// 収められる値\n /// 範囲の最小値\n /// 範囲の最大値\n /// 最小値と最大値の範囲に収めた値\n public static float RangeF(float value, float min, float max)\n {\n if ( value < min )\n {\n value = min;\n }\n else if ( value > max )\n {\n value = max;\n }\n\n return value;\n }\n\n /// \n /// イージング処理されたサインを求める\n /// フェードイン・アウト時のイージングに利用できる\n /// \n /// イージングを行う値\n /// イージング処理されたサイン値\n public static float GetEasingSine(float value)\n {\n if ( value < 0.0f )\n {\n return 0.0f;\n }\n\n if ( value > 1.0f )\n {\n return 1.0f;\n }\n\n return 0.5f - 0.5f * MathF.Cos(value * Pi);\n }\n\n /// \n /// 大きい方の値を返す。\n /// \n /// 左辺の値\n /// 右辺の値\n /// 大きい方の値\n public static float Max(float l, float r) { return l > r ? l : r; }\n\n /// \n /// 小さい方の値を返す。\n /// \n /// 左辺の値\n /// 右辺の値\n /// 小さい方の値\n public static float Min(float l, float r) { return l > r ? r : l; }\n\n /// \n /// 角度値をラジアン値に変換します。\n /// \n /// 角度値\n /// 角度値から変換したラジアン値\n public static float DegreesToRadian(float degrees) { return degrees / 180.0f * Pi; }\n\n /// \n /// ラジアン値を角度値に変換します。\n /// \n /// ラジアン値\n /// ラジアン値から変換した角度値\n public static float RadianToDegrees(float radian) { return radian * 180.0f / Pi; }\n\n /// \n /// 2つのベクトルからラジアン値を求めます。\n /// \n /// 始点ベクトル\n /// 終点ベクトル\n /// ラジアン値から求めた方向ベクトル\n public static float DirectionToRadian(Vector2 from, Vector2 to)\n {\n float q1;\n float q2;\n float ret;\n\n q1 = MathF.Atan2(to.Y, to.X);\n q2 = MathF.Atan2(from.Y, from.X);\n\n ret = q1 - q2;\n\n while ( ret < -Pi )\n {\n ret += Pi * 2.0f;\n }\n\n while ( ret > Pi )\n {\n ret -= Pi * 2.0f;\n }\n\n return ret;\n }\n\n /// \n /// 2つのベクトルから角度値を求めます。\n /// \n /// 始点ベクトル\n /// 終点ベクトル\n /// 角度値から求めた方向ベクトル\n public static float DirectionToDegrees(Vector2 from, Vector2 to)\n {\n float radian;\n float degree;\n\n radian = DirectionToRadian(from, to);\n degree = RadianToDegrees(radian);\n\n if ( to.X - from.X > 0.0f )\n {\n degree = -degree;\n }\n\n return degree;\n }\n\n /// \n /// ラジアン値を方向ベクトルに変換します。\n /// \n /// ラジアン値\n /// ラジアン値から変換した方向ベクトル\n public static Vector2 RadianToDirection(float totalAngle) { return new Vector2(MathF.Sin(totalAngle), MathF.Cos(totalAngle)); }\n\n /// \n /// 三次方程式の三次項の係数が0になったときに補欠的に二次方程式の解をもとめる。\n /// a * x^2 + b * x + c = 0\n /// \n /// 二次項の係数値\n /// 一次項の係数値\n /// 定数項の値\n /// 二次方程式の解\n public static float QuadraticEquation(float a, float b, float c)\n {\n if ( MathF.Abs(a) < Epsilon )\n {\n if ( MathF.Abs(b) < Epsilon )\n {\n return -c;\n }\n\n return -c / b;\n }\n\n return -(b + MathF.Sqrt(b * b - 4.0f * a * c)) / (2.0f * a);\n }\n\n /// \n /// カルダノの公式によってベジェのt値に該当する3次方程式の解を求める。\n /// 重解になったときには0.0~1.0の値になる解を返す。\n /// a * x^3 + b * x^2 + c * x + d = 0\n /// \n /// 三次項の係数値\n /// 二次項の係数値\n /// 一次項の係数値\n /// 定数項の値\n /// 0.0~1.0の間にある解\n public static float CardanoAlgorithmForBezier(float a, float b, float c, float d)\n {\n if ( MathF.Abs(a) < Epsilon )\n {\n return RangeF(QuadraticEquation(b, c, d), 0.0f, 1.0f);\n }\n\n var ba = b / a;\n var ca = c / a;\n var da = d / a;\n\n var p = (3.0f * ca - ba * ba) / 3.0f;\n var p3 = p / 3.0f;\n var q = (2.0f * ba * ba * ba - 9.0f * ba * ca + 27.0f * da) / 27.0f;\n var q2 = q / 2.0f;\n var discriminant = q2 * q2 + p3 * p3 * p3;\n\n var center = 0.5f;\n var threshold = center + 0.01f;\n\n float root1;\n float u1;\n\n if ( discriminant < 0.0f )\n {\n var mp3 = -p / 3.0f;\n var mp33 = mp3 * mp3 * mp3;\n var r = MathF.Sqrt(mp33);\n var t = -q / (2.0f * r);\n var cosphi = RangeF(t, -1.0f, 1.0f);\n var phi = MathF.Acos(cosphi);\n var crtr = MathF.Cbrt(r);\n var t1 = 2.0f * crtr;\n\n root1 = t1 * MathF.Cos(phi / 3.0f) - ba / 3.0f;\n if ( MathF.Abs(root1 - center) < threshold )\n {\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n var root2 = t1 * MathF.Cos((phi + 2.0f * Pi) / 3.0f) - ba / 3.0f;\n if ( MathF.Abs(root2 - center) < threshold )\n {\n return RangeF(root2, 0.0f, 1.0f);\n }\n\n var root3 = t1 * MathF.Cos((phi + 4.0f * Pi) / 3.0f) - ba / 3.0f;\n\n return RangeF(root3, 0.0f, 1.0f);\n }\n\n if ( discriminant == 0.0f )\n {\n if ( q2 < 0.0f )\n {\n u1 = MathF.Cbrt(-q2);\n }\n else\n {\n u1 = -MathF.Cbrt(q2);\n }\n\n root1 = 2.0f * u1 - ba / 3.0f;\n if ( MathF.Abs(root1 - center) < threshold )\n {\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n var root2 = -u1 - ba / 3.0f;\n\n return RangeF(root2, 0.0f, 1.0f);\n }\n\n var sd = MathF.Sqrt(discriminant);\n u1 = MathF.Cbrt(sd - q2);\n var v1 = MathF.Cbrt(sd + q2);\n root1 = u1 - v1 - ba / 3.0f;\n\n return RangeF(root1, 0.0f, 1.0f);\n }\n\n /// \n /// 値を範囲内に納めて返す\n /// \n /// 範囲内か確認する値\n /// 最小値\n /// 最大値\n /// 範囲内に収まった値\n public static int Clamp(int val, int min, int max)\n {\n if ( val < min )\n {\n return min;\n }\n\n if ( max < val )\n {\n return max;\n }\n\n return val;\n }\n\n /// \n /// 値を範囲内に納めて返す\n /// \n /// 範囲内か確認する値\n /// 最小値\n /// 最大値\n /// 範囲内に収まった値\n public static float ClampF(float val, float min, float max)\n {\n if ( val < min )\n {\n return min;\n }\n\n if ( max < val )\n {\n return max;\n }\n\n return val;\n }\n\n /// \n /// 浮動小数点の余りを求める。\n /// \n /// 被除数(割られる値)\n /// 除数(割る値)\n /// 余り\n public static float ModF(float dividend, float divisor)\n {\n if ( !float.IsFinite(dividend) || divisor == 0 || float.IsNaN(dividend) || float.IsNaN(divisor) )\n {\n CubismLog.Warning(\"dividend: %f, divisor: %f ModF() returns 'NaN'.\", dividend, divisor);\n\n return float.NaN;\n }\n\n // 絶対値に変換する。\n var absDividend = MathF.Abs(dividend);\n var absDivisor = MathF.Abs(divisor);\n\n // 絶対値で割り算する。\n var result = absDividend - MathF.Floor(absDividend / absDivisor) * absDivisor;\n\n // 符号を被除数のものに指定する。\n return MathF.CopySign(result, dividend);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Effect/PartData.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Effect;\n\n/// \n/// パーツにまつわる諸々のデータを管理する。\n/// \npublic record PartData\n{\n /// \n /// 連動するパラメータ\n /// \n public readonly List Link = [];\n\n /// \n /// パーツID\n /// \n public required string PartId { get; set; }\n\n /// \n /// パラメータのインデックス\n /// \n public int ParameterIndex { get; set; }\n\n /// \n /// パーツのインデックス\n /// \n public int PartIndex { get; set; }\n\n /// \n /// 初期化する。\n /// \n /// 初期化に使用するモデル\n public void Initialize(CubismModel model)\n {\n ParameterIndex = model.GetParameterIndex(PartId);\n PartIndex = model.GetPartIndex(PartId);\n\n model.SetParameterValue(ParameterIndex, 1);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppView.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Math;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 描画クラス\n/// \n/// \n/// コンストラクタ\n/// \npublic class LAppView(LAppDelegate lapp)\n{\n /// \n /// デバイスからスクリーンへの行列\n /// \n private readonly CubismMatrix44 _deviceToScreen = new();\n\n /// \n /// タッチマネージャー\n /// \n private readonly TouchManager _touchManager = new();\n\n /// \n /// viewMatrix\n /// \n private readonly CubismViewMatrix _viewMatrix = new();\n\n /// \n /// 初期化する。\n /// \n public void Initialize()\n {\n lapp.GL.GetWindowSize(out var width, out var height);\n\n if ( width == 0 || height == 0 )\n {\n return;\n }\n\n // 縦サイズを基準とする\n var ratio = (float)width / height;\n var left = -ratio;\n var right = ratio;\n var bottom = LAppDefine.ViewLogicalLeft;\n var top = LAppDefine.ViewLogicalRight;\n\n _viewMatrix.SetScreenRect(left, right, bottom, top); // デバイスに対応する画面の範囲。 Xの左端, Xの右端, Yの下端, Yの上端\n _viewMatrix.Scale(LAppDefine.ViewScale, LAppDefine.ViewScale);\n\n _deviceToScreen.LoadIdentity(); // サイズが変わった際などリセット必須\n if ( width > height )\n {\n var screenW = MathF.Abs(right - left);\n _deviceToScreen.ScaleRelative(screenW / width, -screenW / width);\n }\n else\n {\n var screenH = MathF.Abs(top - bottom);\n _deviceToScreen.ScaleRelative(screenH / height, -screenH / height);\n }\n\n _deviceToScreen.TranslateRelative(-width * 0.5f, -height * 0.5f);\n\n // 表示範囲の設定\n _viewMatrix.MaxScale = LAppDefine.ViewMaxScale; // 限界拡大率\n _viewMatrix.MinScale = LAppDefine.ViewMinScale; // 限界縮小率\n\n // 表示できる最大範囲\n _viewMatrix.SetMaxScreenRect(\n LAppDefine.ViewLogicalMaxLeft,\n LAppDefine.ViewLogicalMaxRight,\n LAppDefine.ViewLogicalMaxBottom,\n LAppDefine.ViewLogicalMaxTop\n );\n }\n\n /// \n /// 描画する。\n /// \n public void Render()\n {\n var Live2DManager = lapp.Live2dManager;\n Live2DManager.ViewMatrix.SetMatrix(_viewMatrix);\n\n // Cubism更新・描画\n Live2DManager.OnUpdate();\n }\n\n /// \n /// タッチされたときに呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesBegan(float pointX, float pointY)\n {\n _touchManager.TouchesBegan(pointX, pointY);\n CubismLog.Debug($\"[Live2D]touchesBegan x:{pointX:#.##} y:{pointY:#.##}\");\n }\n\n /// \n /// タッチしているときにポインタが動いたら呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesMoved(float pointX, float pointY)\n {\n var viewX = TransformViewX(_touchManager.GetX());\n var viewY = TransformViewY(_touchManager.GetY());\n\n _touchManager.TouchesMoved(pointX, pointY);\n\n lapp.Live2dManager.OnDrag(viewX, viewY);\n }\n\n /// \n /// タッチが終了したら呼ばれる。\n /// \n /// スクリーンX座標\n /// スクリーンY座標\n public void OnTouchesEnded(float _, float __)\n {\n // タッチ終了\n var live2DManager = lapp.Live2dManager;\n live2DManager.OnDrag(0.0f, 0.0f);\n // シングルタップ\n var x = _deviceToScreen.TransformX(_touchManager.GetX()); // 論理座標変換した座標を取得。\n var y = _deviceToScreen.TransformY(_touchManager.GetY()); // 論理座標変換した座標を取得。\n CubismLog.Debug($\"[Live2D]touchesEnded x:{x:#.##} y:{y:#.##}\");\n live2DManager.OnTap(x, y);\n }\n\n /// \n /// X座標をView座標に変換する。\n /// \n /// デバイスX座標\n public float TransformViewX(float deviceX)\n {\n var screenX = _deviceToScreen.TransformX(deviceX); // 論理座標変換した座標を取得。\n\n return _viewMatrix.InvertTransformX(screenX); // 拡大、縮小、移動後の値。\n }\n\n /// \n /// Y座標をView座標に変換する。\n /// \n /// デバイスY座標\n public float TransformViewY(float deviceY)\n {\n var screenY = _deviceToScreen.TransformY(deviceY); // 論理座標変換した座標を取得。\n\n return _viewMatrix.InvertTransformY(screenY); // 拡大、縮小、移動後の値。\n }\n\n /// \n /// X座標をScreen座標に変換する。\n /// \n /// デバイスX座標\n public float TransformScreenX(float deviceX) { return _deviceToScreen.TransformX(deviceX); }\n\n /// \n /// Y座標をScreen座標に変換する。\n /// \n /// デバイスY座標\n public float TransformScreenY(float deviceY) { return _deviceToScreen.TransformY(deviceY); }\n\n /// \n /// 別レンダリングターゲットにモデルを描画するサンプルで\n /// 描画時のαを決定する\n /// \n public static float GetSpriteAlpha(int assign)\n {\n // assignの数値に応じて適当に決定\n var alpha = 0.25f + assign * 0.5f; // サンプルとしてαに適当な差をつける\n if ( alpha > 1.0f )\n {\n alpha = 1.0f;\n }\n\n if ( alpha < 0.1f )\n {\n alpha = 0.1f;\n }\n\n return alpha;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionAnimationService.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.Live2D.Framework.Motion;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Manages Live2D model animations and expressions synchronized with detected speech emotions from audio playback.\n/// \n/// \n/// Responsibilities include:\n/// - Mapping detected emotion events (e.g., emojis from ) to Live2D expressions and\n/// motions.\n/// - Applying expressions for a configurable duration () before\n/// potentially reverting to neutral.\n/// - Playing specific emotion-driven motions or a neutral \"talking\" motion during audio playback.\n/// - Handling emotion timing based on the audio player's current position.\n/// - Persisting the last triggered expression/motion until the hold time expires or it's replaced.\n/// This service assumes LipSync, Blinking, and Idle animations are managed by other services with appropriate\n/// priorities.\n/// It requires an for timed emotion data and an\n/// for playback state and time.\n/// \npublic class EmotionAnimationService : ILive2DAnimationService\n{\n public EmotionAnimationService(ILogger logger, IAudioProgressNotifier audioProgressNotifier, IEmotionService emotionService)\n {\n _logger = logger;\n _audioProgressNotifier = audioProgressNotifier;\n _emotionService = emotionService;\n\n SubscribeToAudioProgressNotifier();\n }\n\n #region Nested Types\n\n private record EmotionMapping(string? ExpressionId, string? MotionGroup);\n\n #endregion\n\n #region Configuration\n\n // How long to hold an expression after it's triggered before reverting to neutral (if playback stops or no new emotion overrides it).\n private const float EXPRESSION_HOLD_DURATION_SECONDS = 3.0f;\n\n // Expression ID for the neutral state.\n private const string NEUTRAL_EXPRESSION_ID = \"neutral\";\n\n // Motion group used for the default talking animation when no specific emotion motion is active.\n private const string NEUTRAL_TALKING_MOTION_GROUP = \"Talking\";\n\n // Priority for motions triggered by specific emotions. Should typically be high to override idle/neutral talking.\n private const MotionPriority EMOTION_MOTION_PRIORITY = MotionPriority.PriorityForce;\n\n // Priority for the neutral talking motion. Should be lower than emotion motions but higher than idle.\n private const MotionPriority NEUTRAL_TALKING_MOTION_PRIORITY = MotionPriority.PriorityNormal;\n\n // Defines the mapping between detected emotion identifiers (e.g., emojis) and Live2D assets.\n // TODO: Consider loading this from an external configuration file for customization.\n private static readonly Dictionary EmotionMap = new() {\n // Positive Emotions\n { \"😊\", new EmotionMapping(\"happy\", \"Happy\") },\n { \"🤩\", new EmotionMapping(\"excited_star\", \"Excited\") },\n { \"😎\", new EmotionMapping(\"cool\", \"Confident\") },\n { \"😏\", new EmotionMapping(\"smug\", \"Confident\") },\n { \"💪\", new EmotionMapping(\"determined\", \"Confident\") },\n // Reactive Emotions\n { \"😳\", new EmotionMapping(\"embarrassed\", \"Nervous\") },\n { \"😲\", new EmotionMapping(\"shocked\", \"Surprised\") },\n { \"🤔\", new EmotionMapping(\"thinking\", \"Thinking\") },\n { \"👀\", new EmotionMapping(\"suspicious\", \"Thinking\") },\n // Negative Emotions\n { \"😤\", new EmotionMapping(\"frustrated\", \"Angry\") },\n { \"😢\", new EmotionMapping(\"sad\", \"Sad\") },\n { \"😅\", new EmotionMapping(\"awkward\", \"Nervous\") },\n { \"🙄\", new EmotionMapping(\"dismissive\", \"Annoyed\") },\n // Expressive Reactions\n { \"💕\", new EmotionMapping(\"adoring\", \"Happy\") },\n { \"😂\", new EmotionMapping(\"laughing\", \"Happy\") },\n { \"🔥\", new EmotionMapping(\"passionate\", \"Excited\") },\n { \"✨\", new EmotionMapping(\"sparkle\", \"Happy\") }\n // Neutral (can map if specific neutral actions are needed, otherwise handled implicitly)\n // { \"😐\", new EmotionMapping(NEUTRAL_EXPRESSION_ID, null) } // Example if needed\n };\n\n #endregion\n\n #region Dependencies\n\n private readonly ILogger _logger;\n\n private readonly IAudioProgressNotifier _audioProgressNotifier;\n\n private readonly IEmotionService _emotionService;\n\n #endregion\n\n #region State\n\n private LAppModel? _model;\n\n private readonly List _activeEmotions = new();\n\n private readonly HashSet _availableExpressions = new();\n\n private readonly HashSet _availableMotionGroups = new();\n\n private int _currentEmotionIndex = -1;\n\n private string? _triggeredEmotionEmoji = null;\n\n private string? _activeExpressionId = null;\n\n private float _timeSinceExpressionSet = 0.0f;\n\n private CubismMotionQueueEntry? _currentEmotionMotionEntry = null;\n\n private CubismMotionQueueEntry? _neutralTalkingMotionEntry = null;\n\n private bool _isStarted = false;\n\n private bool _isPlaying = false;\n\n private bool _disposed = false;\n\n #endregion\n\n #region ILive2DAnimationService Implementation\n\n private void SubscribeToAudioProgressNotifier()\n {\n ObjectDisposedException.ThrowIf(_disposed, this);\n\n UnsubscribeFromCurrentNotifier();\n\n _audioProgressNotifier.ChunkPlaybackStarted += HandleChunkStarted;\n _audioProgressNotifier.ChunkPlaybackEnded += HandleChunkEnded;\n _audioProgressNotifier.PlaybackProgress += HandleProgress;\n }\n\n private void UnsubscribeFromCurrentNotifier()\n {\n _audioProgressNotifier.ChunkPlaybackStarted -= HandleChunkStarted;\n _audioProgressNotifier.ChunkPlaybackEnded -= HandleChunkEnded;\n _audioProgressNotifier.PlaybackProgress -= HandleProgress;\n }\n\n public void Start(LAppModel model)\n {\n ObjectDisposedException.ThrowIf(_disposed, this);\n\n _model = model;\n\n ValidateModelAssets();\n\n _isStarted = true;\n ResetEmotionState(true);\n _logger.LogInformation(\"EmotionAnimationService started for model.\");\n }\n\n public void Stop()\n {\n _isStarted = false;\n ResetEmotionState(true);\n _logger.LogInformation(\"EmotionAnimationService stopped.\");\n }\n\n #endregion\n\n #region Update Logic\n\n public void Update(float deltaTime)\n {\n if ( deltaTime <= 0.0f || _disposed || !_isStarted || _model == null )\n {\n return;\n }\n\n _timeSinceExpressionSet += deltaTime;\n CheckExpressionTimeout();\n\n if ( _isPlaying )\n {\n ManageNeutralTalkingMotion();\n }\n // Optionally ensure neutral talking motion is stopped/faded out if needed when not playing,\n // though priority system might handle this.\n // If _neutralTalkingMotionEntry exists and isn't finished, it might need explicit stopping\n // depending on desired behavior when audio stops mid-talk.\n // For now, we assume idle animations (handled elsewhere) will override it.\n }\n\n private void CheckExpressionTimeout()\n {\n if ( _activeExpressionId == null || _activeExpressionId == NEUTRAL_EXPRESSION_ID ||\n !(_timeSinceExpressionSet >= EXPRESSION_HOLD_DURATION_SECONDS) )\n {\n return;\n }\n\n _logger.LogTrace(\"Expression '{ExpressionId}' hold time expired ({HoldDuration}s). Reverting to neutral.\",\n _activeExpressionId, EXPRESSION_HOLD_DURATION_SECONDS);\n\n ApplyNeutralExpression();\n }\n\n private void ManageNeutralTalkingMotion()\n {\n if ( _model == null )\n {\n return;\n }\n\n var isEmotionMotionActive = _currentEmotionMotionEntry is { Finished: false };\n\n if ( isEmotionMotionActive )\n {\n if ( _currentEmotionMotionEntry is { Finished: true } )\n {\n _currentEmotionMotionEntry = null;\n }\n\n return;\n }\n\n if ( _currentEmotionMotionEntry?.Finished ?? false )\n {\n _currentEmotionMotionEntry = null;\n }\n\n var shouldStartNeutralTalk = _availableMotionGroups.Contains(NEUTRAL_TALKING_MOTION_GROUP) &&\n (_neutralTalkingMotionEntry == null || _neutralTalkingMotionEntry.Finished);\n\n if ( !shouldStartNeutralTalk )\n {\n return;\n }\n\n _logger.LogTrace(\"Starting neutral talking motion (group: {MotionGroup}).\", NEUTRAL_TALKING_MOTION_GROUP);\n _neutralTalkingMotionEntry = _model.StartRandomMotion(NEUTRAL_TALKING_MOTION_GROUP, NEUTRAL_TALKING_MOTION_PRIORITY);\n if ( _neutralTalkingMotionEntry == null )\n {\n _logger.LogDebug(\"Could not start neutral talking motion for group '{MotionGroup}'.\", NEUTRAL_TALKING_MOTION_GROUP);\n }\n }\n\n private void UpdateEmotionBasedOnTime(float currentTime)\n {\n if ( _activeEmotions.Count == 0 || !_isPlaying )\n {\n return;\n }\n\n var targetEmotionIndex = -1;\n for ( var i = 0; i < _activeEmotions.Count; i++ )\n {\n if ( _activeEmotions[i].Timestamp <= currentTime )\n {\n targetEmotionIndex = i;\n }\n else\n {\n break;\n }\n }\n\n if ( targetEmotionIndex != -1 && targetEmotionIndex != _currentEmotionIndex )\n {\n _logger.LogTrace(\"Emotion change detected at T={CurrentTime:F3}. New index: {NewIndex}, Old index: {OldIndex}\",\n currentTime, targetEmotionIndex, _currentEmotionIndex);\n\n _currentEmotionIndex = targetEmotionIndex;\n var newEmotionEmoji = _activeEmotions[_currentEmotionIndex].Emotion;\n ApplyEmotion(newEmotionEmoji);\n }\n // If targetEmotionIndex is -1 (currentTime is before the first emotion),\n // or if the index hasn't changed, do nothing. The state persists.\n }\n\n private void ApplyEmotion(string? emotionEmoji)\n {\n if ( !_isStarted || _model == null )\n {\n return;\n }\n\n if ( emotionEmoji == _triggeredEmotionEmoji )\n {\n return;\n }\n\n _logger.LogDebug(\"Applying triggered emotion: {Emotion}\", emotionEmoji ?? \"Neutral (explicit)\");\n _triggeredEmotionEmoji = emotionEmoji;\n\n EmotionMapping? mapping = null;\n var foundMapping = emotionEmoji != null && EmotionMap.TryGetValue(emotionEmoji, out mapping);\n\n var targetExpressionId = foundMapping ? mapping?.ExpressionId : NEUTRAL_EXPRESSION_ID;\n SetExpression(targetExpressionId);\n\n if ( _currentEmotionMotionEntry?.Finished ?? false )\n {\n _currentEmotionMotionEntry = null;\n }\n\n var targetMotionGroup = foundMapping ? mapping?.MotionGroup : null;\n\n if ( !string.IsNullOrEmpty(targetMotionGroup) )\n {\n if ( _availableMotionGroups.Contains(targetMotionGroup) )\n {\n _logger.LogTrace(\"Attempting to start emotion motion from group: {MotionGroup} with priority {Priority}.\",\n targetMotionGroup, EMOTION_MOTION_PRIORITY);\n\n var newMotionEntry = _model.StartRandomMotion(targetMotionGroup, EMOTION_MOTION_PRIORITY);\n if ( newMotionEntry != null )\n {\n _currentEmotionMotionEntry = newMotionEntry;\n _neutralTalkingMotionEntry = null;\n _logger.LogTrace(\"Emotion motion started successfully.\");\n }\n else\n {\n _logger.LogWarning(\"Could not start motion for group '{MotionGroup}'. Is the group empty or definition invalid?\", targetMotionGroup);\n _currentEmotionMotionEntry = null;\n }\n }\n else\n {\n _logger.LogWarning(\"Motion group '{MotionGroup}' for emotion '{Emotion}' not found in the current model.\", targetMotionGroup, emotionEmoji);\n _currentEmotionMotionEntry = null;\n }\n }\n else\n {\n _currentEmotionMotionEntry = null;\n _logger.LogTrace(\"No specific motion group mapped for emotion '{Emotion}'.\", emotionEmoji ?? \"Neutral\");\n }\n }\n\n private void SetExpression(string? expressionId)\n {\n if ( !_isStarted || _model == null )\n {\n return;\n }\n\n var actualExpressionId = string.IsNullOrEmpty(expressionId) ? NEUTRAL_EXPRESSION_ID : expressionId;\n\n if ( string.IsNullOrEmpty(NEUTRAL_EXPRESSION_ID) && string.IsNullOrEmpty(expressionId) )\n {\n actualExpressionId = null;\n }\n\n if ( actualExpressionId == _activeExpressionId )\n {\n return;\n }\n\n var isTargetNeutral = string.IsNullOrEmpty(actualExpressionId) || actualExpressionId == NEUTRAL_EXPRESSION_ID;\n\n if ( isTargetNeutral )\n {\n ApplyNeutralExpression();\n }\n else if ( _availableExpressions.Contains(actualExpressionId!) )\n {\n _logger.LogTrace(\"Setting expression: {ExpressionId}\", actualExpressionId);\n _model.SetExpression(actualExpressionId!);\n _activeExpressionId = actualExpressionId;\n _timeSinceExpressionSet = 0.0f;\n }\n else\n {\n _logger.LogWarning(\"Expression '{ExpressionId}' not found in model. Applying neutral instead.\", actualExpressionId);\n ApplyNeutralExpression(); // Fallback to neutral\n }\n }\n\n private void ApplyNeutralExpression()\n {\n if ( !_isStarted || _model == null )\n {\n return;\n }\n\n var neutralToApply = string.IsNullOrEmpty(NEUTRAL_EXPRESSION_ID) ? null : NEUTRAL_EXPRESSION_ID;\n\n if ( _activeExpressionId != neutralToApply )\n {\n if ( neutralToApply != null || _activeExpressionId != null ) // Avoid logging null -> null\n {\n _logger.LogTrace(\"Setting neutral expression (was: {PreviousExpression}).\", _activeExpressionId ?? \"model default\");\n }\n\n if ( neutralToApply != null )\n {\n if ( _availableExpressions.Contains(neutralToApply) )\n {\n _model.SetExpression(neutralToApply);\n }\n else\n {\n _logger.LogError(\"Configured NEUTRAL_EXPRESSION_ID '{NeutralId}' is not available in the model, cannot apply.\", NEUTRAL_EXPRESSION_ID);\n neutralToApply = null;\n }\n }\n else\n {\n _logger.LogTrace(\"No neutral expression configured. Model may revert to default.\");\n }\n\n _activeExpressionId = neutralToApply;\n }\n\n _timeSinceExpressionSet = 0.0f;\n }\n\n #endregion\n\n #region Event Handlers\n\n private void HandleChunkStarted(object? sender, AudioChunkPlaybackStartedEvent e)\n {\n if ( !_isStarted || _model == null )\n {\n return;\n }\n\n _logger.LogTrace(\"Audio Chunk Playback Started for segment {SegmentId}.\", e.Chunk.Id);\n _isPlaying = true;\n ResetEmotionState(false);\n\n try\n {\n var emotions = e.Chunk.GetEmotions(_emotionService);\n\n if ( emotions.Any() )\n {\n _activeEmotions.AddRange(emotions.OrderBy(em => em.Timestamp));\n _logger.LogDebug(\"Loaded {Count} timed emotions for the segment.\", _activeEmotions.Count);\n\n UpdateEmotionBasedOnTime(0.0f);\n }\n else\n {\n _logger.LogDebug(\"No timed emotions found for segment {SegmentId}.\", e.Chunk.Id);\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error retrieving or processing emotions for audio segment {SegmentId}.\", e.Chunk.Id);\n }\n }\n\n private void HandleChunkEnded(object? sender, AudioChunkPlaybackEndedEvent e)\n {\n if ( !_isStarted )\n {\n return;\n }\n\n _logger.LogTrace(\"Audio Chunk Playback Ended.\");\n _isPlaying = false;\n _activeEmotions.Clear();\n _currentEmotionIndex = -1;\n\n // Expression timeout is handled by Update loop (CheckExpressionTimeout).\n // Motions will finish naturally or be overridden by idle animations (assumed).\n // Resetting _triggeredEmotionEmoji ensures the next chunk starts fresh.\n // Keep _activeExpressionId as is until timeout or next emotion.\n // _triggeredEmotionEmoji = null; // Reset last triggered emoji immediately? Or let timeout handle expression? Let timeout handle.\n }\n\n private void HandleProgress(object? sender, AudioPlaybackProgressEvent e)\n {\n if ( !_isStarted || !_isPlaying || _model == null )\n {\n return;\n }\n\n UpdateEmotionBasedOnTime((float)e.CurrentPlaybackTime.TotalSeconds);\n }\n\n #endregion\n\n #region State Management & Validation\n\n private void ResetEmotionState(bool forceNeutral)\n {\n _activeEmotions.Clear();\n _currentEmotionIndex = -1;\n\n if ( forceNeutral )\n {\n _currentEmotionMotionEntry = null;\n }\n\n if ( forceNeutral )\n {\n _neutralTalkingMotionEntry = null;\n }\n\n if ( forceNeutral )\n {\n _logger.LogTrace(\"Forcing neutral state on reset.\");\n ApplyNeutralExpression();\n _triggeredEmotionEmoji = null;\n }\n\n _logger.LogTrace(\"Emotion state reset (Active emotions cleared. Forced neutral: {ForceNeutral}).\", forceNeutral);\n }\n\n private void ValidateModelAssets()\n {\n if ( _model == null )\n {\n return;\n }\n\n _logger.LogDebug(\"Validating configured emotion mappings against model assets...\");\n\n _availableExpressions.Clear();\n _availableMotionGroups.Clear();\n\n var modelExpressions = new HashSet(_model.Expressions ?? Enumerable.Empty());\n _logger.LogTrace(\"Model contains {Count} expressions.\", modelExpressions.Count);\n\n var modelMotionGroups = new HashSet(StringComparer.OrdinalIgnoreCase);\n foreach ( var motionKey in _model.Motions ?? Enumerable.Empty() )\n {\n var groupName = LAppModel.GetMotionGroupName(motionKey); // Use static helper\n if ( !string.IsNullOrEmpty(groupName) )\n {\n modelMotionGroups.Add(groupName);\n }\n }\n\n _logger.LogTrace(\"Model contains {Count} unique motion groups (e.g., {Examples}).\",\n modelMotionGroups.Count, string.Join(\", \", modelMotionGroups.Take(5)) + (modelMotionGroups.Count > 5 ? \"...\" : \"\"));\n\n foreach ( var (emotion, mapping) in EmotionMap )\n {\n if ( !string.IsNullOrEmpty(mapping.ExpressionId) )\n {\n if ( modelExpressions.Contains(mapping.ExpressionId) )\n {\n _availableExpressions.Add(mapping.ExpressionId);\n }\n else\n {\n _logger.LogWarning(\"Validation: Expression '{ExpressionId}' (for emotion '{Emotion}') not found.\", mapping.ExpressionId, emotion);\n }\n }\n\n if ( string.IsNullOrEmpty(mapping.MotionGroup) )\n {\n continue;\n }\n\n if ( modelMotionGroups.Contains(mapping.MotionGroup) )\n {\n _availableMotionGroups.Add(mapping.MotionGroup);\n }\n else\n {\n _logger.LogWarning(\"Validation: Motion group '{MotionGroup}' (for emotion '{Emotion}') not found.\", mapping.MotionGroup, emotion);\n }\n }\n\n if ( !string.IsNullOrEmpty(NEUTRAL_EXPRESSION_ID) )\n {\n if ( modelExpressions.Contains(NEUTRAL_EXPRESSION_ID) )\n {\n _availableExpressions.Add(NEUTRAL_EXPRESSION_ID);\n }\n else\n {\n _logger.LogWarning(\"Configured NEUTRAL_EXPRESSION_ID ('{NeutralId}') not found!\", NEUTRAL_EXPRESSION_ID);\n }\n }\n\n if ( !string.IsNullOrEmpty(NEUTRAL_TALKING_MOTION_GROUP) )\n {\n if ( modelMotionGroups.Contains(NEUTRAL_TALKING_MOTION_GROUP) )\n {\n _availableMotionGroups.Add(NEUTRAL_TALKING_MOTION_GROUP);\n }\n else\n {\n _logger.LogWarning(\"Configured NEUTRAL_TALKING_MOTION_GROUP ('{Group}') not found.\", NEUTRAL_TALKING_MOTION_GROUP);\n }\n }\n\n _logger.LogDebug(\"Validation complete. Usable Expressions: {ExprCount}, Usable Motion Groups: {MotionCount}\",\n _availableExpressions.Count, _availableMotionGroups.Count);\n }\n\n #endregion\n\n #region IDisposable Implementation\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( !_disposed )\n {\n if ( disposing )\n {\n _logger.LogDebug(\"Disposing EmotionAnimationService...\");\n Stop();\n UnsubscribeFromCurrentNotifier();\n _activeEmotions.Clear();\n _availableExpressions.Clear();\n _availableMotionGroups.Clear();\n _model = null;\n _logger.LogInformation(\"EmotionAnimationService disposed.\");\n }\n\n _disposed = true;\n }\n }\n\n ~EmotionAnimationService() { Dispose(false); }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismModelMatrix.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// モデル座標設定用の4x4行列クラス。\n/// \npublic record CubismModelMatrix : CubismMatrix44\n{\n public const string KeyWidth = \"width\";\n\n public const string KeyHeight = \"height\";\n\n public const string KeyX = \"x\";\n\n public const string KeyY = \"y\";\n\n public const string KeyCenterX = \"center_x\";\n\n public const string KeyCenterY = \"center_y\";\n\n public const string KeyTop = \"top\";\n\n public const string KeyBottom = \"bottom\";\n\n public const string KeyLeft = \"left\";\n\n public const string KeyRight = \"right\";\n\n /// \n /// 縦幅\n /// \n private readonly float _height;\n\n /// \n /// 横幅\n /// \n private readonly float _width;\n\n public CubismModelMatrix(float w, float h)\n {\n _width = w;\n _height = h;\n\n SetHeight(2.0f);\n }\n\n /// \n /// 横幅を設定する。\n /// \n /// 横幅\n public void SetWidth(float w)\n {\n var scaleX = w / _width;\n var scaleY = scaleX;\n Scale(scaleX, scaleY);\n }\n\n /// \n /// 縦幅を設定する。\n /// \n /// 縦幅\n public void SetHeight(float h)\n {\n var scaleX = h / _height;\n var scaleY = scaleX;\n Scale(scaleX, scaleY);\n }\n\n /// \n /// 位置を設定する。\n /// \n /// X軸の位置\n /// Y軸の位置\n public void SetPosition(float x, float y) { Translate(x, y); }\n\n /// \n /// 中心位置を設定する。\n /// \n /// X軸の中心位置\n /// Y軸の中心位置\n public void SetCenterPosition(float x, float y)\n {\n CenterX(x);\n CenterY(y);\n }\n\n /// \n /// 上辺の位置を設定する。\n /// \n /// 上辺のY軸位置\n public void Top(float y) { SetY(y); }\n\n /// \n /// 下辺の位置を設定する。\n /// \n /// 下辺のY軸位置\n public void Bottom(float y)\n {\n var h = _height * GetScaleY();\n TranslateY(y - h);\n }\n\n /// \n /// 左辺の位置を設定する。\n /// \n /// 左辺のX軸位置\n public void Left(float x) { SetX(x); }\n\n /// \n /// 右辺の位置を設定する。\n /// \n /// 右辺のX軸位置\n public void Right(float x)\n {\n var w = _width * GetScaleX();\n TranslateX(x - w);\n }\n\n /// \n /// X軸の中心位置を設定する。\n /// \n /// X軸の中心位置\n public void CenterX(float x)\n {\n var w = _width * GetScaleX();\n TranslateX(x - w / 2.0f);\n }\n\n /// \n /// X軸の位置を設定する。\n /// \n /// X軸の位置\n public void SetX(float x) { TranslateX(x); }\n\n /// \n /// Y軸の中心位置を設定する。\n /// \n /// Y軸の中心位置\n public void CenterY(float y)\n {\n var h = _height * GetScaleY();\n TranslateY(y - h / 2.0f);\n }\n\n /// \n /// Y軸の位置を設定する。\n /// \n /// Y軸の位置\n public void SetY(float y) { TranslateY(y); }\n\n /// \n /// レイアウト情報から位置を設定する。\n /// \n /// レイアウト情報\n public void SetupFromLayout(Dictionary layout)\n {\n foreach ( var item in layout )\n {\n if ( item.Key == KeyWidth )\n {\n SetWidth(item.Value);\n }\n else if ( item.Key == KeyHeight )\n {\n SetHeight(item.Value);\n }\n }\n\n foreach ( var item in layout )\n {\n if ( item.Key == KeyX )\n {\n SetX(item.Value);\n }\n else if ( item.Key == KeyY )\n {\n SetY(item.Value);\n }\n else if ( item.Key == KeyCenterX )\n {\n CenterX(item.Value);\n }\n else if ( item.Key == KeyCenterY )\n {\n CenterY(item.Value);\n }\n else if ( item.Key == KeyTop )\n {\n Top(item.Value);\n }\n else if ( item.Key == KeyBottom )\n {\n Bottom(item.Value);\n }\n else if ( item.Key == KeyLeft )\n {\n Left(item.Value);\n }\n else if ( item.Key == KeyRight )\n {\n Right(item.Value);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/CubismFramework.cs", "using PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Id;\n\nnamespace PersonaEngine.Lib.Live2D.Framework;\n\n/// \n/// Live2D Cubism Original Workflow SDKのエントリポイント\n/// 利用開始時はCubismFramework.Initialize()を呼び、CubismFramework.Dispose()で終了する。\n/// \npublic static class CubismFramework\n{\n /// \n /// メッシュ頂点のオフセット値\n /// \n public const int VertexOffset = 0;\n\n /// \n /// メッシュ頂点のステップ値\n /// \n public const int VertexStep = 2;\n\n private static ICubismAllocator? s_allocator;\n\n private static Option? s_option;\n\n /// \n /// IDマネージャのインスタンスを取得する。\n /// \n public static CubismIdManager CubismIdManager { get; private set; } = new();\n\n public static bool IsInitialized { get; private set; }\n\n public static bool IsStarted { get; private set; }\n\n /// \n /// Cubism FrameworkのAPIを使用可能にする。\n /// APIを実行する前に必ずこの関数を実行すること。\n /// 引数に必ずメモリアロケータを渡してください。\n /// 一度準備が完了して以降は、再び実行しても内部処理がスキップされます。\n /// \n /// ICubismAllocatorクラスのインスタンス\n /// Optionクラスのインスタンス\n /// 準備処理が完了したらtrueが返ります。\n public static bool StartUp(ICubismAllocator allocator, Option option)\n {\n if ( IsStarted )\n {\n CubismLog.Info(\"[Live2D SDK]CubismFramework.StartUp() is already done.\");\n\n return IsStarted;\n }\n\n s_option = option;\n if ( s_option != null )\n {\n CubismCore.SetLogFunction(s_option.LogFunction);\n }\n\n if ( allocator == null )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.StartUp() failed, need allocator instance.\");\n IsStarted = false;\n }\n else\n {\n s_allocator = allocator;\n IsStarted = true;\n }\n\n //Live2D Cubism Coreバージョン情報を表示\n if ( IsStarted )\n {\n var version = CubismCore.GetVersion();\n\n var major = (version & 0xFF000000) >> 24;\n var minor = (version & 0x00FF0000) >> 16;\n var patch = version & 0x0000FFFF;\n var versionNumber = version;\n\n CubismLog.Info($\"[Live2D SDK]Cubism Core version: {major:#0}.{minor:0}.{patch:0000} ({versionNumber})\");\n }\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.StartUp() is complete.\");\n\n return IsStarted;\n }\n\n /// \n /// StartUp()で初期化したCubismFrameworkの各パラメータをクリアします。\n /// Dispose()したCubismFrameworkを再利用する際に利用してください。\n /// \n public static void CleanUp()\n {\n IsStarted = false;\n IsInitialized = false;\n }\n\n /// \n /// Cubism Framework内のリソースを初期化してモデルを表示可能な状態にします。\n /// 再度Initialize()するには先にDispose()を実行する必要があります。\n /// \n public static void Initialize()\n {\n if ( !IsStarted )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework is not started.\");\n\n return;\n }\n\n // --- s_isInitializedによる連続初期化ガード ---\n // 連続してリソース確保が行われないようにする。\n // 再度Initialize()するには先にDispose()を実行する必要がある。\n if ( IsInitialized )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.Initialize() skipped, already initialized.\");\n\n return;\n }\n\n IsInitialized = true;\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.Initialize() is complete.\");\n }\n\n /// \n /// Cubism Framework内の全てのリソースを解放します。\n /// ただし、外部で確保されたリソースについては解放しません。\n /// 外部で適切に破棄する必要があります。\n /// \n public static void Dispose()\n {\n if ( !IsStarted )\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework is not started.\");\n\n return;\n }\n\n // --- s_isInitializedによる未初期化解放ガード ---\n // Dispose()するには先にInitialize()を実行する必要がある。\n if ( !IsInitialized ) // false...リソース未確保の場合\n {\n CubismLog.Warning(\"[Live2D SDK]CubismFramework.Dispose() skipped, not initialized.\");\n\n return;\n }\n\n IsInitialized = false;\n\n CubismLog.Info(\"[Live2D SDK]CubismFramework.Dispose() is complete.\");\n }\n\n /// \n /// Core APIにバインドしたログ関数を実行する\n /// \n /// ログメッセージ\n public static void CoreLogFunction(string data) { CubismCore.GetLogFunction()?.Invoke(data); }\n\n /// \n /// 現在のログ出力レベル設定の値を返す。\n /// \n /// 現在のログ出力レベル設定の値\n public static LogLevel GetLoggingLevel()\n {\n if ( s_option != null )\n {\n return s_option.LoggingLevel;\n }\n\n return LogLevel.Off;\n }\n\n public static IntPtr Allocate(int size) { return s_allocator!.Allocate(size); }\n\n public static IntPtr AllocateAligned(int size, int alignment) { return s_allocator!.AllocateAligned(size, alignment); }\n\n public static void Deallocate(IntPtr address) { s_allocator!.Deallocate(address); }\n\n public static void DeallocateAligned(IntPtr address) { s_allocator!.DeallocateAligned(address); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppTextureManager.cs", "using System.Runtime.InteropServices;\n\nusing SixLabors.ImageSharp;\nusing SixLabors.ImageSharp.PixelFormats;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// 画像読み込み、管理を行うクラス。\n/// \npublic class LAppTextureManager(LAppDelegate lapp)\n{\n private readonly List _textures = [];\n\n /// \n /// 画像読み込み\n /// \n /// 読み込む画像ファイルパス名\n /// 画像情報。読み込み失敗時はNULLを返す\n public TextureInfo CreateTextureFromPngFile(string fileName)\n {\n //search loaded texture already.\n var item = _textures.FirstOrDefault(a => a.FileName == fileName);\n if ( item != null )\n {\n return item;\n }\n\n // Using SixLabors.ImageSharp to load the image\n using var image = Image.Load(fileName);\n var GL = lapp.GL;\n\n // OpenGL用のテクスチャを生成する\n var textureId = GL.GenTexture();\n GL.BindTexture(GL.GL_TEXTURE_2D, textureId);\n\n // Create a byte array to hold image data\n var pixelData = new byte[4 * image.Width * image.Height]; // 4 bytes per pixel (RGBA)\n\n // Access the pixel data\n image.ProcessPixelRows(accessor =>\n {\n // For each row\n for ( var y = 0; y < accessor.Height; y++ )\n {\n // Get the pixel row span\n var row = accessor.GetRowSpan(y);\n\n // For each pixel in the row\n for ( var x = 0; x < row.Length; x++ )\n {\n // Calculate the position in our byte array\n var arrayPos = (y * accessor.Width + x) * 4;\n\n // Copy RGBA components\n pixelData[arrayPos + 0] = row[x].R;\n pixelData[arrayPos + 1] = row[x].G;\n pixelData[arrayPos + 2] = row[x].B;\n pixelData[arrayPos + 3] = row[x].A;\n }\n }\n });\n\n // Pin the byte array in memory so we can pass a pointer to OpenGL\n var pinnedArray = GCHandle.Alloc(pixelData, GCHandleType.Pinned);\n try\n {\n // Get the address of the first byte in the array\n var pointer = pinnedArray.AddrOfPinnedObject();\n\n // Pass the pointer to OpenGL\n GL.TexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, image.Width, image.Height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pointer);\n GL.GenerateMipmap(GL.GL_TEXTURE_2D);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);\n }\n finally\n {\n // Free the pinned array\n pinnedArray.Free();\n }\n\n GL.BindTexture(GL.GL_TEXTURE_2D, 0);\n\n var info = new TextureInfo { FileName = fileName, Width = image.Width, Height = image.Height, ID = textureId };\n\n _textures.Add(info);\n\n return info;\n }\n\n /// \n /// 指定したテクスチャIDの画像を解放する\n /// \n /// 解放するテクスチャID\n public void ReleaseTexture(int textureId)\n {\n foreach ( var item in _textures )\n {\n if ( item.ID == textureId )\n {\n _textures.Remove(item);\n\n break;\n }\n }\n }\n\n /// \n /// テクスチャIDからテクスチャ情報を得る\n /// \n /// 取得したいテクスチャID\n /// テクスチャが存在していればTextureInfoが返る\n public TextureInfo? GetTextureInfoById(int textureId) { return _textures.FirstOrDefault(a => a.ID == textureId); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Motion/CubismMotionInternal.cs", "using PersonaEngine.Lib.Live2D.Framework.Model;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Motion;\n\n/// \n/// モーション再生終了コールバック関数定義\n/// \npublic delegate void FinishedMotionCallback(CubismModel model, ACubismMotion self);\n\n/// \n/// イベントのコールバックに登録できる関数の型情報\n/// \n/// 発火したイベントの文字列データ\n/// コールバックに返される登録時に指定されたデータ\npublic delegate void CubismMotionEventFunction(CubismUserModel? customData, string eventValue);\n\n/// \n/// モーションカーブのセグメントの評価関数。\n/// \n/// モーションカーブの制御点リスト\n/// 評価する時間[秒]\npublic delegate float csmMotionSegmentEvaluationFunction(CubismMotionPoint[] points, int start, float time);\n\n/// \n/// モーションの優先度定数\n/// \npublic enum MotionPriority\n{\n PriorityNone = 0,\n\n PriorityIdle = 1,\n\n PriorityLow = 2,\n \n PriorityNormal = 3,\n\n PriorityForce = 4\n}\n\n/// \n/// 表情パラメータ値の計算方式\n/// \npublic enum ExpressionBlendType\n{\n /// \n /// 加算\n /// \n Add = 0,\n\n /// \n /// 乗算\n /// \n Multiply = 1,\n\n /// \n /// 上書き\n /// \n Overwrite = 2\n}\n\n/// \n/// 表情のパラメータ情報の構造体。\n/// \npublic record ExpressionParameter\n{\n /// \n /// パラメータID\n /// \n public required string ParameterId { get; set; }\n\n /// \n /// パラメータの演算種類\n /// \n public ExpressionBlendType BlendType { get; set; }\n\n /// \n /// 値\n /// \n public float Value { get; set; }\n}\n\n/// \n/// モーションカーブの種類。\n/// \npublic enum CubismMotionCurveTarget\n{\n /// \n /// モデルに対して\n /// \n Model,\n\n /// \n /// パラメータに対して\n /// \n Parameter,\n\n /// \n /// パーツの不透明度に対して\n /// \n PartOpacity\n}\n\n/// \n/// モーションカーブのセグメントの種類。\n/// \npublic enum CubismMotionSegmentType\n{\n /// \n /// リニア\n /// \n Linear = 0,\n\n /// \n /// ベジェ曲線\n /// \n Bezier = 1,\n\n /// \n /// ステップ\n /// \n Stepped = 2,\n\n /// \n /// インバースステップ\n /// \n InverseStepped = 3\n}\n\n/// \n/// モーションカーブの制御点。\n/// \npublic struct CubismMotionPoint\n{\n /// \n /// 時間[秒]\n /// \n public float Time;\n\n /// \n /// 値\n /// \n public float Value;\n}\n\n/// \n/// モーションカーブのセグメント。\n/// \npublic record CubismMotionSegment\n{\n /// \n /// 最初のセグメントへのインデックス\n /// \n public int BasePointIndex;\n\n /// \n /// 使用する評価関数\n /// \n public csmMotionSegmentEvaluationFunction Evaluate;\n\n /// \n /// セグメントの種類\n /// \n public CubismMotionSegmentType SegmentType;\n}\n\n/// \n/// モーションカーブ。\n/// \npublic record CubismMotionCurve\n{\n /// \n /// 最初のセグメントのインデックス\n /// \n public int BaseSegmentIndex;\n\n /// \n /// フェードインにかかる時間[秒]\n /// \n public float FadeInTime;\n\n /// \n /// フェードアウトにかかる時間[秒]\n /// \n public float FadeOutTime;\n\n /// \n /// カーブのID\n /// \n public string Id;\n\n /// \n /// セグメントの個数\n /// \n public int SegmentCount;\n\n /// \n /// カーブの種類\n /// \n public CubismMotionCurveTarget Type;\n}\n\n/// \n/// イベント。\n/// \npublic record CubismMotionEvent\n{\n public float FireTime;\n\n public string Value;\n}\n\n/// \n/// モーションデータ。\n/// \npublic record CubismMotionData\n{\n /// \n /// カーブの個数\n /// \n public int CurveCount;\n\n /// \n /// カーブのリスト\n /// \n public CubismMotionCurve[] Curves;\n\n /// \n /// モーションの長さ[秒]\n /// \n public float Duration;\n\n /// \n /// UserDataの個数\n /// \n public int EventCount;\n\n /// \n /// イベントのリスト\n /// \n public CubismMotionEvent[] Events;\n\n /// \n /// フレームレート\n /// \n public float Fps;\n\n /// \n /// ループするかどうか\n /// \n public bool Loop;\n\n /// \n /// ポイントのリスト\n /// \n public CubismMotionPoint[] Points;\n\n /// \n /// セグメントのリスト\n /// \n public CubismMotionSegment[] Segments;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/LipSync/VBridgerLipSyncService.cs", "using Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.Live2D.App;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.LipSync;\n\n/// \n/// LipSync service for VBridger parameter conventions.\n/// \npublic sealed class VBridgerLipSyncService : ILive2DAnimationService\n{\n public VBridgerLipSyncService(ILogger logger, IAudioProgressNotifier audioProgressNotifier)\n {\n _logger = logger;\n _audioProgressNotifier = audioProgressNotifier;\n _phonemeMap = InitializeMisakiPhonemeMap();\n\n SubscribeToAudioProgressNotifier();\n }\n\n private void InitializeCurrentParameters()\n {\n if ( _model == null )\n {\n return;\n }\n\n var cubismModel = _model.Model;\n\n // Fetch initial values from the model\n _currentParameterValues[ParamMouthOpenY] = cubismModel.GetParameterValue(ParamMouthOpenY);\n _currentParameterValues[ParamJawOpen] = cubismModel.GetParameterValue(ParamJawOpen);\n _currentParameterValues[ParamMouthForm] = cubismModel.GetParameterValue(ParamMouthForm);\n _currentParameterValues[ParamMouthShrug] = cubismModel.GetParameterValue(ParamMouthShrug);\n _currentParameterValues[ParamMouthFunnel] = cubismModel.GetParameterValue(ParamMouthFunnel);\n _currentParameterValues[ParamMouthPuckerWiden] = cubismModel.GetParameterValue(ParamMouthPuckerWiden);\n _currentParameterValues[ParamMouthPressLipOpen] = cubismModel.GetParameterValue(ParamMouthPressLipOpen);\n _currentParameterValues[ParamMouthX] = cubismModel.GetParameterValue(ParamMouthX);\n _currentParameterValues[ParamCheekPuffC] = 0f;\n }\n\n #region Configuration Constants\n\n private const float SMOOTHING_FACTOR = 35.0f; // How quickly parameters move towards target (higher = faster)\n\n private const float NEUTRAL_RETURN_FACTOR = 15.0f; // How quickly parameters return to neutral when idle\n\n private const float CHEEK_PUFF_DECAY_FACTOR = 80.0f; // How quickly CheekPuff returns to 0\n\n private const float NEUTRAL_THRESHOLD = 0.02f; // Threshold for considering a value as neutral\n\n #endregion\n\n #region Parameter Names\n\n private static readonly string ParamMouthOpenY = \"ParamMouthOpenY\";\n\n private static readonly string ParamJawOpen = \"ParamJawOpen\";\n\n private static readonly string ParamMouthForm = \"ParamMouthForm\";\n\n private static readonly string ParamMouthShrug = \"ParamMouthShrug\";\n\n private static readonly string ParamMouthFunnel = \"ParamMouthFunnel\";\n\n private static readonly string ParamMouthPuckerWiden = \"ParamMouthPuckerWiden\";\n\n private static readonly string ParamMouthPressLipOpen = \"ParamMouthPressLipOpen\";\n\n private static readonly string ParamMouthX = \"ParamMouthX\";\n\n private static readonly string ParamCheekPuffC = \"ParamCheekPuffC\";\n\n #endregion\n\n #region Dependencies and State\n\n private LAppModel? _model;\n\n private readonly IAudioProgressNotifier _audioProgressNotifier;\n\n private readonly List _activePhonemes = new();\n\n private int _currentPhonemeIndex = -1;\n\n private bool _isPlaying = false;\n\n private bool _isStarted = false;\n\n private bool _disposed = false;\n\n private PhonemePose _currentTargetPose = PhonemePose.Neutral;\n\n private PhonemePose _nextTargetPose = PhonemePose.Neutral;\n\n private float _interpolationT = 0f;\n\n private readonly Dictionary _currentParameterValues = new();\n\n private readonly Dictionary _phonemeMap;\n\n private readonly HashSet _phonemeShapeIgnoreChars = ['ˈ', 'ˌ', 'ː']; // Ignore stress/length marks\n\n private readonly ILogger _logger;\n\n #endregion\n\n #region ILipSyncService Implementation\n\n private void SubscribeToAudioProgressNotifier()\n {\n ObjectDisposedException.ThrowIf(_disposed, this);\n\n UnsubscribeFromCurrentNotifier();\n\n _audioProgressNotifier.ChunkPlaybackStarted += HandleChunkStarted;\n _audioProgressNotifier.ChunkPlaybackEnded += HandleChunkEnded;\n _audioProgressNotifier.PlaybackProgress += HandleProgress;\n }\n\n private void UnsubscribeFromCurrentNotifier()\n {\n _audioProgressNotifier.ChunkPlaybackStarted -= HandleChunkStarted;\n _audioProgressNotifier.ChunkPlaybackEnded -= HandleChunkEnded;\n _audioProgressNotifier.PlaybackProgress -= HandleProgress;\n\n ResetState();\n }\n\n public void Start(LAppModel model)\n {\n ObjectDisposedException.ThrowIf(_disposed, this);\n\n _model = model;\n\n InitializeCurrentParameters();\n\n _isStarted = true;\n\n _logger.LogInformation(\"Started lip syncing.\");\n }\n\n public void Stop()\n {\n _isStarted = false;\n ResetState();\n _logger.LogInformation(\"Stopped lip syncing.\");\n }\n\n #endregion\n\n #region Update Logic\n\n public void Update(float deltaTime)\n {\n if ( deltaTime <= 0.0f || _disposed || !_isStarted || _model == null )\n {\n return;\n }\n\n if ( !_isPlaying )\n {\n SmoothParametersToNeutral(deltaTime);\n\n return;\n }\n\n var easedT = EaseInOutQuad(_interpolationT);\n var frameTargetPose = PhonemePose.Lerp(_currentTargetPose, _nextTargetPose, easedT);\n SmoothParametersToTarget(frameTargetPose, deltaTime);\n ApplySmoothedParameters();\n }\n\n private void UpdateTargetPoses(float currentTime)\n {\n if ( _model == null || !_isPlaying || _activePhonemes.Count == 0 )\n {\n if ( _currentTargetPose != PhonemePose.Neutral || _nextTargetPose != PhonemePose.Neutral )\n {\n _currentTargetPose = GetPoseFromCurrentValues();\n _nextTargetPose = PhonemePose.Neutral;\n _interpolationT = 0f;\n _logger.LogTrace(\"Targeting Neutral Pose.\");\n }\n\n _currentPhonemeIndex = -1;\n\n return;\n }\n\n var foundIndex = FindPhonemeIndexAtTime(currentTime);\n\n if ( foundIndex != -1 )\n {\n if ( foundIndex != _currentPhonemeIndex )\n {\n _logger.LogTrace(\"Phoneme changed: {PhonemeIndex} -> {FoundIndex} ({Phoneme}) at T={CurrentTime:F3}\", _currentPhonemeIndex, foundIndex, _activePhonemes[foundIndex].Phoneme, currentTime);\n\n if ( _currentPhonemeIndex == -1 )\n {\n _currentTargetPose = GetPoseFromCurrentValues();\n }\n else\n {\n _currentTargetPose = GetPoseForPhoneme(_activePhonemes[_currentPhonemeIndex].Phoneme);\n }\n\n _nextTargetPose = GetPoseForPhoneme(_activePhonemes[foundIndex].Phoneme);\n _currentPhonemeIndex = foundIndex;\n }\n\n var currentPh = _activePhonemes[_currentPhonemeIndex];\n var duration = currentPh.EndTime - currentPh.StartTime;\n _interpolationT = duration > 0.001\n ? (float)Math.Clamp((currentTime - currentPh.StartTime) / duration, 0.0, 1.0)\n : 1.0f;\n }\n else\n {\n if ( _currentTargetPose != PhonemePose.Neutral || _nextTargetPose != PhonemePose.Neutral )\n {\n _currentTargetPose = GetPoseFromCurrentValues();\n _nextTargetPose = PhonemePose.Neutral;\n _interpolationT = 0f;\n _logger.LogTrace(\"Targeting Neutral Pose (Gap/End).\");\n }\n\n if ( _activePhonemes.Count > 0 &&\n (currentTime < _activePhonemes.First().StartTime - 0.1 ||\n currentTime > _activePhonemes.Last().EndTime + 0.1) )\n {\n _currentPhonemeIndex = -1;\n }\n }\n }\n\n private int FindPhonemeIndexAtTime(float currentTime)\n {\n if ( _currentPhonemeIndex >= 0 && _currentPhonemeIndex < _activePhonemes.Count )\n {\n var ph = _activePhonemes[_currentPhonemeIndex];\n if ( currentTime >= ph.StartTime && currentTime < ph.EndTime + 0.001 )\n {\n return _currentPhonemeIndex;\n }\n }\n\n var searchStartIndex = Math.Max(0, _currentPhonemeIndex - 1);\n for ( var i = searchStartIndex; i < _activePhonemes.Count; i++ )\n {\n var ph = _activePhonemes[i];\n if ( currentTime >= ph.StartTime && currentTime < ph.EndTime + 0.001 )\n {\n return i;\n }\n }\n\n if ( _activePhonemes.Count > 0 )\n {\n if ( currentTime < _activePhonemes[0].StartTime )\n {\n return -1;\n }\n\n if ( Math.Abs(currentTime - _activePhonemes.Last().EndTime) < 0.01 )\n {\n return _activePhonemes.Count - 1;\n }\n }\n\n return -1;\n }\n\n private PhonemePose GetPoseFromCurrentValues()\n {\n return new PhonemePose(\n _currentParameterValues[ParamMouthOpenY],\n _currentParameterValues[ParamJawOpen],\n _currentParameterValues[ParamMouthForm],\n _currentParameterValues[ParamMouthShrug],\n _currentParameterValues[ParamMouthFunnel],\n _currentParameterValues[ParamMouthPuckerWiden],\n _currentParameterValues[ParamMouthPressLipOpen],\n _currentParameterValues[ParamMouthX],\n _currentParameterValues[ParamCheekPuffC]\n );\n }\n\n #endregion\n\n #region Parameter Smoothing\n\n private void SmoothParametersToTarget(PhonemePose targetPose, float deltaTime)\n {\n var smoothFactor = SMOOTHING_FACTOR * deltaTime;\n\n _currentParameterValues[ParamMouthOpenY] = Lerp(_currentParameterValues[ParamMouthOpenY], targetPose.MouthOpenY, smoothFactor);\n _currentParameterValues[ParamJawOpen] = Lerp(_currentParameterValues[ParamJawOpen], targetPose.JawOpen, smoothFactor);\n _currentParameterValues[ParamMouthForm] = Lerp(_currentParameterValues[ParamMouthForm], targetPose.MouthForm, smoothFactor);\n _currentParameterValues[ParamMouthShrug] = Lerp(_currentParameterValues[ParamMouthShrug], targetPose.MouthShrug, smoothFactor);\n _currentParameterValues[ParamMouthFunnel] = Lerp(_currentParameterValues[ParamMouthFunnel], targetPose.MouthFunnel, smoothFactor);\n _currentParameterValues[ParamMouthPuckerWiden] = Lerp(_currentParameterValues[ParamMouthPuckerWiden], targetPose.MouthPuckerWiden, smoothFactor);\n _currentParameterValues[ParamMouthPressLipOpen] = Lerp(_currentParameterValues[ParamMouthPressLipOpen], targetPose.MouthPressLipOpen, smoothFactor);\n _currentParameterValues[ParamMouthX] = Lerp(_currentParameterValues[ParamMouthX], targetPose.MouthX, smoothFactor);\n\n if ( targetPose.CheekPuffC > NEUTRAL_THRESHOLD )\n {\n _currentParameterValues[ParamCheekPuffC] = Lerp(_currentParameterValues[ParamCheekPuffC], targetPose.CheekPuffC, smoothFactor);\n }\n else\n {\n var decayFactor = CHEEK_PUFF_DECAY_FACTOR * deltaTime;\n _currentParameterValues[ParamCheekPuffC] = Lerp(_currentParameterValues[ParamCheekPuffC], 0.0f, decayFactor);\n }\n }\n\n private void SmoothParametersToNeutral(float deltaTime)\n {\n var smoothFactor = NEUTRAL_RETURN_FACTOR * deltaTime;\n var neutral = PhonemePose.Neutral;\n\n _currentParameterValues[ParamMouthOpenY] = Lerp(_currentParameterValues[ParamMouthOpenY], neutral.MouthOpenY, smoothFactor);\n _currentParameterValues[ParamJawOpen] = Lerp(_currentParameterValues[ParamJawOpen], neutral.JawOpen, smoothFactor);\n _currentParameterValues[ParamMouthForm] = Lerp(_currentParameterValues[ParamMouthForm], neutral.MouthForm, smoothFactor);\n _currentParameterValues[ParamMouthShrug] = Lerp(_currentParameterValues[ParamMouthShrug], neutral.MouthShrug, smoothFactor);\n _currentParameterValues[ParamMouthFunnel] = Lerp(_currentParameterValues[ParamMouthFunnel], neutral.MouthFunnel, smoothFactor);\n _currentParameterValues[ParamMouthPuckerWiden] = Lerp(_currentParameterValues[ParamMouthPuckerWiden], neutral.MouthPuckerWiden, smoothFactor);\n _currentParameterValues[ParamMouthPressLipOpen] = Lerp(_currentParameterValues[ParamMouthPressLipOpen], neutral.MouthPressLipOpen, smoothFactor);\n _currentParameterValues[ParamMouthX] = Lerp(_currentParameterValues[ParamMouthX], neutral.MouthX, smoothFactor);\n\n var decayFactor = CHEEK_PUFF_DECAY_FACTOR * deltaTime;\n _currentParameterValues[ParamCheekPuffC] = Lerp(_currentParameterValues[ParamCheekPuffC], 0.0f, decayFactor);\n\n ApplySmoothedParameters();\n }\n\n private bool IsApproximatelyNeutral()\n {\n var neutral = PhonemePose.Neutral;\n\n return Math.Abs(_currentParameterValues[ParamMouthOpenY] - neutral.MouthOpenY) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamJawOpen] - neutral.JawOpen) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthForm] - neutral.MouthForm) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthShrug] - neutral.MouthShrug) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthFunnel] - neutral.MouthFunnel) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthPuckerWiden] - neutral.MouthPuckerWiden) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthPressLipOpen] - neutral.MouthPressLipOpen) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamMouthX] - neutral.MouthX) < NEUTRAL_THRESHOLD &&\n Math.Abs(_currentParameterValues[ParamCheekPuffC] - neutral.CheekPuffC) < NEUTRAL_THRESHOLD;\n }\n\n private void ApplySmoothedParameters()\n {\n if ( _model == null )\n {\n _logger.LogWarning(\"Attempted to apply parameters but model is null.\");\n\n return;\n }\n\n try\n {\n var cubismModel = _model.Model;\n cubismModel.SetParameterValue(ParamMouthOpenY, _currentParameterValues[ParamMouthOpenY]);\n cubismModel.SetParameterValue(ParamJawOpen, _currentParameterValues[ParamJawOpen]);\n cubismModel.SetParameterValue(ParamMouthForm, _currentParameterValues[ParamMouthForm]);\n cubismModel.SetParameterValue(ParamMouthShrug, _currentParameterValues[ParamMouthShrug]);\n cubismModel.SetParameterValue(ParamMouthFunnel, _currentParameterValues[ParamMouthFunnel]);\n cubismModel.SetParameterValue(ParamMouthPuckerWiden, _currentParameterValues[ParamMouthPuckerWiden]);\n cubismModel.SetParameterValue(ParamMouthPressLipOpen, _currentParameterValues[ParamMouthPressLipOpen]);\n cubismModel.SetParameterValue(ParamMouthX, _currentParameterValues[ParamMouthX]);\n cubismModel.SetParameterValue(ParamCheekPuffC, _currentParameterValues[ParamCheekPuffC]);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error applying Live2D parameters\");\n }\n }\n\n #endregion\n\n #region Event Handlers and State Management\n\n private void HandleChunkStarted(object? sender, AudioChunkPlaybackStartedEvent e)\n {\n if ( !_isStarted )\n {\n return;\n }\n\n _logger.LogTrace(\"Audio Chunk Playback Started.\");\n ProcessAudioSegment(e.Chunk);\n _isPlaying = true;\n _currentPhonemeIndex = -1;\n\n var initialTime = _activePhonemes.Count != 0 ? (float)_activePhonemes.First().StartTime : 0f;\n UpdateTargetPoses(initialTime);\n }\n\n private void HandleChunkEnded(object? sender, AudioChunkPlaybackEndedEvent e)\n {\n if ( !_isStarted )\n {\n return;\n }\n\n _logger.LogTrace(\"Audio Chunk Playback Ended.\");\n _isPlaying = false;\n }\n\n private void HandleProgress(object? sender, AudioPlaybackProgressEvent e)\n {\n if ( !_isStarted || !_isPlaying )\n {\n return;\n }\n\n UpdateTargetPoses((float)e.CurrentPlaybackTime.TotalSeconds);\n }\n\n private void ResetState()\n {\n _activePhonemes.Clear();\n _currentPhonemeIndex = -1;\n _isPlaying = false;\n _currentTargetPose = PhonemePose.Neutral;\n _nextTargetPose = PhonemePose.Neutral;\n _interpolationT = 0f;\n InitializeCurrentParameters();\n _logger.LogTrace(\"LipSync state reset.\");\n }\n\n #endregion\n\n #region Phoneme Processing\n\n private void ProcessAudioSegment(AudioSegment segment)\n {\n _activePhonemes.Clear();\n\n var lastEndTime = 0.0;\n\n foreach ( var token in segment.Tokens )\n {\n if ( string.IsNullOrEmpty(token.Phonemes) || !token.StartTs.HasValue || !token.EndTs.HasValue || token.EndTs.Value <= token.StartTs.Value )\n {\n _logger.LogTrace(\"Skipping invalid token: Phonemes='{Phonemes}', Start={StartTs}, End={EndTs}\", token.Phonemes, token.StartTs, token.EndTs);\n\n continue;\n }\n\n var tokenStartTime = Math.Max(lastEndTime, token.StartTs.Value);\n var tokenEndTime = Math.Max(tokenStartTime + 0.001, token.EndTs.Value);\n\n var phonemeChars = SplitPhonemes(token.Phonemes);\n if ( phonemeChars.Count == 0 )\n {\n _logger.LogTrace(\"No valid phoneme characters found in token: '{Phonemes}'\", token.Phonemes);\n\n continue;\n }\n\n var tokenDuration = tokenEndTime - tokenStartTime;\n var timePerPhoneme = tokenDuration / phonemeChars.Count;\n var currentPhonemeStartTime = tokenStartTime;\n\n foreach ( var phChar in phonemeChars )\n {\n var phonemeEndTime = currentPhonemeStartTime + timePerPhoneme;\n _activePhonemes.Add(new TimedPhoneme { Phoneme = phChar, StartTime = currentPhonemeStartTime, EndTime = phonemeEndTime });\n currentPhonemeStartTime = phonemeEndTime;\n }\n\n lastEndTime = currentPhonemeStartTime;\n }\n\n _activePhonemes.Sort((a, b) => a.StartTime.CompareTo(b.StartTime));\n _logger.LogDebug(\"Processed segment into {Count} timed phonemes.\", _activePhonemes.Count);\n }\n\n private List SplitPhonemes(string phonemeString)\n {\n var result = new List();\n if ( string.IsNullOrEmpty(phonemeString) )\n {\n return result;\n }\n\n foreach ( var c in phonemeString )\n {\n if ( !_phonemeShapeIgnoreChars.Contains(c) )\n {\n result.Add(c.ToString());\n }\n }\n\n return result;\n }\n\n private PhonemePose GetPoseForPhoneme(string phoneme)\n {\n if ( _phonemeMap.TryGetValue(phoneme, out var pose) )\n {\n return pose;\n }\n\n _logger.LogDebug(\"Phoneme '{Phoneme}' not found in map. Returning Neutral.\", phoneme);\n\n return PhonemePose.Neutral;\n }\n\n #endregion\n\n #region Helper Functions\n\n private static float EaseInOutQuad(float t)\n {\n t = Math.Clamp(t, 0.0f, 1.0f);\n\n return t < 0.5f ? 2.0f * t * t : 1.0f - (float)Math.Pow(-2.0 * t + 2.0, 2.0) / 2.0f;\n }\n\n private static float Lerp(float a, float b, float t)\n {\n t = Math.Clamp(t, 0.0f, 1.0f);\n\n return a + (b - a) * t;\n }\n\n #endregion\n\n #region Structs and Maps\n\n public struct PhonemePose : IEquatable\n {\n public float MouthOpenY; // 0-1: How open the mouth is\n\n public float JawOpen; // 0-1: How open the jaw is\n\n public float MouthForm; // -1 (Frown) to +1 (Smile): Vertical lip corner movement\n\n public float MouthShrug; // 0-1: Upward lip shrug/tension\n\n public float MouthFunnel; // 0-1: Funnel shape (lips forward/pursed)\n\n public float MouthPuckerWiden; // -1 (Wide) to +1 (Pucker): Controls mouth width\n\n public float MouthPressLipOpen; // -1 (Pressed Thin) to 0 (Touching) to +1 (Separated/Teeth)\n\n public float MouthX; // -1 to 1: Horizontal mouth shift\n\n public float CheekPuffC; // 0-1: Cheek puff amount\n\n public static PhonemePose Neutral = new();\n\n public PhonemePose(float openY = 0, float jawOpen = 0, float form = 0, float shrug = 0, float funnel = 0, float puckerWiden = 0, float pressLip = 0, float mouthX = 0, float cheekPuff = 0)\n {\n MouthOpenY = openY;\n JawOpen = jawOpen;\n MouthForm = form;\n MouthShrug = shrug;\n MouthFunnel = funnel;\n MouthPuckerWiden = puckerWiden;\n MouthPressLipOpen = pressLip;\n MouthX = mouthX;\n CheekPuffC = cheekPuff;\n }\n\n public static PhonemePose Lerp(PhonemePose a, PhonemePose b, float t)\n {\n t = Math.Clamp(t, 0.0f, 1.0f);\n\n return new PhonemePose(\n VBridgerLipSyncService.Lerp(a.MouthOpenY, b.MouthOpenY, t),\n VBridgerLipSyncService.Lerp(a.JawOpen, b.JawOpen, t),\n VBridgerLipSyncService.Lerp(a.MouthForm, b.MouthForm, t),\n VBridgerLipSyncService.Lerp(a.MouthShrug, b.MouthShrug, t),\n VBridgerLipSyncService.Lerp(a.MouthFunnel, b.MouthFunnel, t),\n VBridgerLipSyncService.Lerp(a.MouthPuckerWiden, b.MouthPuckerWiden, t),\n VBridgerLipSyncService.Lerp(a.MouthPressLipOpen, b.MouthPressLipOpen, t),\n VBridgerLipSyncService.Lerp(a.MouthX, b.MouthX, t),\n VBridgerLipSyncService.Lerp(a.CheekPuffC, b.CheekPuffC, t)\n );\n }\n\n public bool Equals(PhonemePose other)\n {\n const float tolerance = 0.001f;\n\n return Math.Abs(MouthOpenY - other.MouthOpenY) < tolerance &&\n Math.Abs(JawOpen - other.JawOpen) < tolerance &&\n Math.Abs(MouthForm - other.MouthForm) < tolerance &&\n Math.Abs(MouthShrug - other.MouthShrug) < tolerance &&\n Math.Abs(MouthFunnel - other.MouthFunnel) < tolerance &&\n Math.Abs(MouthPuckerWiden - other.MouthPuckerWiden) < tolerance &&\n Math.Abs(MouthPressLipOpen - other.MouthPressLipOpen) < tolerance &&\n Math.Abs(MouthX - other.MouthX) < tolerance &&\n Math.Abs(CheekPuffC - other.CheekPuffC) < tolerance;\n }\n\n public override bool Equals(object? obj) { return obj is PhonemePose other && Equals(other); }\n\n public override int GetHashCode() { return HashCode.Combine(HashCode.Combine(MouthOpenY, JawOpen, MouthForm, MouthShrug, MouthFunnel, MouthPuckerWiden, MouthPressLipOpen, MouthX), CheekPuffC); }\n\n public static bool operator ==(PhonemePose left, PhonemePose right) { return left.Equals(right); }\n\n public static bool operator !=(PhonemePose left, PhonemePose right) { return !(left == right); }\n }\n\n private struct TimedPhoneme\n {\n public string Phoneme;\n\n public double StartTime;\n\n public double EndTime;\n }\n\n private Dictionary InitializeMisakiPhonemeMap()\n {\n // Phoneme to pose mapping based on VBridger parameter definitions:\n // MouthForm: -1 (Frown) to +1 (Smile)\n // MouthPuckerWiden: -1 (Wide) to +1 (Pucker)\n // MouthPressLipOpen: -1 (Pressed Thin) to +1 (Separated/Teeth)\n\n var map = new Dictionary();\n\n // --- Neutral ---\n map.Add(\"SIL\", PhonemePose.Neutral); // Neutral: open=0, jaw=0, form=0, shrug=0, funnel=0, puckerWiden=0, pressLip=0, puff=0\n\n // --- Shared IPA Consonants ---\n // Plosives (b, p, d, t, g, k) - Focus on closure and puff\n map.Add(\"b\", new PhonemePose(pressLip: -1.0f, cheekPuff: 0.6f)); // Pressed lips, puff\n map.Add(\"p\", new PhonemePose(pressLip: -1.0f, cheekPuff: 0.8f)); // Pressed lips, strong puff\n map.Add(\"d\", new PhonemePose(0.05f, 0.05f, pressLip: 0.0f, cheekPuff: 0.2f)); // Slight open, lips touch/nearly touch, slight puff\n map.Add(\"t\", new PhonemePose(0.05f, 0.05f, pressLip: 0.0f, cheekPuff: 0.3f)); // Slight open, lips touch/nearly touch, moderate puff\n map.Add(\"ɡ\", new PhonemePose(0.1f, 0.15f, pressLip: 0.2f, cheekPuff: 0.5f)); // Back sound, slight open, slight separation, puff\n map.Add(\"k\", new PhonemePose(0.1f, 0.15f, pressLip: 0.2f, cheekPuff: 0.4f)); // Back sound, slight open, slight separation, moderate puff\n\n // Fricatives (f, v, s, z, h, ʃ, ʒ, ð, θ) - Focus on partial closure/airflow shapes\n map.Add(\"f\", new PhonemePose(0.05f, pressLip: -0.2f, form: -0.2f, puckerWiden: -0.1f)); // Lower lip near upper teeth: Slight press, slight frown, slightly wide\n map.Add(\"v\", new PhonemePose(0.05f, pressLip: -0.1f, form: -0.2f, puckerWiden: -0.1f)); // Voiced 'f': Less press?\n map.Add(\"s\", new PhonemePose(jawOpen: 0.0f, pressLip: 0.9f, form: 0.3f, puckerWiden: -0.6f)); // Teeth close/showing, slight smile, wide\n map.Add(\"z\", new PhonemePose(jawOpen: 0.0f, pressLip: 0.8f, form: 0.2f, puckerWiden: -0.5f)); // Voiced 's': Slightly less extreme?\n map.Add(\"h\", new PhonemePose(0.2f, 0.2f, pressLip: 0.5f)); // Breathy open, lips separated\n map.Add(\"ʃ\", new PhonemePose(0.1f, funnel: 0.9f, puckerWiden: 0.6f, pressLip: 0.2f)); // 'sh': Funnel, puckered but flatter than 'oo', slight separation\n map.Add(\"ʒ\", new PhonemePose(0.1f, funnel: 0.8f, puckerWiden: 0.5f, pressLip: 0.2f)); // 'zh': Similar to 'sh'\n map.Add(\"ð\", new PhonemePose(0.05f, pressLip: 0.1f, puckerWiden: -0.2f)); // Soft 'th': Tongue tip, lips nearly touching, slightly wide\n map.Add(\"θ\", new PhonemePose(0.05f, pressLip: 0.2f, puckerWiden: -0.3f)); // Hard 'th': More airflow? More separation/width?\n\n // Nasals (m, n, ŋ) - Focus on closure or near-closure\n map.Add(\"m\", new PhonemePose(pressLip: -1.0f)); // Pressed lips\n map.Add(\"n\", new PhonemePose(0.05f, 0.05f, pressLip: 0.0f)); // Like 'd' position, lips touching\n map.Add(\"ŋ\", new PhonemePose(0.15f, 0.2f, pressLip: 0.4f)); // 'ng': Back tongue, mouth open more, lips separated\n\n // Liquids/Glides (l, ɹ, w, j) - Varied shapes\n map.Add(\"l\", new PhonemePose(0.2f, 0.2f, puckerWiden: -0.3f, pressLip: 0.6f)); // Tongue tip visible: Slightly open, slightly wide, lips separated\n map.Add(\"ɹ\", new PhonemePose(0.15f, 0.15f, funnel: 0.4f, puckerWiden: 0.2f, pressLip: 0.3f)); // 'r': Some funneling, slight pucker, separation\n map.Add(\"w\", new PhonemePose(0.1f, 0.1f, funnel: 1.0f, puckerWiden: 0.9f, pressLip: -0.3f)); // Like 'u': Strong funnel, strong pucker, lips maybe slightly pressed\n map.Add(\"j\", new PhonemePose(0.1f, 0.1f, 0.6f, 0.3f, puckerWiden: -0.8f, pressLip: 0.8f)); // 'y': Like 'i', smile, shrug, wide, teeth showing\n\n // --- Shared Consonant Clusters ---\n map.Add(\"ʤ\", new PhonemePose(0.1f, funnel: 0.8f, puckerWiden: 0.5f, pressLip: 0.2f, cheekPuff: 0.3f)); // 'j'/'dg': Target 'ʒ' shape + puff\n map.Add(\"ʧ\", new PhonemePose(0.1f, funnel: 0.9f, puckerWiden: 0.6f, pressLip: 0.2f, cheekPuff: 0.4f)); // 'ch': Target 'ʃ' shape + puff\n\n // --- Shared IPA Vowels ---\n map.Add(\"ə\", new PhonemePose(0.3f, 0.3f, pressLip: 0.5f)); // Schwa: Neutral open, lips separated\n map.Add(\"i\", new PhonemePose(0.1f, 0.1f, 0.7f, 0.4f, puckerWiden: -0.9f, pressLip: 0.9f)); // 'ee': Smile, shrug, wide, teeth showing\n map.Add(\"u\", new PhonemePose(0.15f, 0.15f, funnel: 1.0f, puckerWiden: 1.0f, pressLip: -0.2f)); // 'oo': Funnel, puckered, slight press\n map.Add(\"ɑ\", new PhonemePose(0.9f, 1.0f, pressLip: 0.8f)); // 'aa': Very open, lips separated\n map.Add(\"ɔ\", new PhonemePose(0.6f, 0.7f, funnel: 0.5f, puckerWiden: 0.3f, pressLip: 0.7f)); // 'aw': Open, some funnel, slight pucker, separated\n map.Add(\"ɛ\", new PhonemePose(0.5f, 0.5f, puckerWiden: -0.5f, pressLip: 0.7f)); // 'eh': Mid open, somewhat wide, separated\n map.Add(\"ɜ\", new PhonemePose(0.4f, 0.4f, pressLip: 0.6f)); // 'er': Mid open, neutral width, separated (blend with 'ɹ')\n map.Add(\"ɪ\", new PhonemePose(0.2f, 0.2f, 0.2f, puckerWiden: -0.6f, pressLip: 0.8f)); // 'ih': Slight open, slight smile, wide, separated\n map.Add(\"ʊ\", new PhonemePose(0.2f, 0.2f, funnel: 0.8f, puckerWiden: 0.7f, pressLip: 0.1f)); // 'uu': Slight open, funnel, pucker, near touch\n map.Add(\"ʌ\", new PhonemePose(0.6f, 0.6f, pressLip: 0.7f)); // 'uh': Mid open, neutral width, separated\n\n // --- Shared Diphthong Vowels (Targeting the end-shape's characteristics) ---\n map.Add(\"A\", new PhonemePose(0.3f, 0.3f, 0.4f, puckerWiden: -0.7f, pressLip: 0.8f)); // 'ay' (ends like ɪ/i): Mid-close, smile, wide, separated\n map.Add(\"I\", new PhonemePose(0.4f, 0.4f, 0.3f, puckerWiden: -0.6f, pressLip: 0.8f)); // 'eye' (ends like ɪ/i): Mid-open, smile, wide, separated\n map.Add(\"W\", new PhonemePose(0.3f, 0.3f, funnel: 0.9f, puckerWiden: 0.8f, pressLip: 0.0f)); // 'ow' (ends like ʊ/u): Mid-close, funnel, pucker, touching\n map.Add(\"Y\", new PhonemePose(0.3f, 0.3f, 0.2f, puckerWiden: -0.5f, pressLip: 0.8f)); // 'oy' (ends like ɪ/i): Mid-close, smile, wide, separated\n\n // --- Shared Custom Vowel ---\n map.Add(\"ᵊ\", new PhonemePose(0.1f, 0.1f, pressLip: 0.2f)); // Small schwa: Minimal open, slight separation\n\n // --- American-only ---\n map.Add(\"æ\", new PhonemePose(0.7f, 0.7f, 0.3f, puckerWiden: -0.8f, pressLip: 0.9f)); // 'ae': Open, slight smile, wide, teeth showing\n map.Add(\"O\", new PhonemePose(0.3f, 0.3f, funnel: 0.8f, puckerWiden: 0.6f, pressLip: 0.1f)); // US 'oh' (ends like ʊ/u): Mid-close, funnel, pucker, near touch\n map.Add(\"ᵻ\", new PhonemePose(0.15f, 0.15f, puckerWiden: -0.2f, pressLip: 0.6f)); // Between ə/ɪ: Slightly open, neutral-wide, separated\n map.Add(\"ɾ\", new PhonemePose(0.05f, 0.05f, pressLip: 0.3f)); // Flap 't': Very quick, slight separation\n\n // --- British-only ---\n map.Add(\"a\", new PhonemePose(0.7f, 0.7f, puckerWiden: -0.4f, pressLip: 0.8f)); // UK 'ash': Open, less wide than US 'æ', separated\n map.Add(\"Q\", new PhonemePose(0.3f, 0.3f, funnel: 0.7f, puckerWiden: 0.5f, pressLip: 0.1f)); // UK 'oh' (ends like ʊ/u): Mid-close, funnel, pucker, near touch\n map.Add(\"ɒ\", new PhonemePose(0.8f, 0.9f, funnel: 0.2f, puckerWiden: 0.1f, pressLip: 0.8f)); // 'on': Open, slight funnel, slight pucker, separated\n\n return map;\n }\n\n #endregion\n\n #region IDisposable Implementation\n\n public void Dispose() { Dispose(true); }\n\n private void Dispose(bool disposing)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( disposing )\n {\n _logger.LogDebug(\"Disposing...\");\n Stop();\n UnsubscribeFromCurrentNotifier();\n _activePhonemes.Clear();\n _currentParameterValues.Clear();\n }\n\n _disposed = true;\n _logger.LogInformation(\"Disposed\");\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Math/CubismViewMatrix.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Math;\n\n/// \n/// カメラの位置変更に使うと便利な4x4行列のクラス。\n/// \npublic record CubismViewMatrix : CubismMatrix44\n{\n /// \n /// デバイスに対応する論理座標上の範囲(左辺X軸位置)\n /// \n public float ScreenLeft { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(右辺X軸位置)\n /// \n public float ScreenRight { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(下辺Y軸位置)\n /// \n public float ScreenTop { get; private set; }\n\n /// \n /// デバイスに対応する論理座標上の範囲(上辺Y軸位置)\n /// \n public float ScreenBottom { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(左辺X軸位置)\n /// \n public float MaxLeft { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(右辺X軸位置)\n /// \n public float MaxRight { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(下辺Y軸位置)\n /// \n public float MaxTop { get; private set; }\n\n /// \n /// 論理座標上の移動可能範囲(上辺Y軸位置)\n /// \n public float MaxBottom { get; private set; }\n\n /// \n /// 拡大率の最大値\n /// \n public float MaxScale { get; set; }\n\n /// \n /// 拡大率の最小値\n /// \n public float MinScale { get; set; }\n\n /// \n /// 移動を調整する。\n /// \n /// X軸の移動量\n /// Y軸の移動量\n public void AdjustTranslate(float x, float y)\n {\n if ( _tr[0] * MaxLeft + (_tr[12] + x) > ScreenLeft )\n {\n x = ScreenLeft - _tr[0] * MaxLeft - _tr[12];\n }\n\n if ( _tr[0] * MaxRight + (_tr[12] + x) < ScreenRight )\n {\n x = ScreenRight - _tr[0] * MaxRight - _tr[12];\n }\n\n if ( _tr[5] * MaxTop + (_tr[13] + y) < ScreenTop )\n {\n y = ScreenTop - _tr[5] * MaxTop - _tr[13];\n }\n\n if ( _tr[5] * MaxBottom + (_tr[13] + y) > ScreenBottom )\n {\n y = ScreenBottom - _tr[5] * MaxBottom - _tr[13];\n }\n\n float[] tr1 = [\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n x, y, 0.0f, 1.0f\n ];\n\n MultiplyByMatrix(tr1);\n }\n\n /// \n /// 拡大率を調整する。\n /// \n /// 拡大を行うX軸の中心位置\n /// 拡大を行うY軸の中心位置\n /// 拡大率\n public void AdjustScale(float cx, float cy, float scale)\n {\n var maxScale = MaxScale;\n var minScale = MinScale;\n\n var targetScale = scale * _tr[0]; //\n\n if ( targetScale < minScale )\n {\n if ( _tr[0] > 0.0f )\n {\n scale = minScale / _tr[0];\n }\n }\n else if ( targetScale > maxScale )\n {\n if ( _tr[0] > 0.0f )\n {\n scale = maxScale / _tr[0];\n }\n }\n\n MultiplyByMatrix([\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n -cx, -cy, 0.0f, 1.0f\n ]);\n\n MultiplyByMatrix([\n scale, 0.0f, 0.0f, 0.0f,\n 0.0f, scale, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f\n ]);\n\n MultiplyByMatrix([\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n cx, cy, 0.0f, 1.0f\n ]);\n }\n\n /// \n /// デバイスに対応する論理座標上の範囲の設定を行う。\n /// \n /// 左辺のX軸の位置\n /// 右辺のX軸の位置\n /// 下辺のY軸の位置\n /// 上辺のY軸の位置\n public void SetScreenRect(float left, float right, float bottom, float top)\n {\n ScreenLeft = left;\n ScreenRight = right;\n ScreenTop = top;\n ScreenBottom = bottom;\n }\n\n /// \n /// デバイスに対応する論理座標上の移動可能範囲の設定を行う。\n /// \n /// 左辺のX軸の位置\n /// 右辺のX軸の位置\n /// 下辺のY軸の位置\n /// 上辺のY軸の位置\n public void SetMaxScreenRect(float left, float right, float bottom, float top)\n {\n MaxLeft = left;\n MaxRight = right;\n MaxTop = top;\n MaxBottom = bottom;\n }\n\n /// \n /// 拡大率が最大になっているかどうかを確認する。\n /// \n /// \n /// true 拡大率は最大になっている\n /// false 拡大率は最大になっていない\n /// \n public bool IsMaxScale() { return GetScaleX() >= MaxScale; }\n\n /// \n /// 拡大率が最小になっているかどうかを確認する。\n /// \n /// \n /// true 拡大率は最小になっている\n /// false 拡大率は最小になっていない\n /// \n public bool IsMinScale() { return GetScaleX() <= MinScale; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/PhonemizerG2P.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic class PhonemizerG2P : IPhonemizer\n{\n private readonly IFallbackPhonemizer? _fallback;\n\n private readonly ILexicon _lexicon;\n\n private readonly Regex _linkRegex;\n\n private readonly IPosTagger _posTagger;\n\n private readonly Regex _subtokenRegex;\n\n private readonly string _unk;\n\n private bool _disposed;\n\n public PhonemizerG2P(IPosTagger posTagger, ILexicon lexicon, IFallbackPhonemizer? fallback = null, string unk = \"❓\")\n {\n _posTagger = posTagger ?? throw new ArgumentNullException(nameof(posTagger));\n _fallback = fallback;\n _unk = unk;\n _lexicon = lexicon;\n\n // Initialize regular expressions once for performance\n _linkRegex = new Regex(@\"\\[([^\\]]+)\\]\\(([^\\)]*)\\)\", RegexOptions.Compiled);\n _subtokenRegex = new Regex(\n @\"^[''']+|\\p{Lu}(?=\\p{Lu}\\p{Ll})|(?:^-)?(?:\\d?[,.]?\\d)+|[-_]+|[''']{2,}|\\p{L}*?(?:[''']\\p{L})*?\\p{Ll}(?=\\p{Lu})|\\p{L}+(?:[''']\\p{L})*|[^-_\\p{L}'''\\d]|[''']+$\",\n RegexOptions.Compiled);\n\n _disposed = false;\n }\n\n public async Task ToPhonemesAsync(string text, CancellationToken cancellationToken = default)\n {\n // 1. Preprocess text\n var (processedText, textTokens, features) = Preprocess(text);\n\n // 2. Tag text with POS tagger\n var posTokens = await _posTagger.TagAsync(processedText, cancellationToken);\n\n // 3. Convert to internal token representation\n var tokens = ConvertToTokens(posTokens);\n\n // 4. Apply features from preprocessing\n ApplyFeatures(tokens, textTokens, features);\n\n // 5. Fold left (merge non-head tokens with previous token)\n tokens = FoldLeft(tokens);\n\n // 6. Retokenize (split complex tokens and handle special cases)\n var retokenizedTokens = Retokenize(tokens);\n\n // 7. Process phonemes using lexicon and fallback\n var ctx = new TokenContext();\n await ProcessTokensAsync(retokenizedTokens, ctx, cancellationToken);\n\n // 8. Merge retokenized tokens\n var mergedTokens = MergeRetokenizedTokens(retokenizedTokens);\n\n // 9. Generate final phoneme string\n var phonemes = string.Concat(mergedTokens.Select(t => (t.Phonemes ?? _unk) + t.Whitespace));\n\n return new PhonemeResult(phonemes, mergedTokens);\n }\n\n public void Dispose() { GC.SuppressFinalize(this); }\n\n private List ConvertToTokens(IReadOnlyList posTokens)\n {\n var tokens = new List(posTokens.Count);\n\n foreach ( var pt in posTokens )\n {\n tokens.Add(new Token { Text = pt.Text, Tag = pt.PartOfSpeech ?? string.Empty, Whitespace = pt.IsWhitespace ? \" \" : string.Empty });\n }\n\n return tokens;\n }\n\n private (string ProcessedText, List Tokens, Dictionary Features) Preprocess(string text)\n {\n text = text.TrimStart();\n var result = new StringBuilder(text.Length);\n var tokens = new List();\n var features = new Dictionary();\n\n var lastEnd = 0;\n\n foreach ( Match m in _linkRegex.Matches(text) )\n {\n if ( m.Index > lastEnd )\n {\n var segment = text.Substring(lastEnd, m.Index - lastEnd);\n result.Append(segment);\n tokens.AddRange(segment.Split(' ', StringSplitOptions.RemoveEmptyEntries));\n }\n\n var linkText = m.Groups[1].Value;\n var featureText = m.Groups[2].Value;\n\n object? featureValue = null;\n if ( featureText.Length >= 1 )\n {\n if ( (featureText[0] == '-' || featureText[0] == '+') &&\n int.TryParse(featureText, out var intVal) )\n {\n featureValue = intVal;\n }\n else if ( int.TryParse(featureText, out intVal) )\n {\n featureValue = intVal;\n }\n else if ( featureText == \"0.5\" || featureText == \"+0.5\" )\n {\n featureValue = 0.5;\n }\n else if ( featureText == \"-0.5\" )\n {\n featureValue = -0.5;\n }\n else if ( featureText.Length > 1 )\n {\n var firstChar = featureText[0];\n var lastChar = featureText[featureText.Length - 1];\n\n if ( firstChar == '/' && lastChar == '/' )\n {\n featureValue = firstChar + featureText.Substring(1, featureText.Length - 2);\n }\n else if ( firstChar == '#' && lastChar == '#' )\n {\n featureValue = firstChar + featureText.Substring(1, featureText.Length - 2);\n }\n }\n }\n\n if ( featureValue != null )\n {\n features[tokens.Count] = featureValue;\n }\n\n result.Append(linkText);\n tokens.Add(linkText);\n lastEnd = m.Index + m.Length;\n }\n\n if ( lastEnd < text.Length )\n {\n var segment = text.Substring(lastEnd);\n result.Append(segment);\n tokens.AddRange(segment.Split(' ', StringSplitOptions.RemoveEmptyEntries));\n }\n\n return (result.ToString(), tokens, features);\n }\n\n private void ApplyFeatures(List tokens, List textTokens, Dictionary features)\n {\n if ( features.Count == 0 )\n {\n return;\n }\n\n var alignment = CreateBidirectionalAlignment(textTokens, tokens.Select(t => t.Text).ToList());\n\n foreach ( var kvp in features )\n {\n var sourceIndex = kvp.Key;\n var value = kvp.Value;\n\n var matchedIndices = new List();\n for ( var i = 0; i < alignment.Length; i++ )\n {\n if ( alignment[i] == sourceIndex )\n {\n matchedIndices.Add(i);\n }\n }\n\n for ( var matchCount = 0; matchCount < matchedIndices.Count; matchCount++ )\n {\n var tokenIndex = matchedIndices[matchCount];\n\n if ( tokenIndex >= tokens.Count )\n {\n continue;\n }\n\n if ( value is int intValue )\n {\n tokens[tokenIndex].Stress = intValue;\n }\n else if ( value is double doubleValue )\n {\n tokens[tokenIndex].Stress = doubleValue;\n }\n else if ( value is string strValue )\n {\n if ( strValue.StartsWith(\"/\") )\n {\n // The \"i == 0\" in Python refers to the first match of this feature\n tokens[tokenIndex].IsHead = matchCount == 0;\n tokens[tokenIndex].Phonemes = matchCount == 0 ? strValue.Substring(1) : string.Empty;\n tokens[tokenIndex].Rating = 5;\n }\n else if ( strValue.StartsWith(\"#\") )\n {\n tokens[tokenIndex].NumFlags = strValue.Substring(1);\n }\n }\n }\n }\n }\n\n private int[] CreateBidirectionalAlignment(List source, List target)\n {\n // This is a simplified version - ideally it would match spaCy's algorithm more closely\n var alignment = new int[target.Count];\n\n // Create a combined string from each list to verify they match overall\n var sourceText = string.Join(\"\", source).ToLowerInvariant();\n var targetText = string.Join(\"\", target).ToLowerInvariant();\n\n // Initialize all alignments to no match\n for ( var i = 0; i < alignment.Length; i++ )\n {\n alignment[i] = -1;\n }\n\n var targetIndex = 0;\n var sourcePos = 0;\n\n // Track position in the joined strings to handle multi-token to single token mappings\n for ( var sourceIndex = 0; sourceIndex < source.Count; sourceIndex++ )\n {\n var sourceToken = source[sourceIndex].ToLowerInvariant();\n sourcePos += sourceToken.Length;\n\n var targetPos = 0;\n for ( var i = 0; i < targetIndex; i++ )\n {\n targetPos += target[i].ToLowerInvariant().Length;\n }\n\n // Map all target tokens that overlap with this source token\n while ( targetIndex < target.Count && targetPos < sourcePos )\n {\n var targetToken = target[targetIndex].ToLowerInvariant();\n alignment[targetIndex] = sourceIndex;\n\n targetPos += targetToken.Length;\n targetIndex++;\n }\n }\n\n return alignment;\n }\n\n private List FoldLeft(List tokens)\n {\n if ( tokens.Count <= 1 )\n {\n return tokens;\n }\n\n var result = new List(tokens.Count);\n result.Add(tokens[0]);\n\n for ( var i = 1; i < tokens.Count; i++ )\n {\n if ( !tokens[i].IsHead )\n {\n var merged = Token.MergeTokens(\n [result[^1], tokens[i]],\n _unk);\n\n result[^1] = merged;\n }\n else\n {\n result.Add(tokens[i]);\n }\n }\n\n return result;\n }\n\n private List Retokenize(List tokens)\n {\n var result = new List(tokens.Count * 2); // Estimate capacity\n string? currentCurrency = null;\n\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var token = tokens[i];\n List subtokens;\n\n // Split token if needed\n if ( token.Alias == null && token.Phonemes == null )\n {\n var subTokenTexts = Subtokenize(token.Text);\n subtokens = new List(subTokenTexts.Count);\n\n for ( var j = 0; j < subTokenTexts.Count; j++ )\n {\n subtokens.Add(new Token {\n Text = subTokenTexts[j],\n Tag = token.Tag,\n Whitespace = j == subTokenTexts.Count - 1 ? token.Whitespace : string.Empty,\n IsHead = token.IsHead && j == 0,\n Stress = token.Stress,\n NumFlags = token.NumFlags\n });\n }\n }\n else\n {\n subtokens = new List { token };\n }\n\n // Process each subtoken\n for ( var j = 0; j < subtokens.Count; j++ )\n {\n var t = subtokens[j];\n\n if ( t.Alias != null || t.Phonemes != null )\n {\n // Skip special handling for already processed tokens\n }\n else if ( t.Tag == \"$\" && PhonemizerConstants.Currencies.ContainsKey(t.Text) )\n {\n currentCurrency = t.Text;\n t.Phonemes = string.Empty;\n t.Rating = 4;\n }\n else if ( t is { Tag: \":\", Text: \"-\" or \"–\" } )\n {\n t.Phonemes = \"—\";\n t.Rating = 3;\n }\n else if ( PhonemizerConstants.PunctTags.Contains(t.Tag) )\n {\n if ( PhonemizerConstants.PunctTagPhonemes.TryGetValue(t.Tag, out var phoneme) )\n {\n t.Phonemes = phoneme;\n }\n else\n {\n var sb = new StringBuilder();\n foreach ( var c in t.Text )\n {\n if ( PhonemizerConstants.Puncts.Contains(c) )\n {\n sb.Append(c);\n }\n }\n\n t.Phonemes = sb.ToString();\n }\n\n t.Rating = 4;\n }\n else if ( currentCurrency != null )\n {\n if ( t.Tag != \"CD\" )\n {\n currentCurrency = null;\n }\n else if ( j + 1 == subtokens.Count && (i + 1 == tokens.Count || tokens[i + 1].Tag != \"CD\") )\n {\n t.Currency = currentCurrency;\n }\n }\n else if ( 0 < j && j < subtokens.Count - 1 &&\n t.Text == \"2\" &&\n char.IsLetter(subtokens[j - 1].Text[subtokens[j - 1].Text.Length - 1]) &&\n char.IsLetter(subtokens[j + 1].Text[0]) )\n {\n t.Alias = \"to\";\n }\n\n // Add to result\n if ( t.Alias != null || t.Phonemes != null )\n {\n result.Add(t);\n }\n else if ( result.Count > 0 &&\n result[result.Count - 1] is List lastList &&\n lastList.Count > 0 &&\n string.IsNullOrEmpty(lastList[lastList.Count - 1].Whitespace) )\n {\n t.IsHead = false;\n ((List)result[^1]).Add(t);\n }\n else\n {\n result.Add(string.IsNullOrEmpty(t.Whitespace) ? new List { t } : t);\n }\n }\n }\n\n // Simplify lists with single elements\n for ( var i = 0; i < result.Count; i++ )\n {\n if ( result[i] is List list && list.Count == 1 )\n {\n result[i] = list[0];\n }\n }\n\n return result;\n }\n\n private List Subtokenize(string word)\n {\n var matches = _subtokenRegex.Matches(word);\n if ( matches.Count == 0 )\n {\n return new List { word };\n }\n\n var result = new List(matches.Count);\n foreach ( Match match in matches )\n {\n result.Add(match.Value);\n }\n\n return result;\n }\n\n private async Task ProcessTokensAsync(List tokens, TokenContext ctx, CancellationToken cancellationToken)\n {\n // Process tokens in reverse order\n for ( var i = tokens.Count - 1; i >= 0; i-- )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n return;\n }\n\n if ( tokens[i] is Token token )\n {\n if ( token.Phonemes == null )\n {\n (token.Phonemes, token.Rating) = await GetPhonemesAsync(token, ctx, cancellationToken);\n }\n\n ctx = TokenContext.UpdateContext(ctx, token.Phonemes, token);\n }\n else if ( tokens[i] is List subtokens )\n {\n await ProcessSubtokensAsync(subtokens, ctx, cancellationToken);\n }\n }\n }\n\n private async Task ProcessSubtokensAsync(List tokens, TokenContext ctx, CancellationToken cancellationToken)\n {\n int left = 0,\n right = tokens.Count;\n\n var shouldFallback = false;\n\n while ( left < right )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n return;\n }\n\n if ( tokens.Skip(left).Take(right - left).Any(t => t.Alias != null || t.Phonemes != null) )\n {\n left++;\n\n continue;\n }\n\n var mergedToken = Token.MergeTokens(tokens.Skip(left).Take(right - left).ToList(), _unk);\n var (phonemes, rating) = await GetPhonemesAsync(mergedToken, ctx, cancellationToken);\n\n if ( phonemes != null )\n {\n tokens[left].Phonemes = phonemes;\n tokens[left].Rating = rating;\n\n for ( var i = left + 1; i < right; i++ )\n {\n tokens[i].Phonemes = string.Empty;\n tokens[i].Rating = rating;\n }\n\n ctx = TokenContext.UpdateContext(ctx, phonemes, mergedToken);\n right = left;\n left = 0;\n }\n else if ( left + 1 < right )\n {\n left++;\n }\n else\n {\n right--;\n var t = tokens[right];\n\n if ( t.Phonemes == null )\n {\n if ( t.Text.All(c => PhonemizerConstants.SubtokenJunks.Contains(c)) )\n {\n t.Phonemes = string.Empty;\n t.Rating = 3;\n }\n else if ( _fallback != null )\n {\n shouldFallback = true;\n\n break;\n }\n }\n\n left = 0;\n }\n }\n\n if ( shouldFallback && _fallback != null )\n {\n var mergedToken = Token.MergeTokens(tokens, _unk);\n var (phonemes, rating) = await _fallback.GetPhonemesAsync(mergedToken.Text, cancellationToken);\n\n if ( phonemes != null )\n {\n tokens[0].Phonemes = phonemes;\n tokens[0].Rating = rating;\n\n for ( var j = 1; j < tokens.Count; j++ )\n {\n tokens[j].Phonemes = string.Empty;\n tokens[j].Rating = rating;\n }\n }\n }\n\n ResolveTokens(tokens);\n }\n\n private async Task<(string? Phonemes, int? Rating)> GetPhonemesAsync(Token token, TokenContext ctx, CancellationToken cancellationToken)\n {\n // Try to get from lexicon\n var (phonemes, rating) = _lexicon.ProcessToken(token, ctx);\n\n // If not found, try fallback\n if ( phonemes == null && _fallback != null )\n {\n return await _fallback.GetPhonemesAsync(token.Alias ?? token.Text, cancellationToken);\n }\n\n return (phonemes, rating);\n }\n\n private void ResolveTokens(List tokens)\n {\n // Calculate if there should be space between phonemes\n var text = string.Concat(tokens.Take(tokens.Count - 1).Select(t => t.Text + t.Whitespace)) +\n tokens[tokens.Count - 1].Text;\n\n var prespace = text.Contains(' ') || text.Contains('/') ||\n text.Where(c => !PhonemizerConstants.SubtokenJunks.Contains(c))\n .Select(c => char.IsLetter(c)\n ? 0\n : char.IsDigit(c)\n ? 1\n : 2)\n .Distinct()\n .Count() > 1;\n\n // Handle specific cases\n for ( var i = 0; i < tokens.Count; i++ )\n {\n var t = tokens[i];\n\n if ( t.Phonemes == null )\n {\n if ( i == tokens.Count - 1 && t.Text.Length > 0 &&\n PhonemizerConstants.NonQuotePuncts.Contains(t.Text[0]) )\n {\n t.Phonemes = t.Text;\n t.Rating = 3;\n }\n else if ( t.Text.All(c => PhonemizerConstants.SubtokenJunks.Contains(c)) )\n {\n t.Phonemes = string.Empty;\n t.Rating = 3;\n }\n }\n else if ( i > 0 )\n {\n t.Prespace = prespace;\n }\n }\n\n if ( prespace )\n {\n return;\n }\n\n // Adjust stress patterns\n var indices = new List<(bool HasPrimaryStress, int Weight, int Index)>();\n for ( var i = 0; i < tokens.Count; i++ )\n {\n if ( !string.IsNullOrEmpty(tokens[i].Phonemes) )\n {\n var hasPrimary = tokens[i].Phonemes.Contains(PhonemizerConstants.PrimaryStress);\n indices.Add((hasPrimary, tokens[i].StressWeight(), i));\n }\n }\n\n if ( indices.Count == 2 && tokens[indices[0].Index].Text.Length == 1 )\n {\n var i = indices[1].Index;\n tokens[i].Phonemes = ApplyStress(tokens[i].Phonemes!, -0.5);\n\n return;\n }\n\n if ( indices.Count < 2 || indices.Count(x => x.HasPrimaryStress) <= (indices.Count + 1) / 2 )\n {\n return;\n }\n\n indices.Sort();\n foreach ( var (_, _, i) in indices.Take(indices.Count / 2) )\n {\n tokens[i].Phonemes = ApplyStress(tokens[i].Phonemes!, -0.5);\n }\n }\n\n private string ApplyStress(string phonemes, double stress)\n {\n if ( stress < -1 )\n {\n return phonemes\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty);\n }\n\n if ( stress == -1 || ((stress == 0 || stress == -0.5) && phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return phonemes\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), PhonemizerConstants.SecondaryStress.ToString());\n }\n\n if ( (stress == 0 || stress == 0.5 || stress == 1) &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.SecondaryStress + phonemes);\n }\n\n if ( stress >= 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n return phonemes.Replace(PhonemizerConstants.SecondaryStress.ToString(), PhonemizerConstants.PrimaryStress.ToString());\n }\n\n if ( stress > 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.PrimaryStress + phonemes);\n }\n\n return phonemes;\n }\n\n private string RestressPhonemes(string phonemes)\n {\n var chars = phonemes.ToCharArray();\n var charPositions = new List<(int Position, char Char)>();\n\n for ( var i = 0; i < chars.Length; i++ )\n {\n charPositions.Add((i, chars[i]));\n }\n\n var stressPositions = new Dictionary();\n for ( var i = 0; i < charPositions.Count; i++ )\n {\n if ( PhonemizerConstants.Stresses.Contains(charPositions[i].Char) )\n {\n // Find the next vowel\n var vowelPos = -1;\n for ( var j = i + 1; j < charPositions.Count; j++ )\n {\n if ( PhonemizerConstants.Vowels.Contains(charPositions[j].Char) )\n {\n vowelPos = j;\n\n break;\n }\n }\n\n if ( vowelPos != -1 )\n {\n stressPositions[charPositions[i].Position] = charPositions[vowelPos].Position;\n charPositions[i] = ((int)(vowelPos - 0.5), charPositions[i].Char);\n }\n }\n }\n\n charPositions.Sort((a, b) => a.Position.CompareTo(b.Position));\n\n return new string(charPositions.Select(cp => cp.Char).ToArray());\n }\n\n private List MergeRetokenizedTokens(List retokenizedTokens)\n {\n var result = new List();\n\n foreach ( var item in retokenizedTokens )\n {\n if ( item is Token token )\n {\n result.Add(token);\n }\n else if ( item is List tokens )\n {\n result.Add(Token.MergeTokens(tokens, _unk));\n }\n }\n\n return result;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismMoc.cs", "using System.Runtime.InteropServices;\n\nusing PersonaEngine.Lib.Live2D.Framework.Core;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// Mocデータの管理を行うクラス。\n/// \npublic class CubismMoc : IDisposable\n{\n /// \n /// Mocデータ\n /// \n private readonly IntPtr _moc;\n\n /// \n /// バッファからMocファイルを読み取り、Mocデータを作成する。\n /// \n /// Mocファイルのバッファ\n /// MOCの整合性チェックフラグ(初期値 : false)\n /// \n public CubismMoc(byte[] mocBytes, bool shouldCheckMocConsistency = false)\n {\n var alignedBuffer = CubismFramework.AllocateAligned(mocBytes.Length, CsmEnum.csmAlignofMoc);\n Marshal.Copy(mocBytes, 0, alignedBuffer, mocBytes.Length);\n\n if ( shouldCheckMocConsistency )\n {\n // .moc3の整合性を確認\n var consistency = HasMocConsistency(alignedBuffer, mocBytes.Length);\n if ( !consistency )\n {\n CubismFramework.DeallocateAligned(alignedBuffer);\n\n // 整合性が確認できなければ処理しない\n throw new Exception(\"Inconsistent MOC3.\");\n }\n }\n\n var moc = CubismCore.ReviveMocInPlace(alignedBuffer, mocBytes.Length);\n\n if ( moc == IntPtr.Zero )\n {\n throw new Exception(\"MOC3 is null\");\n }\n\n _moc = moc;\n\n MocVersion = CubismCore.GetMocVersion(alignedBuffer, mocBytes.Length);\n\n var modelSize = CubismCore.GetSizeofModel(_moc);\n var modelMemory = CubismFramework.AllocateAligned(modelSize, CsmEnum.CsmAlignofModel);\n\n var model = CubismCore.InitializeModelInPlace(_moc, modelMemory, modelSize);\n\n if ( model == IntPtr.Zero )\n {\n throw new Exception(\"MODEL is null\");\n }\n\n Model = new CubismModel(model);\n }\n\n /// \n /// 読み込んだモデルの.moc3 Version\n /// \n public uint MocVersion { get; }\n\n public CubismModel Model { get; }\n\n /// \n /// デストラクタ。\n /// \n public void Dispose()\n {\n Model.Dispose();\n CubismFramework.DeallocateAligned(_moc);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// 最新の.moc3 Versionを取得する。\n /// \n /// \n public static uint GetLatestMocVersion() { return CubismCore.GetLatestMocVersion(); }\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// '1' if Moc is valid; '0' otherwise.\n public static bool HasMocConsistency(IntPtr address, int size) { return CubismCore.HasMocConsistency(address, size); }\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Mocファイルのバッファ\n /// バッファのサイズ\n /// 'true' if Moc is valid; 'false' otherwise.\n public static bool HasMocConsistencyFromUnrevivedMoc(byte[] data)\n {\n var alignedBuffer = CubismFramework.AllocateAligned(data.Length, CsmEnum.csmAlignofMoc);\n Marshal.Copy(data, 0, alignedBuffer, data.Length);\n\n var consistency = HasMocConsistency(alignedBuffer, data.Length);\n\n CubismFramework.DeallocateAligned(alignedBuffer);\n\n return consistency;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleTimeline.cs", "using System.Numerics;\n\nusing FontStashSharp;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Manages active subtitle segments, updates their state based on time,\n/// determines visible lines, and calculates their positions.\n/// \npublic class SubtitleTimeline\n{\n private readonly List _activeSegments = new();\n\n private readonly float _bottomMargin;\n\n private readonly FSColor _highlightColor;\n\n private readonly float _interSegmentSpacing;\n\n private readonly float _lineSpacing;\n\n private readonly Lock _lock = new();\n\n private readonly int _maxVisibleLines;\n\n private readonly FSColor _normalColor;\n\n private readonly TextMeasurer _textMeasurer;\n\n private readonly List _visibleLinesCache;\n\n private readonly IWordAnimator _wordAnimator;\n\n public SubtitleTimeline(\n int maxVisibleLines,\n float bottomMargin,\n float lineSpacing,\n float interSegmentSpacing,\n TextMeasurer textMeasurer,\n IWordAnimator wordAnimator,\n FSColor highlightColor,\n FSColor normalColor)\n {\n _maxVisibleLines = Math.Max(1, maxVisibleLines);\n _bottomMargin = bottomMargin;\n _lineSpacing = lineSpacing;\n _interSegmentSpacing = interSegmentSpacing;\n _textMeasurer = textMeasurer;\n _wordAnimator = wordAnimator;\n _highlightColor = highlightColor;\n _normalColor = normalColor;\n\n _visibleLinesCache = new List(_maxVisibleLines * 2);\n }\n\n public void AddSegment(SubtitleSegment segment)\n {\n lock (_lock)\n {\n _activeSegments.Add(segment);\n }\n }\n\n public void RemoveSegment(object originalSegmentIdentifier)\n {\n lock (_lock)\n {\n _activeSegments.RemoveAll(s => ReferenceEquals(s.OriginalAudioSegment, originalSegmentIdentifier) || s.OriginalAudioSegment.Equals(originalSegmentIdentifier));\n\n // TODO: If using object pooling for segments/lines/words, return them to the pool here.\n }\n }\n\n /// \n /// Updates the animation progress and state of words in active segments.\n /// \n public void Update(float currentTime)\n {\n lock (_lock)\n {\n for ( var i = _activeSegments.Count - 1; i >= 0; i-- )\n {\n var segment = _activeSegments[i];\n\n // Optimization: Potentially skip segments that are entirely in the past?\n // if (segment.EstimatedEndTime < currentTime - someBuffer) continue;\n // Optimization: Potentially skip segments entirely in the future?\n // if (segment.AbsoluteStartTime > currentTime + someBuffer) continue;\n\n for ( var j = 0; j < segment.Lines.Count; j++ )\n {\n var line = segment.Lines[j];\n // Use ref local for structs to avoid copying if SubtitleWordInfo is a struct\n // Requires Words to be an array or Span for direct ref access.\n // With List, we modify the copy and then update the list element.\n for ( var k = 0; k < line.Words.Count; k++ )\n {\n var word = line.Words[k];\n\n if ( word.HasStarted(currentTime) )\n {\n if ( word.IsComplete(currentTime) )\n {\n word.AnimationProgress = 1.0f;\n }\n else\n {\n var elapsed = currentTime - word.AbsoluteStartTime;\n word.AnimationProgress = Math.Clamp(elapsed / word.Duration, 0.0f, 1.0f);\n }\n }\n else\n {\n word.AnimationProgress = 0.0f;\n }\n\n word.CurrentScale = _wordAnimator.CalculateScale(word.AnimationProgress);\n word.CurrentColor = _wordAnimator.CalculateColor(_highlightColor, _normalColor, word.AnimationProgress);\n\n line.Words[k] = word;\n }\n }\n }\n }\n }\n\n public List GetVisibleLinesAndPosition(float currentTime, int viewportWidth, int viewportHeight)\n {\n _visibleLinesCache.Clear();\n\n lock (_lock)\n {\n for ( var i = _activeSegments.Count - 1; i >= 0; i-- )\n {\n var segment = _activeSegments[i];\n\n // Optimization: If segment hasn't started, none of its lines are visible.\n if ( segment.AbsoluteStartTime > currentTime )\n {\n continue;\n }\n\n for ( var j = segment.Lines.Count - 1; j >= 0; j-- )\n {\n var line = segment.Lines[j];\n\n if ( line.Words.Count > 0 && line.Words[0].HasStarted(currentTime) )\n {\n _visibleLinesCache.Add(line);\n if ( _visibleLinesCache.Count >= _maxVisibleLines )\n {\n goto FoundEnoughLines;\n }\n }\n\n // Optimization: If the first word of this line hasn't started,\n // earlier lines in the *same segment* also won't have started yet.\n // (Assumes words within a line are chronologically ordered).\n // else if (line.Words.Count > 0)\n // {\n // break; // Stop checking lines in this segment\n // }\n }\n }\n }\n\n FoundEnoughLines:\n\n _visibleLinesCache.Reverse();\n\n var currentBaselineY = viewportHeight - _bottomMargin;\n\n for ( var i = _visibleLinesCache.Count - 1; i >= 0; i-- )\n {\n var line = _visibleLinesCache[i];\n line.BaselineY = currentBaselineY;\n\n var currentX = (viewportWidth - line.TotalWidth) / 2.0f;\n\n for ( var k = 0; k < line.Words.Count; k++ )\n {\n var word = line.Words[k];\n\n var wordCenterX = currentX + word.Size.X / 2.0f;\n var wordCenterY = currentBaselineY - _textMeasurer.LineHeight / 2.0f;\n\n word.Position = new Vector2(wordCenterX, wordCenterY);\n line.Words[k] = word;\n currentX += word.Size.X;\n }\n\n currentBaselineY -= _lineSpacing;\n\n if ( i > 0 && _visibleLinesCache[i - 1].SegmentIndex != line.SegmentIndex )\n {\n currentBaselineY -= _interSegmentSpacing;\n }\n }\n\n return _visibleLinesCache;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/LAppDelegate.cs", "using PersonaEngine.Lib.Live2D.Framework;\nusing PersonaEngine.Lib.Live2D.Framework.Core;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering;\nusing PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\nnamespace PersonaEngine.Lib.Live2D.App;\n\n/// \n/// アプリケーションクラス。\n/// Cubism SDK の管理を行う。\n/// \npublic class LAppDelegate : IDisposable\n{\n /// \n /// Cubism SDK Allocator\n /// \n private readonly LAppAllocator _cubismAllocator;\n\n /// \n /// Cubism SDK Option\n /// \n private readonly Option _cubismOption;\n\n /// \n /// クリックしているか\n /// \n private bool _captured;\n\n /// \n /// マウスX座標\n /// \n private float _mouseX;\n\n /// \n /// マウスY座標\n /// \n private float _mouseY;\n\n /// \n /// Initialize関数で設定したウィンドウ高さ\n /// \n private int _windowHeight;\n\n /// \n /// Initialize関数で設定したウィンドウ幅\n /// \n private int _windowWidth;\n\n public LAppDelegate(OpenGLApi gl, LogFunction log)\n {\n GL = gl;\n\n View = new LAppView(this);\n TextureManager = new LAppTextureManager(this);\n _cubismAllocator = new LAppAllocator();\n\n //テクスチャサンプリング設定\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);\n GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);\n\n //透過設定\n GL.Enable(GL.GL_BLEND);\n GL.BlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);\n\n // ウィンドウサイズ記憶\n GL.GetWindowSize(out _windowWidth, out _windowHeight);\n\n //AppViewの初期化\n View.Initialize();\n\n // Cubism SDK の初期化\n _cubismOption = new Option { LogFunction = log, LoggingLevel = LAppDefine.CubismLoggingLevel };\n CubismFramework.StartUp(_cubismAllocator, _cubismOption);\n\n //Initialize cubism\n CubismFramework.Initialize();\n\n //load model\n Live2dManager = new LAppLive2DManager(this);\n\n LAppPal.DeltaTime = 0;\n }\n\n /// \n /// テクスチャマネージャー\n /// \n public LAppTextureManager TextureManager { get; private set; }\n\n public LAppLive2DManager Live2dManager { get; private set; }\n\n public OpenGLApi GL { get; }\n\n /// \n /// View情報\n /// \n public LAppView View { get; private set; }\n\n public CubismTextureColor BGColor { get; set; } = new(0, 0, 0, 0);\n\n /// \n /// 解放する。\n /// \n public void Dispose()\n {\n // リソースを解放\n Live2dManager.Dispose();\n\n //Cubism SDK の解放\n CubismFramework.Dispose();\n\n GC.SuppressFinalize(this);\n }\n\n public void Resize()\n {\n GL.GetWindowSize(out var width, out var height);\n if ( (_windowWidth != width || _windowHeight != height) && width > 0 && height > 0 )\n {\n //AppViewの初期化\n View.Initialize();\n // サイズを保存しておく\n _windowWidth = width;\n _windowHeight = height;\n }\n }\n\n public void Update(float tick)\n {\n // 時間更新\n LAppPal.DeltaTime = tick;\n }\n\n /// \n /// 実行処理。\n /// \n public void Run()\n {\n // 画面の初期化\n GL.ClearColor(BGColor.R, BGColor.G, BGColor.B, BGColor.A);\n GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);\n GL.ClearDepthf(1.0f);\n\n //描画更新\n View.Render();\n }\n\n /// \n /// OpenGL用 glfwSetMouseButtonCallback用関数。\n /// \n /// ボタン種類\n /// 実行結果\n public void OnMouseCallBack(bool press)\n {\n if ( press )\n {\n _captured = true;\n View.OnTouchesBegan(_mouseX, _mouseY);\n }\n else\n {\n if ( _captured )\n {\n _captured = false;\n View.OnTouchesEnded(_mouseX, _mouseY);\n }\n }\n }\n\n /// \n /// OpenGL用 glfwSetCursorPosCallback用関数。\n /// \n /// x座標\n /// x座標\n public void OnMouseCallBack(float x, float y)\n {\n if ( !_captured )\n {\n return;\n }\n\n _mouseX = x;\n _mouseY = y;\n\n View.OnTouchesMoved(_mouseX, _mouseY);\n }\n\n public void StartSpeaking(string filePath) { Live2dManager.StartSpeaking(filePath); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/AudioConverter.cs", "using System.Buffers.Binary;\nusing System.Runtime.CompilerServices;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Provides functionality for converting audio between different formats.\n/// \npublic static class AudioConverter\n{\n /// \n /// Calculates the required size for a buffer to hold the converted audio.\n /// \n /// The source audio buffer.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The size in bytes needed for the target buffer.\n public static int CalculateTargetBufferSize(\n ReadOnlyMemory sourceBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var framesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // If resampling is needed, adjust the frame count\n if ( sourceFormat.SampleRate != targetFormat.SampleRate )\n {\n framesCount = CalculateResampledFrameCount(framesCount, sourceFormat.SampleRate, targetFormat.SampleRate);\n }\n\n // Calculate the expected size of the target buffer\n return framesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Calculates the number of frames after resampling.\n /// \n /// Number of frames in the source buffer.\n /// Sample rate of the source audio.\n /// Target sample rate.\n /// The number of frames after resampling.\n public static int CalculateResampledFrameCount(\n int sourceFrameCount,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n return (int)Math.Ceiling(sourceFrameCount * ((double)targetSampleRate / sourceSampleRate));\n }\n\n /// \n /// Converts audio data between different formats.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the converted data to.\n /// The format of the source audio.\n /// The format for the target audio.\n /// The number of bytes written to the target buffer.\n /// Thrown if the target buffer is too small.\n public static int Convert(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat)\n {\n // Calculate the number of frames in the source buffer\n var sourceFramesCount = sourceBuffer.Length / sourceFormat.BytesPerFrame;\n\n // Check if resampling is needed\n var needsResampling = sourceFormat.SampleRate != targetFormat.SampleRate;\n\n // Calculate the expected number of frames in the target buffer\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceFormat.SampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate the expected size of the target buffer\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Fast path for same format conversion with no resampling\n if ( !needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n sourceBuffer.CopyTo(targetBuffer);\n\n return sourceBuffer.Length;\n }\n\n // If only resampling is needed (same format otherwise)\n if ( needsResampling &&\n sourceFormat.Channels == targetFormat.Channels &&\n sourceFormat.BitsPerSample == targetFormat.BitsPerSample )\n {\n return ResampleDirect(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // For mono-to-stereo int16 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 32 && targetFormat.BitsPerSample == 16 )\n {\n ConvertMonoFloat32ToStereoInt16Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For stereo-to-mono conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 2 && targetFormat.Channels == 1 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertStereoInt16ToMonoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // For mono-int16 to stereo-float32 conversion, use optimized path\n if ( !needsResampling &&\n sourceFormat.Channels == 1 && targetFormat.Channels == 2 &&\n sourceFormat.BitsPerSample == 16 && targetFormat.BitsPerSample == 32 )\n {\n ConvertMonoInt16ToStereoFloat32Direct(sourceBuffer, targetBuffer, sourceFramesCount);\n\n return expectedTargetSize;\n }\n\n // General case: convert through intermediate float format\n return ConvertGeneral(\n sourceBuffer,\n targetBuffer,\n sourceFormat,\n targetFormat,\n sourceFramesCount,\n targetFramesCount,\n needsResampling);\n }\n\n /// \n /// Specialized fast path to convert 48kHz stereo float32 audio to 16kHz mono int16 audio.\n /// This optimized method combines resampling, channel conversion, and bit depth conversion in one pass.\n /// \n /// The 48kHz stereo float32 audio buffer.\n /// The target buffer to receive the 16kHz mono int16 data.\n /// The number of bytes written to the target buffer.\n public static int ConvertStereoFloat32_48kTo_MonoInt16_16k(\n ReadOnlyMemory stereoFloat32Buffer,\n Memory targetBuffer)\n {\n var sourceFormat = new AudioFormat(2, 32, 48000);\n var targetFormat = new AudioFormat(1, 16, 16000);\n\n // Calculate number of source and target frames\n var sourceFramesCount = stereoFloat32Buffer.Length / sourceFormat.BytesPerFrame;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, 48000, 16000);\n\n // Calculate expected target size and verify buffer is large enough\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Process the conversion directly\n ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n stereoFloat32Buffer.Span,\n targetBuffer.Span,\n sourceFramesCount,\n targetFramesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Direct conversion implementation for 48kHz stereo float32 to 16kHz mono int16.\n /// Combines downsampling (48kHz to 16kHz - 3:1 ratio), stereo to mono mixing, and float32 to int16 conversion.\n /// \n private static void ConvertStereoFloat32_48kTo_MonoInt16_16kDirect(\n ReadOnlySpan source,\n Span target,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // The resampling ratio is exactly 3:1 (48000/16000)\n const int resampleRatio = 3;\n\n // For optimal quality, we'll use a simple low-pass filter when downsampling\n // by averaging 3 consecutive frames before picking every 3rd one\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source frame index (center of 3-frame window)\n var sourceFrameBase = targetFrame * resampleRatio;\n\n // Initialize accumulator for filtered sample\n var monoSampleAccumulator = 0f;\n var sampleCount = 0;\n\n // Apply a simple averaging filter over a window of frames\n for ( var offset = -1; offset <= 1; offset++ )\n {\n var sourceFrameIndex = sourceFrameBase + offset;\n\n // Skip samples outside buffer boundary\n if ( sourceFrameIndex < 0 || sourceFrameIndex >= sourceFramesCount )\n {\n continue;\n }\n\n // Read left and right float32 samples and average them to mono\n var sourceByteIndex = sourceFrameIndex * 8; // 8 bytes per stereo float32 frame\n var leftSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex, 4));\n var rightSample = BinaryPrimitives.ReadSingleLittleEndian(source.Slice(sourceByteIndex + 4, 4));\n\n // Average stereo to mono\n var monoSample = (leftSample + rightSample) * 0.5f;\n\n // Accumulate filtered sample\n monoSampleAccumulator += monoSample;\n sampleCount++;\n }\n\n // Average samples if we have any\n var filteredSample = sampleCount > 0 ? monoSampleAccumulator / sampleCount : 0f;\n\n // Convert float32 to int16 (with scaling and clamping)\n var int16Sample = ClampToInt16(filteredSample * 32767f);\n\n // Write to target buffer\n var targetByteIndex = targetFrame * 2; // 2 bytes per mono int16 frame\n BinaryPrimitives.WriteInt16LittleEndian(target.Slice(targetByteIndex, 2), int16Sample);\n }\n }\n\n /// \n /// Resamples audio using a higher quality filter.\n /// Uses a sinc filter for better frequency response.\n /// \n private static void ResampleWithFilter(float[] source, float[] target, uint sourceRate, uint targetRate)\n {\n // For 48kHz to 16kHz, we have a 3:1 ratio\n var ratio = (double)sourceRate / targetRate;\n\n // Use a simple windowed-sinc filter with 8 taps for anti-aliasing\n var filterSize = 8;\n\n for ( var targetIndex = 0; targetIndex < target.Length; targetIndex++ )\n {\n // Calculate the corresponding position in the source\n var sourcePos = targetIndex * ratio;\n var sourceCenterIndex = (int)sourcePos;\n\n // Apply the filter\n var sum = 0f;\n var totalWeight = 0f;\n\n for ( var tap = -filterSize / 2; tap < filterSize / 2; tap++ )\n {\n var sourceIndex = sourceCenterIndex + tap;\n\n // Skip samples outside buffer boundary\n if ( sourceIndex < 0 || sourceIndex >= source.Length )\n {\n continue;\n }\n\n // Calculate the sinc weight\n var x = sourcePos - sourceIndex;\n var weight = x == 0 ? 1.0f : (float)(Math.Sin(Math.PI * x) / (Math.PI * x));\n\n // Apply a Hann window to reduce ringing\n weight *= 0.5f * (1 + (float)Math.Cos(2 * Math.PI * (tap + filterSize / 2) / filterSize));\n\n sum += source[sourceIndex] * weight;\n totalWeight += weight;\n }\n\n // Normalize the output\n target[targetIndex] = totalWeight > 0 ? sum / totalWeight : 0f;\n }\n }\n\n /// \n /// Resamples audio data to a different sample rate.\n /// \n /// The source audio buffer.\n /// The target audio buffer to write the resampled data to.\n /// The format of the source audio.\n /// The target sample rate.\n /// The number of bytes written to the target buffer.\n public static int Resample(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n uint targetSampleRate)\n {\n // Create target format with the new sample rate but same other parameters\n var targetFormat = new AudioFormat(\n sourceFormat.Channels,\n sourceFormat.BitsPerSample,\n targetSampleRate);\n\n return Convert(sourceBuffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Resamples floating-point audio samples directly.\n /// \n /// The source float samples.\n /// The target buffer to write the resampled samples to.\n /// Number of channels in the audio.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ResampleFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort channels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n // Fast path for same sample rate\n if ( sourceSampleRate == targetSampleRate )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceSamples.Length / channels;\n }\n\n var sourceFramesCount = sourceSamples.Length / channels;\n var targetFramesCount = CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate);\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * channels )\n {\n throw new ArgumentException(\"Target buffer is too small for the resampled audio.\");\n }\n\n // Perform the resampling\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n channels,\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Converts float samples to a different format (channels, sample rate) and outputs as byte array.\n /// \n /// The source float samples.\n /// The target buffer to write the converted data to.\n /// Number of channels in the source.\n /// Source sample rate.\n /// The desired output format.\n /// The number of bytes written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetBuffer,\n ushort sourceChannels,\n uint sourceSampleRate,\n AudioFormat targetFormat)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetFormat.SampleRate;\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetFormat.SampleRate)\n : sourceFramesCount;\n\n // Calculate expected target buffer size\n var expectedTargetSize = targetFramesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Handle resampling if needed\n ReadOnlyMemory resampledSamples;\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceChannels];\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n }\n else\n {\n resampledSamples = sourceSamples;\n }\n\n // Handle channel conversion if needed\n ReadOnlyMemory convertedSamples;\n if ( sourceChannels != targetFormat.Channels )\n {\n var convertedBuffer = new float[targetFramesCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceChannels,\n targetFormat.Channels,\n targetFramesCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return expectedTargetSize;\n }\n\n /// \n /// Converts audio format with direct access to float samples.\n /// \n /// The source float samples.\n /// The target buffer to write the converted samples to.\n /// Number of channels in the source.\n /// Number of channels for the output.\n /// Source sample rate.\n /// Target sample rate.\n /// The number of frames written to the target buffer.\n public static int ConvertFloat(\n ReadOnlyMemory sourceSamples,\n Memory targetSamples,\n ushort sourceChannels,\n ushort targetChannels,\n uint sourceSampleRate,\n uint targetSampleRate)\n {\n var sourceFramesCount = sourceSamples.Length / sourceChannels;\n var needsResampling = sourceSampleRate != targetSampleRate;\n var needsChannelConversion = sourceChannels != targetChannels;\n\n // If no conversion needed, just copy\n if ( !needsResampling && !needsChannelConversion )\n {\n sourceSamples.CopyTo(targetSamples);\n\n return sourceFramesCount;\n }\n\n // Calculate target frames count after potential resampling\n var targetFramesCount = needsResampling\n ? CalculateResampledFrameCount(sourceFramesCount, sourceSampleRate, targetSampleRate)\n : sourceFramesCount;\n\n // Ensure target buffer is large enough\n if ( targetSamples.Length < targetFramesCount * targetChannels )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n // Optimize the common path where only channel conversion or only resampling is needed\n if ( needsResampling && !needsChannelConversion )\n {\n // Only resample\n ResampleFloatBuffer(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels, // same as targetChannels in this case\n sourceFramesCount,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n if ( !needsResampling && needsChannelConversion )\n {\n // Only convert channels\n ConvertChannels(\n sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n sourceFramesCount);\n\n return sourceFramesCount;\n }\n\n // If we need both resampling and channel conversion\n // First resample, then convert channels\n var resampledBuffer = needsResampling ? new float[targetFramesCount * sourceChannels] : null;\n\n if ( needsResampling )\n {\n ResampleFloatBuffer(\n sourceSamples.Span,\n resampledBuffer.AsSpan(),\n sourceChannels,\n sourceFramesCount,\n targetFramesCount);\n }\n\n // Then convert channels\n ConvertChannels(\n needsResampling ? resampledBuffer.AsSpan() : sourceSamples.Span,\n targetSamples.Span,\n sourceChannels,\n targetChannels,\n targetFramesCount);\n\n return targetFramesCount;\n }\n\n /// \n /// Direct resampling of audio data without format conversion.\n /// \n private static int ResampleDirect(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Convert to float for processing\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Resample the float samples\n var resampledBuffer = new float[targetFramesCount * targetFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n // Serialize back to the target format\n SampleSerializer.Serialize(resampledBuffer, targetBuffer, targetFormat.BitsPerSample);\n\n return targetFramesCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Resamples floating-point audio samples.\n /// \n private static void ResampleFloatBuffer(\n ReadOnlySpan sourceBuffer,\n Span targetBuffer,\n ushort channels,\n int sourceFramesCount,\n int targetFramesCount)\n {\n // Calculate the step size for linear interpolation\n var step = (double)(sourceFramesCount - 1) / (targetFramesCount - 1);\n\n for ( var targetFrame = 0; targetFrame < targetFramesCount; targetFrame++ )\n {\n // Calculate source position (as a floating point value)\n var sourcePos = targetFrame * step;\n\n // Get indices of the two source frames to interpolate between\n var sourceFrameLow = (int)sourcePos;\n var sourceFrameHigh = Math.Min(sourceFrameLow + 1, sourceFramesCount - 1);\n\n // Calculate interpolation factor\n var fraction = (float)(sourcePos - sourceFrameLow);\n\n // Interpolate each channel\n for ( var channel = 0; channel < channels; channel++ )\n {\n var sourceLowIndex = sourceFrameLow * channels + channel;\n var sourceHighIndex = sourceFrameHigh * channels + channel;\n var targetIndex = targetFrame * channels + channel;\n\n // Linear interpolation\n targetBuffer[targetIndex] = Lerp(\n sourceBuffer[sourceLowIndex],\n sourceBuffer[sourceHighIndex],\n fraction);\n }\n }\n }\n\n /// \n /// Linear interpolation between two values.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static float Lerp(float a, float b, float t) { return a + (b - a) * t; }\n\n /// \n /// Converts mono float32 audio to stereo int16 PCM format.\n /// \n /// The mono float32 audio buffer.\n /// The target buffer to receive the stereo int16 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoFloat32ToStereoInt16(\n ReadOnlyMemory monoFloat32Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(32, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(16, sampleRate);\n\n return Convert(monoFloat32Buffer, targetBuffer, sourceFormat, targetFormat);\n }\n\n /// \n /// Converts mono int16 audio to stereo float32 PCM format.\n /// \n /// The mono int16 audio buffer.\n /// The target buffer to receive the stereo float32 PCM data.\n /// The sample rate of the audio (preserved in the conversion).\n /// The number of bytes written to the target buffer.\n public static int ConvertMonoInt16ToStereoFloat32(\n ReadOnlyMemory monoInt16Buffer,\n Memory targetBuffer,\n uint sampleRate = 44100)\n {\n var sourceFormat = AudioFormat.CreateMono(16, sampleRate);\n var targetFormat = AudioFormat.CreateStereo(32, sampleRate);\n\n // Use fast path for this specific conversion\n var framesCount = monoInt16Buffer.Length / sourceFormat.BytesPerFrame;\n var expectedTargetSize = framesCount * targetFormat.BytesPerFrame;\n\n if ( targetBuffer.Length < expectedTargetSize )\n {\n throw new ArgumentException(\"Target buffer is too small for the converted audio.\");\n }\n\n ConvertMonoInt16ToStereoFloat32Direct(monoInt16Buffer, targetBuffer, framesCount);\n\n return expectedTargetSize;\n }\n\n /// \n /// Optimized direct conversion from mono float32 to stereo int16.\n /// \n private static void ConvertMonoFloat32ToStereoInt16Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 4 bytes per float32\n var targetIndex = frame * 4; // 2 bytes per int16 * 2 channels\n\n // Read float32 value\n var floatValue = BinaryPrimitives.ReadSingleLittleEndian(sourceSpan.Slice(sourceIndex, 4));\n\n // Convert to int16 (with clamping)\n var int16Value = ClampToInt16(floatValue * 32767f);\n\n // Write the same value to both left and right channels\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex, 2), int16Value);\n BinaryPrimitives.WriteInt16LittleEndian(targetSpan.Slice(targetIndex + 2, 2), int16Value);\n }\n }\n\n /// \n /// Optimized direct conversion from stereo int16 to mono float32.\n /// \n private static void ConvertStereoInt16ToMonoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 4; // 2 bytes per int16 * 2 channels\n var targetIndex = frame * 4; // 4 bytes per float32\n\n // Read int16 values for left and right channels\n var leftValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n var rightValue = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex + 2, 2));\n\n // Convert to float32 and average the channels\n var floatValue = (leftValue + rightValue) * 0.5f / 32768f;\n\n // Write to target buffer\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n }\n }\n\n /// \n /// Optimized direct conversion from mono int16 to stereo float32.\n /// \n private static void ConvertMonoInt16ToStereoFloat32Direct(\n ReadOnlyMemory source,\n Memory target,\n int framesCount)\n {\n var sourceSpan = source.Span;\n var targetSpan = target.Span;\n\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2; // 2 bytes per int16\n var targetIndex = frame * 8; // 4 bytes per float32 * 2 channels\n\n // Read int16 value\n var int16Value = BinaryPrimitives.ReadInt16LittleEndian(sourceSpan.Slice(sourceIndex, 2));\n\n // Convert to float32\n var floatValue = int16Value / 32768f;\n\n // Write the same float value to both left and right channels\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex, 4), floatValue);\n BinaryPrimitives.WriteSingleLittleEndian(targetSpan.Slice(targetIndex + 4, 4), floatValue);\n }\n }\n\n /// \n /// General case conversion using intermediate float format.\n /// \n private static int ConvertGeneral(\n ReadOnlyMemory sourceBuffer,\n Memory targetBuffer,\n AudioFormat sourceFormat,\n AudioFormat targetFormat,\n int sourceFramesCount,\n int targetFramesCount,\n bool needsResampling)\n {\n // Deserialize to float samples - this will give us interleaved float samples\n var floatSamples = new float[sourceFramesCount * sourceFormat.Channels];\n SampleSerializer.Deserialize(sourceBuffer, floatSamples.AsMemory(), sourceFormat.BitsPerSample);\n\n // Perform resampling if needed\n Memory resampledSamples;\n int actualFrameCount;\n\n if ( needsResampling )\n {\n var resampledBuffer = new float[targetFramesCount * sourceFormat.Channels];\n ResampleFloatBuffer(\n floatSamples.AsSpan(),\n resampledBuffer.AsSpan(),\n sourceFormat.Channels,\n sourceFramesCount,\n targetFramesCount);\n\n resampledSamples = resampledBuffer;\n actualFrameCount = targetFramesCount;\n }\n else\n {\n resampledSamples = floatSamples;\n actualFrameCount = sourceFramesCount;\n }\n\n // Convert channel configuration if needed\n Memory convertedSamples;\n\n if ( sourceFormat.Channels != targetFormat.Channels )\n {\n var convertedBuffer = new float[actualFrameCount * targetFormat.Channels];\n ConvertChannels(\n resampledSamples.Span,\n convertedBuffer.AsSpan(),\n sourceFormat.Channels,\n targetFormat.Channels,\n actualFrameCount);\n\n convertedSamples = convertedBuffer;\n }\n else\n {\n // No channel conversion needed\n convertedSamples = resampledSamples;\n }\n\n // Serialize to the target format\n SampleSerializer.Serialize(convertedSamples, targetBuffer, targetFormat.BitsPerSample);\n\n return actualFrameCount * targetFormat.BytesPerFrame;\n }\n\n /// \n /// Converts between different channel configurations.\n /// \n private static void ConvertChannels(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n // If source and target have the same number of channels, just copy\n if ( sourceChannels == targetChannels )\n {\n source.CopyTo(target);\n\n return;\n }\n\n // Handle specific conversions with optimized implementations\n if ( sourceChannels == 1 && targetChannels == 2 )\n {\n // Mono to stereo conversion\n ConvertMonoToStereo(source, target, framesCount);\n }\n else if ( sourceChannels == 2 && targetChannels == 1 )\n {\n // Stereo to mono conversion\n ConvertStereoToMono(source, target, framesCount);\n }\n else\n {\n // More general conversion implementation\n ConvertChannelsGeneral(source, target, sourceChannels, targetChannels, framesCount);\n }\n }\n\n /// \n /// Converts mono audio to stereo by duplicating each sample.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertMonoToStereo(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceSample = source[frame];\n var targetIndex = frame * 2;\n\n target[targetIndex] = sourceSample; // Left channel\n target[targetIndex + 1] = sourceSample; // Right channel\n }\n }\n\n /// \n /// Converts stereo audio to mono by averaging the channels.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertStereoToMono(\n ReadOnlySpan source,\n Span target,\n int framesCount)\n {\n for ( var frame = 0; frame < framesCount; frame++ )\n {\n var sourceIndex = frame * 2;\n var leftSample = source[sourceIndex];\n var rightSample = source[sourceIndex + 1];\n\n target[frame] = (leftSample + rightSample) * 0.5f; // Average the channels\n }\n }\n\n /// \n /// General method for converting between different channel configurations.\n /// \n private static void ConvertChannelsGeneral(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int framesCount)\n {\n ConvertChannelsChunk(source, target, sourceChannels, targetChannels, 0, framesCount);\n }\n\n /// \n /// Converts a chunk of frames between different channel configurations.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static void ConvertChannelsChunk(\n ReadOnlySpan source,\n Span target,\n ushort sourceChannels,\n ushort targetChannels,\n int startFrame,\n int endFrame)\n {\n for ( var frame = startFrame; frame < endFrame; frame++ )\n {\n var sourceFrameOffset = frame * sourceChannels;\n var targetFrameOffset = frame * targetChannels;\n\n // Find the minimum of source and target channels\n var minChannels = Math.Min(sourceChannels, targetChannels);\n\n // Copy the available channels\n for ( var channel = 0; channel < minChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + channel];\n }\n\n // If target has more channels than source, duplicate the last channel\n for ( var channel = minChannels; channel < targetChannels; channel++ )\n {\n target[targetFrameOffset + channel] = source[sourceFrameOffset + (minChannels - 1)];\n }\n }\n }\n\n /// \n /// Clamps a float value to the range of a 16-bit integer.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static short ClampToInt16(float value)\n {\n if ( value > 32767f )\n {\n return 32767;\n }\n\n if ( value < -32768f )\n {\n return -32768;\n }\n\n return (short)value;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OnnxAudioSynthesizer.cs", "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of audio synthesis using ONNX models\n/// \npublic class OnnxAudioSynthesizer : IAudioSynthesizer\n{\n private readonly ITtsCache _cache;\n\n private readonly SemaphoreSlim _inferenceThrottle;\n\n private readonly IModelProvider _ittsModelProvider;\n\n private readonly ILogger _logger;\n\n private readonly IOptionsMonitor _options;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private bool _disposed;\n\n private IReadOnlyDictionary? _phonemeToIdMap;\n\n private InferenceSession? _synthesisSession;\n\n public OnnxAudioSynthesizer(\n IModelProvider ittsModelProvider,\n IKokoroVoiceProvider voiceProvider,\n ITtsCache cache,\n IOptionsMonitor options,\n ILogger logger)\n {\n _ittsModelProvider = ittsModelProvider ?? throw new ArgumentNullException(nameof(ittsModelProvider));\n _voiceProvider = voiceProvider ?? throw new ArgumentNullException(nameof(voiceProvider));\n _cache = cache ?? throw new ArgumentNullException(nameof(cache));\n _options = options ?? throw new ArgumentNullException(nameof(options));\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n // Create throttle to limit concurrent inference operations\n _inferenceThrottle = new SemaphoreSlim(\n Math.Max(1, Environment.ProcessorCount / 2), // Use half of available cores for inference\n Environment.ProcessorCount);\n\n _logger.LogInformation(\"Initialized ONNX audio synthesizer\");\n }\n\n /// \n /// Synthesizes audio from phonemes\n /// \n public async Task SynthesizeAsync(\n string phonemes,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(phonemes) )\n {\n return new AudioData(Array.Empty(), Array.Empty());\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n // Initialize lazily on first use\n await EnsureInitializedAsync(cancellationToken);\n\n // Get current options (to ensure we have the latest values)\n var currentOptions = options ?? _options.CurrentValue;\n\n // Validate phoneme length\n if ( phonemes.Length > currentOptions.MaxPhonemeLength )\n {\n _logger.LogWarning(\"Truncating phonemes to maximum length {MaxLength}\", currentOptions.MaxPhonemeLength);\n phonemes = phonemes.Substring(0, currentOptions.MaxPhonemeLength);\n }\n\n // Convert phonemes to tokens\n var tokens = ConvertPhonemesToTokens(phonemes);\n if ( tokens.Count == 0 )\n {\n _logger.LogWarning(\"No valid tokens generated from phonemes\");\n\n return new AudioData(Array.Empty(), Array.Empty());\n }\n\n // Get voice data\n var voice = await _voiceProvider.GetVoiceAsync(currentOptions.DefaultVoice, cancellationToken);\n\n // Create audio with throttling for inference\n await _inferenceThrottle.WaitAsync(cancellationToken);\n\n try\n {\n // Measure performance\n var timer = Stopwatch.StartNew();\n\n // Perform inference\n var (audioData, phonemeTimings) = await RunInferenceAsync(tokens, voice, options, cancellationToken);\n\n // Log performance metrics\n timer.Stop();\n LogPerformanceMetrics(timer.Elapsed, audioData.Length, phonemes.Length, options);\n\n return new AudioData(audioData, phonemeTimings);\n }\n finally\n {\n _inferenceThrottle.Release();\n }\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"Audio synthesis was canceled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during audio synthesis\");\n\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _synthesisSession?.Dispose();\n _synthesisSession = null;\n\n _phonemeToIdMap = null;\n _inferenceThrottle.Dispose();\n\n _disposed = true;\n\n await Task.CompletedTask;\n }\n\n /// \n /// Ensures the model and resources are initialized\n /// \n private async Task EnsureInitializedAsync(CancellationToken cancellationToken)\n {\n if ( _synthesisSession != null && _phonemeToIdMap != null )\n {\n return;\n }\n\n // Load model and resources\n await InitializeSessionAsync(cancellationToken);\n await LoadPhonemeMapAsync(cancellationToken);\n }\n\n /// \n /// Initializes the ONNX inference session\n /// \n private async Task InitializeSessionAsync(CancellationToken cancellationToken)\n {\n if ( _synthesisSession != null )\n {\n return;\n }\n\n _logger.LogInformation(\"Initializing synthesis model\");\n\n // Create optimized session options\n var sessionOptions = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Math.Max(1, Environment.ProcessorCount / 2),\n IntraOpNumThreads = Math.Max(1, Environment.ProcessorCount / 2),\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n try\n {\n sessionOptions.AppendExecutionProvider_CUDA();\n _logger.LogInformation(\"CUDA execution provider added successfully\");\n }\n catch (Exception ex)\n {\n _logger.LogWarning(\"CUDA execution provider not available: {Message}. Using CPU.\", ex.Message);\n }\n\n // Get model with retry mechanism\n var maxRetries = 3;\n Exception? lastException = null;\n\n for ( var attempt = 0; attempt < maxRetries; attempt++ )\n {\n try\n {\n var model = await _ittsModelProvider.GetModelAsync(ModelType.KokoroSynthesis, cancellationToken);\n var modelData = await model.GetDataAsync();\n\n _synthesisSession = new InferenceSession(modelData, sessionOptions);\n _logger.LogInformation(\"Synthesis model initialized successfully\");\n\n return;\n }\n catch (Exception ex)\n {\n lastException = ex;\n _logger.LogWarning(ex, \"Error initializing ONNX session (attempt {Attempt} of {MaxRetries}). Retrying...\",\n attempt + 1, maxRetries);\n\n if ( attempt < maxRetries - 1 )\n {\n // Exponential backoff\n await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)), cancellationToken);\n }\n }\n }\n\n // If we get here, all attempts failed\n throw new InvalidOperationException(\n $\"Failed to initialize ONNX session after {maxRetries} attempts\", lastException);\n }\n\n /// \n /// Loads the phoneme-to-ID mapping\n /// \n private async Task LoadPhonemeMapAsync(CancellationToken cancellationToken)\n {\n if ( _phonemeToIdMap != null )\n {\n return;\n }\n\n _logger.LogInformation(\"Loading phoneme mapping\");\n\n try\n {\n // Use cache for phoneme map to avoid repeated loading\n _phonemeToIdMap = await _cache.GetOrAddAsync(\"phoneme_map\", async ct =>\n {\n var model = await _ittsModelProvider.GetModelAsync(ModelType.KokoroPhonemeMappings, ct);\n var mapPath = model.Path;\n\n _logger.LogDebug(\"Loading phoneme mapping from {Path}\", mapPath);\n\n var lines = await File.ReadAllLinesAsync(mapPath, ct);\n\n // Initialize with capacity for better performance\n var mapping = new Dictionary(lines.Length);\n\n foreach ( var line in lines )\n {\n if ( string.IsNullOrWhiteSpace(line) || line.Length < 3 )\n {\n continue;\n }\n\n mapping[line[0]] = long.Parse(line[2..]);\n }\n\n _logger.LogInformation(\"Loaded {Count} phoneme mappings\", mapping.Count);\n\n return mapping;\n }, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n /* Ignored */\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error loading phoneme mapping\");\n\n throw;\n }\n }\n\n /// \n /// Converts phoneme characters to token IDs\n /// \n private List ConvertPhonemesToTokens(string phonemes)\n {\n // If no mapping loaded, can't convert\n if ( _phonemeToIdMap == null )\n {\n throw new InvalidOperationException(\"Phoneme map not initialized\");\n }\n\n // Pre-allocate with expected capacity\n var tokens = new List(phonemes.Length);\n\n foreach ( var phoneme in phonemes )\n {\n if ( _phonemeToIdMap.TryGetValue(phoneme, out var id) )\n {\n tokens.Add(id);\n }\n }\n\n return tokens;\n }\n\n /// \n /// Runs model inference to generate audio\n /// \n private async Task<(Memory AudioData, Memory PhonemeTimings)> RunInferenceAsync(\n List tokens,\n VoiceData voice,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default)\n {\n // Make sure session is initialized\n if ( _synthesisSession == null )\n {\n throw new InvalidOperationException(\"Synthesis session not initialized\");\n }\n\n // Get current options (to ensure we have the latest values)\n var currentOptions = options ?? _options.CurrentValue;\n\n // Create model inputs\n var modelInputs = CreateModelInputs(tokens, voice, currentOptions.DefaultSpeed);\n\n // Run inference\n using var results = _synthesisSession.Run(modelInputs);\n\n // Extract results\n var waveformTensor = results[0].AsTensor();\n var durationTensor = results[1].AsTensor();\n\n // Extract result data\n var waveformLength = waveformTensor.Dimensions.Length > 0 ? waveformTensor.Dimensions[0] : 0;\n\n var waveform = new float[waveformLength];\n var durations = new long[durationTensor.Length];\n\n // Copy data to results\n Buffer.BlockCopy(waveformTensor.ToArray(), 0, waveform, 0, waveformLength * sizeof(float));\n Buffer.BlockCopy(durationTensor.ToArray(), 0, durations, 0, durations.Length * sizeof(long));\n\n // Apply audio processing if needed\n if ( currentOptions.TrimSilence )\n {\n waveform = TrimSilence(waveform);\n }\n\n return (waveform, durations);\n }\n\n /// \n /// Creates input tensors for the synthesis model\n /// \n private List CreateModelInputs(List tokens, VoiceData voice, float speed)\n {\n // Add boundary tokens (BOS/EOS)\n var tokenArray = ArrayPool.Shared.Rent(tokens.Count + 2);\n\n try\n {\n // BOS token\n tokenArray[0] = 0;\n\n // Copy tokens\n tokens.CopyTo(tokenArray, 1);\n\n // EOS token\n tokenArray[tokens.Count + 1] = 0;\n\n // Create tensors\n var inputTokens = new DenseTensor(\n tokenArray.AsMemory(0, tokens.Count + 2),\n new[] { 1, tokens.Count + 2 });\n\n var styleInput = voice.GetEmbedding(inputTokens.Dimensions).ToArray();\n var voiceEmbedding = new DenseTensor(styleInput, new[] { 1, styleInput.Length });\n\n var speedTensor = new DenseTensor(\n new[] { speed },\n new[] { 1 });\n\n // Return named tensors\n return new List { NamedOnnxValue.CreateFromTensor(\"input_ids\", inputTokens), NamedOnnxValue.CreateFromTensor(\"style\", voiceEmbedding), NamedOnnxValue.CreateFromTensor(\"speed\", speedTensor) };\n }\n finally\n {\n // Always return the rented array\n ArrayPool.Shared.Return(tokenArray);\n }\n }\n\n /// \n /// Trims silence from the beginning and end of audio data\n /// \n private float[] TrimSilence(float[] audioData, float threshold = 0.01f, int minSamples = 512)\n {\n if ( audioData.Length <= minSamples * 2 )\n {\n return audioData;\n }\n\n // Find start (first sample above threshold)\n var startIndex = 0;\n for ( var i = 0; i < audioData.Length - minSamples; i++ )\n {\n if ( Math.Abs(audioData[i]) > threshold )\n {\n startIndex = Math.Max(0, i - minSamples);\n\n break;\n }\n }\n\n // Find end (last sample above threshold)\n var endIndex = audioData.Length - 1;\n for ( var i = audioData.Length - 1; i >= minSamples; i-- )\n {\n if ( Math.Abs(audioData[i]) > threshold )\n {\n endIndex = Math.Min(audioData.Length - 1, i + minSamples);\n\n break;\n }\n }\n\n // If no significant audio found, return original\n if ( startIndex >= endIndex )\n {\n return audioData;\n }\n\n // Create trimmed array\n var newLength = endIndex - startIndex + 1;\n var result = new float[newLength];\n Array.Copy(audioData, startIndex, result, 0, newLength);\n\n return result;\n }\n\n /// \n /// Logs performance metrics for inference\n /// \n private void LogPerformanceMetrics(TimeSpan elapsed, int audioLength, int phonemeCount, KokoroVoiceOptions? options = null)\n {\n // Get current options to ensure we have the latest sample rate\n var currentOptions = options ?? _options.CurrentValue;\n\n var audioDuration = audioLength / (float)currentOptions.SampleRate;\n var elapsedSeconds = elapsed.TotalSeconds;\n var speedup = elapsedSeconds > 0 ? audioDuration / elapsedSeconds : 0;\n\n _logger.LogInformation(\n \"Generated {AudioDuration:F2}s audio for {PhonemeCount} phonemes in {Elapsed:F2}s (x{Speedup:F2} real-time)\",\n audioDuration, phonemeCount, elapsedSeconds, speedup);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsEngine.cs", "using System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.LLM;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Main TTS engine implementation\n/// \npublic class TtsEngine : ITtsEngine\n{\n private readonly IList _audioFilters;\n\n private readonly ILogger _logger;\n\n private readonly IOptionsMonitor _options;\n\n private readonly IPhonemizer _phonemizer;\n\n private readonly IAudioSynthesizer _synthesizer;\n\n private readonly IList _textFilters;\n\n private readonly ITextProcessor _textProcessor;\n\n private readonly SemaphoreSlim _throttle;\n\n private bool _disposed;\n\n public TtsEngine(\n ITextProcessor textProcessor,\n IPhonemizer phonemizer,\n IAudioSynthesizer synthesizer,\n IOptionsMonitor options,\n IEnumerable audioFilters,\n IEnumerable textFilters,\n ILoggerFactory loggerFactory)\n {\n _textProcessor = textProcessor ?? throw new ArgumentNullException(nameof(textProcessor));\n _phonemizer = phonemizer ?? throw new ArgumentNullException(nameof(phonemizer));\n _synthesizer = synthesizer ?? throw new ArgumentNullException(nameof(synthesizer));\n _options = options;\n _audioFilters = audioFilters.OrderByDescending(x => x.Priority).ToList();\n _textFilters = textFilters.OrderByDescending(x => x.Priority).ToList();\n _logger = loggerFactory?.CreateLogger() ?? throw new ArgumentNullException(nameof(loggerFactory));\n\n _throttle = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount);\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _throttle.Dispose();\n _disposed = true;\n }\n\n public async Task SynthesizeStreamingAsync(\n ChannelReader inputReader,\n ChannelWriter outputWriter,\n Guid turnId,\n Guid sessionId,\n KokoroVoiceOptions? options = null,\n CancellationToken cancellationToken = default\n )\n {\n var textBuffer = new StringBuilder(4096);\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n\n try\n {\n await foreach ( var (_, _, _, textChunk) in inputReader.ReadAllAsync(cancellationToken).ConfigureAwait(false) )\n {\n if ( cancellationToken.IsCancellationRequested )\n {\n break;\n }\n\n if ( string.IsNullOrEmpty(textChunk) )\n {\n continue;\n }\n\n textBuffer.Append(textChunk);\n var currentText = textBuffer.ToString();\n\n var processedText = await _textProcessor.ProcessAsync(currentText, cancellationToken);\n var sentences = processedText.Sentences;\n\n if ( sentences.Count <= 1 )\n {\n continue;\n }\n\n // Process all sentences except the last one(which might be incomplete)\n for ( var i = 0; i < sentences.Count - 1; i++ )\n {\n var sentence = sentences[i].Trim();\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n continue;\n }\n\n await foreach ( var segment in ProcessSentenceAsync(sentence, options, cancellationToken) )\n {\n ApplyAudioFilters(segment);\n\n if ( firstChunk )\n {\n var firstChunkEvent = new TtsStreamStartEvent(sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, cancellationToken).ConfigureAwait(false);\n\n firstChunk = false;\n }\n\n var chunkEvent = new TtsChunkEvent(sessionId, turnId, DateTimeOffset.UtcNow, segment);\n await outputWriter.WriteAsync(chunkEvent, cancellationToken).ConfigureAwait(false);\n }\n }\n\n textBuffer.Clear();\n textBuffer.Append(sentences[^1]);\n }\n\n var remainingText = textBuffer.ToString().Trim();\n if ( !string.IsNullOrEmpty(remainingText) )\n {\n await foreach ( var segment in ProcessSentenceAsync(remainingText, options, cancellationToken) )\n {\n ApplyAudioFilters(segment);\n\n if ( firstChunk )\n {\n var firstChunkEvent = new TtsStreamStartEvent(sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, cancellationToken).ConfigureAwait(false);\n\n firstChunk = false;\n }\n \n var chunkEvent = new TtsChunkEvent(sessionId, turnId, DateTimeOffset.UtcNow, segment);\n await outputWriter.WriteAsync(chunkEvent, cancellationToken).ConfigureAwait(false);\n }\n }\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n\n await outputWriter.WriteAsync(new ErrorOutputEvent(sessionId, turnId, DateTimeOffset.UtcNow, ex), cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n if ( !firstChunk )\n {\n await outputWriter.WriteAsync(new TtsStreamEndEvent(sessionId, turnId, DateTimeOffset.UtcNow, completedReason), cancellationToken).ConfigureAwait(false);\n }\n }\n\n return completedReason;\n }\n\n /// \n /// Processes a single sentence for synthesis\n /// \n private async IAsyncEnumerable ProcessSentenceAsync(\n string sentence,\n KokoroVoiceOptions? options = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n yield break;\n }\n\n await _throttle.WaitAsync(cancellationToken);\n\n var currentOptions = options ?? _options.CurrentValue;\n\n try\n {\n // Apply text filters before processing\n var processedText = sentence;\n var textFilterResults = new List(_textFilters.Count);\n\n foreach ( var textFilter in _textFilters )\n {\n var filterResult = await textFilter.ProcessAsync(processedText, cancellationToken);\n processedText = filterResult.ProcessedText;\n\n textFilterResults.Add(filterResult);\n }\n\n // Get phonemes\n var phonemeResult = await _phonemizer.ToPhonemesAsync(processedText, cancellationToken);\n\n // Process each phoneme chunk\n foreach ( var phonemeChunk in SplitPhonemes(phonemeResult.Phonemes, 510) )\n {\n // Get audio\n var audioData = await _synthesizer.SynthesizeAsync(\n phonemeChunk,\n currentOptions,\n cancellationToken);\n\n // Apply timing\n ApplyTokenTimings(\n phonemeResult.Tokens,\n currentOptions,\n audioData.PhonemeTimings);\n\n // Return segment\n var segment = new AudioSegment(\n audioData.Samples,\n options?.SampleRate ?? _options.CurrentValue.SampleRate,\n phonemeResult.Tokens);\n\n for ( var index = 0; index < _textFilters.Count; index++ )\n {\n var textFilter = _textFilters[index];\n var textFilterResult = textFilterResults[index];\n await textFilter.PostProcessAsync(textFilterResult, segment, cancellationToken);\n }\n\n yield return segment;\n }\n }\n finally\n {\n _throttle.Release();\n }\n }\n\n /// \n /// Splits phonemes into manageable chunks\n /// \n private IEnumerable SplitPhonemes(string phonemes, int maxLength)\n {\n if ( string.IsNullOrEmpty(phonemes) )\n {\n yield return string.Empty;\n\n yield break;\n }\n\n if ( phonemes.Length <= maxLength )\n {\n yield return phonemes;\n\n yield break;\n }\n\n var currentIndex = 0;\n while ( currentIndex < phonemes.Length )\n {\n var remainingLength = phonemes.Length - currentIndex;\n var chunkSize = Math.Min(maxLength, remainingLength);\n\n // Find a good breakpoint (whitespace or punctuation)\n if ( chunkSize < remainingLength && chunkSize > 10 )\n {\n // Look backwards from the end to find a good breakpoint\n for ( var i = currentIndex + chunkSize - 1; i > currentIndex + 10; i-- )\n {\n if ( char.IsWhiteSpace(phonemes[i]) || IsPunctuation(phonemes[i]) )\n {\n chunkSize = i - currentIndex + 1;\n\n break;\n }\n }\n }\n\n yield return phonemes.Substring(currentIndex, chunkSize);\n currentIndex += chunkSize;\n }\n }\n\n private bool IsPunctuation(char c) { return \".,:;!?-—()[]{}\\\"'\".Contains(c); }\n\n private void ApplyAudioFilters(AudioSegment audioSegment)\n {\n foreach ( var audioFilter in _audioFilters )\n {\n audioFilter.Process(audioSegment);\n }\n }\n\n /// \n /// Applies timing information to tokens\n /// \n private void ApplyTokenTimings(\n IReadOnlyList tokens,\n KokoroVoiceOptions options,\n ReadOnlyMemory phonemeTimings)\n {\n // Skip if no timing information\n if ( tokens.Count == 0 || phonemeTimings.Length < 3 )\n {\n return;\n }\n\n var timingsSpan = phonemeTimings.Span;\n\n // Magic scaling factor for timing conversion\n const int TIME_DIVISOR = 80;\n\n // Start with boundary tokens (often token)\n var leftTime = options.TrimSilence ? 0 : 2 * Math.Max(0, timingsSpan[0] - 3);\n var rightTime = leftTime;\n\n // Process each token\n var timingIndex = 1;\n foreach ( var token in tokens )\n {\n // Skip tokens without phonemes\n if ( string.IsNullOrEmpty(token.Phonemes) )\n {\n // Handle whitespace timing specially\n if ( token.Whitespace == \" \" && timingIndex + 1 < timingsSpan.Length )\n {\n timingIndex++;\n leftTime = rightTime + timingsSpan[timingIndex];\n rightTime = leftTime + timingsSpan[timingIndex];\n timingIndex++;\n }\n\n continue;\n }\n\n // Calculate end index for this token's phonemes\n var endIndex = timingIndex + (token.Phonemes?.Length ?? 0);\n if ( endIndex >= phonemeTimings.Length )\n {\n continue;\n }\n\n // Start time for this token\n var startTime = (double)leftTime / TIME_DIVISOR;\n\n // Sum durations for all phonemes in this token\n var tokenDuration = 0L;\n for ( var i = timingIndex; i < endIndex && i < timingsSpan.Length; i++ )\n {\n tokenDuration += timingsSpan[i];\n }\n\n // Handle whitespace after token\n var spaceDuration = token.Whitespace == \" \" && endIndex < timingsSpan.Length\n ? timingsSpan[endIndex]\n : 0;\n\n // Calculate end time\n leftTime = rightTime + 2 * tokenDuration + spaceDuration;\n var endTime = (double)leftTime / TIME_DIVISOR;\n rightTime = leftTime + spaceDuration;\n\n // Add token with timing\n token.StartTs = startTime;\n token.EndTs = endTime;\n\n // Move to next token's timing\n timingIndex = endIndex + (token.Whitespace == \" \" ? 1 : 0);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/Text/Subtitles/SubtitleProcessor.cs", "using System.Text;\n\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.Text.Subtitles;\n\n/// \n/// Processes raw AudioSegments into structured SubtitleSegments containing lines and words\n/// with calculated timing and layout information.\n/// \npublic class SubtitleProcessor(TextMeasurer textMeasurer, float defaultWordDuration = 0.3f)\n{\n private readonly float _defaultWordDuration = Math.Max(0.01f, defaultWordDuration);\n\n public SubtitleSegment ProcessSegment(AudioSegment audioSegment, float segmentAbsoluteStartTime)\n {\n if ( audioSegment?.Tokens == null || audioSegment.Tokens.Count == 0 )\n {\n return new SubtitleSegment(audioSegment!, segmentAbsoluteStartTime, string.Empty);\n }\n\n // --- 1. Build Full Text ---\n\n var textBuilder = new StringBuilder();\n foreach ( var token in audioSegment.Tokens )\n {\n textBuilder.Append(token.Text);\n textBuilder.Append(token.Whitespace);\n }\n\n var fullText = textBuilder.ToString();\n\n var processedSegment = new SubtitleSegment(audioSegment, segmentAbsoluteStartTime, fullText);\n var currentLine = new SubtitleLine(0, 0);\n var currentLineWidth = 0f;\n var cumulativeTimeOffset = 0f;\n\n // --- 2. Iterate Tokens, Calculate Timing & Layout ---\n for ( var i = 0; i < audioSegment.Tokens.Count; i++ )\n {\n var token = audioSegment.Tokens[i];\n var wordText = token.Text + token.Whitespace;\n var wordSize = textMeasurer.MeasureText(wordText);\n\n // --- 3. Line Breaking ---\n if ( currentLineWidth > 0 && currentLineWidth + wordSize.X > textMeasurer.AvailableWidth )\n {\n processedSegment.AddLine(currentLine);\n currentLine = new SubtitleLine(processedSegment.Lines.Count, 0); // TODO: Get segment index properly if needed\n currentLineWidth = 0f;\n }\n\n // --- 4. Word Timing Calculation ---\n float wordStartTimeOffset;\n float wordDuration;\n\n if ( token.StartTs.HasValue )\n {\n wordStartTimeOffset = (float)token.StartTs.Value;\n if ( token.EndTs.HasValue )\n {\n // Case 1: Start and End provided\n wordDuration = (float)(token.EndTs.Value - token.StartTs.Value);\n }\n else\n {\n // Case 2: Only Start provided - Estimate duration until next token or use default\n var nextTokenStartOffset = FindNextTokenStartOffset(audioSegment, i);\n if ( nextTokenStartOffset > wordStartTimeOffset )\n {\n wordDuration = nextTokenStartOffset - wordStartTimeOffset;\n }\n else\n {\n wordDuration = _defaultWordDuration;\n }\n }\n }\n else\n {\n // Case 3: No Start provided - Estimate start based on previous word's end or cumulative time\n wordStartTimeOffset = cumulativeTimeOffset;\n var nextTokenStartOffset = FindNextTokenStartOffset(audioSegment, i);\n if ( nextTokenStartOffset > wordStartTimeOffset )\n {\n wordDuration = nextTokenStartOffset - wordStartTimeOffset;\n }\n else\n {\n wordDuration = _defaultWordDuration;\n }\n }\n\n wordDuration = Math.Max(0.01f, wordDuration);\n\n cumulativeTimeOffset = wordStartTimeOffset + wordDuration;\n\n // --- 5. Create Word Info ---\n var wordInfo = new SubtitleWordInfo { Text = wordText, Size = wordSize, AbsoluteStartTime = segmentAbsoluteStartTime + wordStartTimeOffset, Duration = wordDuration };\n\n currentLine.AddWord(wordInfo);\n currentLineWidth += wordSize.X;\n }\n\n if ( currentLine.Words.Count > 0 )\n {\n processedSegment.AddLine(currentLine);\n }\n\n return processedSegment;\n }\n\n private float FindNextTokenStartOffset(AudioSegment segment, int currentTokenIndex)\n {\n for ( var j = currentTokenIndex + 1; j < segment.Tokens.Count; j++ )\n {\n if ( segment.Tokens[j].StartTs.HasValue )\n {\n return (float)segment.Tokens[j].StartTs!.Value;\n }\n }\n\n // Indicate not found or end of segment\n // Return a value that ensures the calling logic uses the default duration.\n // Returning -1 or float.MaxValue could work, depending on how it's used.\n // Let's return a value <= the current offset to trigger default duration.\n return segment.Tokens[currentTokenIndex].StartTs.HasValue ? (float)segment.Tokens[currentTokenIndex].StartTs!.Value : 0f;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismOffscreenSurface_OpenGLES2.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\n/// \n/// オフスクリーン描画用構造体\n/// \npublic class CubismOffscreenSurface_OpenGLES2(OpenGLApi gl)\n{\n /// \n /// 引数によって設定されたカラーバッファか?\n /// \n private bool _isColorBufferInherited;\n\n /// \n /// 旧フレームバッファ\n /// \n private int _oldFBO;\n\n /// \n /// レンダリングターゲットとしてのアドレス\n /// \n public int RenderTexture { get; private set; }\n\n /// \n /// 描画の際使用するテクスチャとしてのアドレス\n /// \n public int ColorBuffer { get; private set; }\n\n /// \n /// Create時に指定された幅\n /// \n public int BufferWidth { get; private set; }\n\n /// \n /// Create時に指定された高さ\n /// \n public int BufferHeight { get; private set; }\n\n /// \n /// 指定の描画ターゲットに向けて描画開始\n /// \n /// 0以上の場合、EndDrawでこの値をglBindFramebufferする\n public void BeginDraw(int restoreFBO = -1)\n {\n if ( RenderTexture == 0 )\n {\n return;\n }\n\n // バックバッファのサーフェイスを記憶しておく\n if ( restoreFBO < 0 )\n {\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out _oldFBO);\n }\n else\n {\n _oldFBO = restoreFBO;\n }\n\n //マスク用RenderTextureをactiveにセット\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, RenderTexture);\n }\n\n /// \n /// 描画終了\n /// \n public void EndDraw()\n {\n if ( RenderTexture == 0 )\n {\n return;\n }\n\n // 描画対象を戻す\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, _oldFBO);\n }\n\n /// \n /// レンダリングターゲットのクリア\n /// 呼ぶ場合はBeginDrawの後で呼ぶこと\n /// \n /// 赤(0.0~1.0)\n /// 緑(0.0~1.0)\n /// 青(0.0~1.0)\n /// α(0.0~1.0)\n public void Clear(float r, float g, float b, float a)\n {\n // マスクをクリアする\n gl.ClearColor(r, g, b, a);\n gl.Clear(gl.GL_COLOR_BUFFER_BIT);\n }\n\n /// \n /// CubismOffscreenFrame作成\n /// \n /// 作成するバッファ幅\n /// 作成するバッファ高さ\n /// 0以外の場合、ピクセル格納領域としてcolorBufferを使用する\n public bool CreateOffscreenSurface(int displayBufferWidth, int displayBufferHeight, int colorBuffer = 0)\n {\n // 一旦削除\n DestroyOffscreenSurface();\n\n // 新しく生成する\n if ( colorBuffer == 0 )\n {\n ColorBuffer = gl.GenTexture();\n\n gl.BindTexture(gl.GL_TEXTURE_2D, ColorBuffer);\n gl.TexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, displayBufferWidth, displayBufferHeight, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, 0);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);\n gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);\n gl.BindTexture(gl.GL_TEXTURE_2D, 0);\n\n _isColorBufferInherited = false;\n }\n else\n {\n // 指定されたものを使用\n ColorBuffer = colorBuffer;\n\n _isColorBufferInherited = true;\n }\n\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out var tmpFramebufferObject);\n\n var ret = gl.GenFramebuffer();\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, ret);\n gl.FramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, ColorBuffer, 0);\n gl.BindFramebuffer(gl.GL_FRAMEBUFFER, tmpFramebufferObject);\n\n RenderTexture = ret;\n\n BufferWidth = displayBufferWidth;\n BufferHeight = displayBufferHeight;\n\n // 成功\n return true;\n }\n\n /// \n /// CubismOffscreenFrameの削除\n /// \n public void DestroyOffscreenSurface()\n {\n if ( !_isColorBufferInherited && ColorBuffer != 0 )\n {\n gl.DeleteTexture(ColorBuffer);\n ColorBuffer = 0;\n }\n\n if ( RenderTexture != 0 )\n {\n gl.DeleteFramebuffer(RenderTexture);\n RenderTexture = 0;\n }\n }\n\n /// \n /// 現在有効かどうか\n /// \n public bool IsValid() { return RenderTexture != 0; }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/App/TouchManager.cs", "namespace PersonaEngine.Lib.Live2D.App;\n\npublic class TouchManager\n{\n /// \n /// 前回の値から今回の値へのxの移動距離。\n /// \n private float _deltaX;\n\n /// \n /// 前回の値から今回の値へのyの移動距離。\n /// \n private float _deltaY;\n\n /// \n /// フリップが有効かどうか\n /// \n private bool _flipAvailable;\n\n /// \n /// 2本以上でタッチしたときの指の距離\n /// \n private float _lastTouchDistance;\n\n /// \n /// シングルタッチ時のxの値\n /// \n private float _lastX;\n\n /// \n /// ダブルタッチ時の一つ目のxの値\n /// \n private float _lastX1;\n\n /// \n /// ダブルタッチ時の二つ目のxの値\n /// \n private float _lastX2;\n\n /// \n /// シングルタッチ時のyの値\n /// \n private float _lastY;\n\n /// \n /// ダブルタッチ時の一つ目のyの値\n /// \n private float _lastY1;\n\n /// \n /// ダブルタッチ時の二つ目のyの値\n /// \n private float _lastY2;\n\n /// \n /// このフレームで掛け合わせる拡大率。拡大操作中以外は1。\n /// \n private float _scale;\n\n /// \n /// タッチを開始した時のyの値\n /// \n private float _startX;\n\n /// \n /// タッチを開始した時のxの値\n /// \n private float _startY;\n\n /// \n /// シングルタッチ時はtrue\n /// \n private bool _touchSingle;\n\n public TouchManager() { _scale = 1.0f; }\n\n public float GetCenterX() { return _lastX; }\n\n public float GetCenterY() { return _lastY; }\n\n public float GetDeltaX() { return _deltaX; }\n\n public float GetDeltaY() { return _deltaY; }\n\n public float GetStartX() { return _startX; }\n\n public float GetStartY() { return _startY; }\n\n public float GetScale() { return _scale; }\n\n public float GetX() { return _lastX; }\n\n public float GetY() { return _lastY; }\n\n public float GetX1() { return _lastX1; }\n\n public float GetY1() { return _lastY1; }\n\n public float GetX2() { return _lastX2; }\n\n public float GetY2() { return _lastY2; }\n\n public bool IsSingleTouch() { return _touchSingle; }\n\n public bool IsFlickAvailable() { return _flipAvailable; }\n\n public void DisableFlick() { _flipAvailable = false; }\n\n /// \n /// タッチ開始時イベント\n /// \n /// タッチした画面のyの値\n /// タッチした画面のxの値\n public void TouchesBegan(float deviceX, float deviceY)\n {\n _lastX = deviceX;\n _lastY = deviceY;\n _startX = deviceX;\n _startY = deviceY;\n _lastTouchDistance = -1.0f;\n _flipAvailable = true;\n _touchSingle = true;\n }\n\n /// \n /// ドラッグ時のイベント\n /// \n /// タッチした画面のxの値\n /// タッチした画面のyの値\n public void TouchesMoved(float deviceX, float deviceY)\n {\n _lastX = deviceX;\n _lastY = deviceY;\n _lastTouchDistance = -1.0f;\n _touchSingle = true;\n }\n\n /// \n /// ドラッグ時のイベント\n /// \n /// 1つめのタッチした画面のxの値\n /// 1つめのタッチした画面のyの値\n /// 2つめのタッチした画面のxの値\n /// 2つめのタッチした画面のyの値\n public void TouchesMoved(float deviceX1, float deviceY1, float deviceX2, float deviceY2)\n {\n var distance = CalculateDistance(deviceX1, deviceY1, deviceX2, deviceY2);\n var centerX = (deviceX1 + deviceX2) * 0.5f;\n var centerY = (deviceY1 + deviceY2) * 0.5f;\n\n if ( _lastTouchDistance > 0.0f )\n {\n _scale = MathF.Pow(distance / _lastTouchDistance, 0.75f);\n _deltaX = CalculateMovingAmount(deviceX1 - _lastX1, deviceX2 - _lastX2);\n _deltaY = CalculateMovingAmount(deviceY1 - _lastY1, deviceY2 - _lastY2);\n }\n else\n {\n _scale = 1.0f;\n _deltaX = 0.0f;\n _deltaY = 0.0f;\n }\n\n _lastX = centerX;\n _lastY = centerY;\n _lastX1 = deviceX1;\n _lastY1 = deviceY1;\n _lastX2 = deviceX2;\n _lastY2 = deviceY2;\n _lastTouchDistance = distance;\n _touchSingle = false;\n }\n\n /// \n /// フリックの距離測定\n /// \n /// フリック距離\n public float GetFlickDistance() { return CalculateDistance(_startX, _startY, _lastX, _lastY); }\n\n /// \n /// 点1から点2への距離を求める\n /// \n /// 1つめのタッチした画面のxの値\n /// 1つめのタッチした画面のyの値\n /// 2つめのタッチした画面のxの値\n /// 2つめのタッチした画面のyの値\n /// 2点の距離\n public static float CalculateDistance(float x1, float y1, float x2, float y2) { return MathF.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); }\n\n /// \n /// 二つの値から、移動量を求める。\n /// 違う方向の場合は移動量0。同じ方向の場合は、絶対値が小さい方の値を参照する\n /// \n /// 1つめの移動量\n /// 2つめの移動量\n /// 小さい方の移動量\n public static float CalculateMovingAmount(float v1, float v2)\n {\n if ( v1 > 0.0f != v2 > 0.0f )\n {\n return 0.0f;\n }\n\n var sign = v1 > 0.0f ? 1.0f : -1.0f;\n var absoluteValue1 = MathF.Abs(v1);\n var absoluteValue2 = MathF.Abs(v2);\n\n return sign * (absoluteValue1 < absoluteValue2 ? absoluteValue1 : absoluteValue2);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Model/CubismModelUserData.cs", "using System.Text.Json;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Model;\n\n/// \n/// ユーザデータをロード、管理、検索インターフェイス、解放までを行う。\n/// \npublic class CubismModelUserData\n{\n public const string ArtMesh = \"ArtMesh\";\n\n public const string Meta = \"Meta\";\n\n public const string UserDataCount = \"UserDataCount\";\n\n public const string TotalUserDataSize = \"TotalUserDataSize\";\n\n public const string UserData = \"UserData\";\n\n public const string Target = \"Target\";\n\n public const string Id = \"Id\";\n\n public const string Value = \"Value\";\n\n /// \n /// ユーザデータ構造体配列\n /// \n private readonly List _userDataNodes = [];\n\n /// \n /// 閲覧リスト保持\n /// \n public readonly List ArtMeshUserDataNodes = [];\n\n /// \n /// userdata3.jsonをパースする。\n /// \n /// userdata3.jsonが読み込まれいるバッファ\n public CubismModelUserData(string data)\n {\n using var stream = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n var obj = JsonSerializer.Deserialize(stream, CubismModelUserDataObjContext.Default.CubismModelUserDataObj)\n ?? throw new Exception(\"Load UserData error\");\n\n var typeOfArtMesh = CubismFramework.CubismIdManager.GetId(ArtMesh);\n\n var nodeCount = obj.Meta.UserDataCount;\n\n for ( var i = 0; i < nodeCount; i++ )\n {\n var node = obj.UserData[i];\n CubismModelUserDataNode addNode = new() { TargetId = CubismFramework.CubismIdManager.GetId(node.Id), TargetType = CubismFramework.CubismIdManager.GetId(node.Target), Value = CubismFramework.CubismIdManager.GetId(node.Value) };\n _userDataNodes.Add(addNode);\n\n if ( addNode.TargetType == typeOfArtMesh )\n {\n ArtMeshUserDataNodes.Add(addNode);\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/PcmResampler.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\npublic class PcmResampler\n{\n // Constants for audio format\n private const int BYTES_PER_SAMPLE = 2;\n\n private const int MAX_FRAME_SIZE = 1920;\n\n private readonly float[] _filterCoefficients;\n\n private readonly int _filterDelay;\n\n // Filter configuration\n private readonly int _filterTaps;\n\n private readonly float[] _floatHistory;\n\n private readonly short[] _history;\n\n // Sample rate configuration\n\n // Pre-allocated working buffers\n private readonly short[] _inputSamples;\n\n private int _historyLength;\n\n // State tracking\n private float _position = 0.0f;\n\n public PcmResampler(int inputSampleRate = 48000, int outputSampleRate = 16000)\n {\n if ( inputSampleRate <= 0 || outputSampleRate <= 0 )\n {\n throw new ArgumentException(\"Sample rates must be positive values\");\n }\n\n InputSampleRate = inputSampleRate;\n OutputSampleRate = outputSampleRate;\n ResampleRatio = (float)InputSampleRate / OutputSampleRate;\n\n _filterTaps = DetermineOptimalFilterTaps(ResampleRatio);\n _filterDelay = _filterTaps / 2;\n\n var cutoffFrequency = Math.Min(0.45f * OutputSampleRate, 0.9f * OutputSampleRate / 2) / InputSampleRate;\n _filterCoefficients = GenerateLowPassFilter(_filterTaps, cutoffFrequency);\n\n _history = new short[_filterTaps + 10];\n _floatHistory = new float[_filterTaps + 10];\n _historyLength = 0;\n\n _inputSamples = new short[MAX_FRAME_SIZE];\n }\n\n public float ResampleRatio { get; }\n\n public int InputSampleRate { get; }\n\n public int OutputSampleRate { get; }\n\n private int DetermineOptimalFilterTaps(float ratio)\n {\n if ( Math.Abs(ratio - Math.Round(ratio)) < 0.01f )\n {\n return Math.Max(24, (int)(12 * ratio));\n }\n\n return Math.Max(36, (int)(18 * ratio));\n }\n\n private float[] GenerateLowPassFilter(int taps, float cutoff)\n {\n var coefficients = new float[taps];\n var center = taps / 2;\n\n var sum = 0.0;\n for ( var i = 0; i < taps; i++ )\n {\n if ( i == center )\n {\n coefficients[i] = (float)(2.0 * Math.PI * cutoff);\n }\n else\n {\n var x = 2.0 * Math.PI * cutoff * (i - center);\n coefficients[i] = (float)(Math.Sin(x) / x);\n }\n\n var window = 0.42 - 0.5 * Math.Cos(2.0 * Math.PI * i / (taps - 1))\n + 0.08 * Math.Cos(4.0 * Math.PI * i / (taps - 1));\n\n coefficients[i] *= (float)window;\n\n sum += coefficients[i];\n }\n\n for ( var i = 0; i < taps; i++ )\n {\n coefficients[i] /= (float)sum;\n }\n\n return coefficients;\n }\n\n public int Process(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length / BYTES_PER_SAMPLE;\n ConvertToShorts(input, _inputSamples, inputSampleCount);\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples * BYTES_PER_SAMPLE )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetSampleWithHistory(sampleIndex, _inputSamples, inputSampleCount);\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n if ( outputIndex < maxOutputSamples )\n {\n BinaryPrimitives.WriteInt16LittleEndian(\n output.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateHistory(_inputSamples, inputSampleCount);\n _position -= inputSampleCount;\n\n return outputIndex * BYTES_PER_SAMPLE;\n }\n\n public int Process(Stream input, Memory output)\n {\n var buffer = new byte[MAX_FRAME_SIZE * BYTES_PER_SAMPLE];\n var bytesRead = input.Read(buffer, 0, buffer.Length);\n\n return Process(buffer.AsSpan(0, bytesRead), output.Span);\n }\n\n public int ProcessInPlace(Span buffer)\n {\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length / BYTES_PER_SAMPLE;\n\n // Make a copy of the input for processing\n Span inputCopy = stackalloc short[inputSampleCount];\n for ( var i = 0; i < inputSampleCount; i++ )\n {\n inputCopy[i] = BinaryPrimitives.ReadInt16LittleEndian(buffer.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // Calculate positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n short sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _history[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n var outputValue = (short)Math.Clamp((int)Math.Round(sum), short.MinValue, short.MaxValue);\n BinaryPrimitives.WriteInt16LittleEndian(\n buffer.Slice(outputIndex * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE), outputValue);\n\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n // We need to keep the input history despite having processed in-place\n UpdateHistory(inputCopy.ToArray(), inputSampleCount);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount * BYTES_PER_SAMPLE;\n }\n\n public int ProcessFloat(ReadOnlySpan input, Span output)\n {\n var inputSampleCount = input.Length;\n\n var maxOutputSamples = (int)Math.Ceiling(inputSampleCount / ResampleRatio) + 2;\n if ( output.Length < maxOutputSamples )\n {\n throw new ArgumentException(\"Output buffer is too small for the resampled data\");\n }\n\n var outputIndex = 0;\n\n while ( _position < inputSampleCount )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(_position);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n var sample = GetFloatSampleWithHistory(sampleIndex, input);\n sum += sample * _filterCoefficients[tap];\n }\n\n if ( outputIndex < maxOutputSamples )\n {\n output[outputIndex] = sum;\n outputIndex++;\n }\n\n _position += ResampleRatio;\n }\n\n UpdateFloatHistory(input);\n _position -= inputSampleCount;\n\n return outputIndex;\n }\n\n public int ProcessFloatInPlace(Span buffer)\n {\n // For in-place, we must work backward to avoid overwriting unprocessed input\n if ( ResampleRatio < 1.0f )\n {\n throw new InvalidOperationException(\"In-place resampling only supports downsampling (input rate > output rate)\");\n }\n\n var inputSampleCount = buffer.Length;\n var expectedOutputCount = (int)Math.Ceiling(inputSampleCount / ResampleRatio);\n\n // First, store the full input for history and reference\n var inputCopy = new float[inputSampleCount];\n buffer.CopyTo(inputCopy);\n\n // Calculate sample positions and work from last to first\n var outputIndex = expectedOutputCount - 1;\n var lastPosition = _position + (inputSampleCount - 1) - ResampleRatio * (expectedOutputCount - 1);\n\n while ( lastPosition >= 0 && outputIndex >= 0 )\n {\n float sum = 0;\n var baseIndex = (int)Math.Floor(lastPosition);\n\n for ( var tap = 0; tap < _filterTaps; tap++ )\n {\n var sampleIndex = baseIndex - _filterDelay + tap;\n float sample;\n\n if ( sampleIndex >= 0 && sampleIndex < inputSampleCount )\n {\n sample = inputCopy[sampleIndex];\n }\n else if ( sampleIndex < 0 && -sampleIndex <= _historyLength )\n {\n sample = _floatHistory[_historyLength + sampleIndex];\n }\n else\n {\n sample = 0f;\n }\n\n sum += sample * _filterCoefficients[tap];\n }\n\n buffer[outputIndex] = sum;\n outputIndex--;\n lastPosition -= ResampleRatio;\n }\n\n UpdateFloatHistory(inputCopy);\n _position = _position + inputSampleCount - ResampleRatio * expectedOutputCount;\n\n return expectedOutputCount;\n }\n\n private short GetSampleWithHistory(int index, short[] inputSamples, int inputSampleCount)\n {\n if ( index >= 0 && index < inputSampleCount )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _history[_historyLength + index];\n }\n\n return 0;\n }\n\n private float GetFloatSampleWithHistory(int index, ReadOnlySpan inputSamples)\n {\n if ( index >= 0 && index < inputSamples.Length )\n {\n return inputSamples[index];\n }\n\n if ( index < 0 && -index <= _historyLength )\n {\n return _floatHistory[_historyLength + index];\n }\n\n return 0f;\n }\n\n private void UpdateHistory(short[] currentFrame, int frameLength)\n {\n var samplesToKeep = Math.Min(frameLength, _history.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _history.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_history, _historyLength - unusedHistorySamples, _history, 0, unusedHistorySamples);\n }\n\n Array.Copy(currentFrame, frameLength - samplesToKeep, _history, unusedHistorySamples, samplesToKeep);\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _history.Length);\n }\n\n private void UpdateFloatHistory(ReadOnlySpan currentFrame)\n {\n var samplesToKeep = Math.Min(currentFrame.Length, _floatHistory.Length);\n\n if ( samplesToKeep > 0 )\n {\n var unusedHistorySamples = Math.Min(_historyLength, _floatHistory.Length - samplesToKeep);\n if ( unusedHistorySamples > 0 )\n {\n Array.Copy(_floatHistory, _historyLength - unusedHistorySamples, _floatHistory, 0, unusedHistorySamples);\n }\n\n for ( var i = 0; i < samplesToKeep; i++ )\n {\n _floatHistory[unusedHistorySamples + i] = currentFrame[currentFrame.Length - samplesToKeep + i];\n }\n\n _historyLength = unusedHistorySamples + samplesToKeep;\n }\n\n _historyLength = Math.Min(_historyLength, _floatHistory.Length);\n }\n\n private void ConvertToShorts(ReadOnlySpan input, short[] output, int sampleCount)\n {\n for ( var i = 0; i < sampleCount; i++ )\n {\n output[i] = BinaryPrimitives.ReadInt16LittleEndian(input.Slice(i * BYTES_PER_SAMPLE, BYTES_PER_SAMPLE));\n }\n }\n\n public void Reset()\n {\n _position = 0;\n _historyLength = 0;\n Array.Clear(_history, 0, _history.Length);\n Array.Clear(_floatHistory, 0, _floatHistory.Length);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/MicrophoneConfigEditor.cs", "using System.Diagnostics;\nusing System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for Microphone section configuration.\n/// Allows selection of the audio input device.\n/// \npublic class MicrophoneConfigEditor : ConfigSectionEditorBase\n{\n private const string DefaultDeviceDisplayName = \"(Default Device)\"; // Display name for null/empty device\n\n // --- Dependencies ---\n private readonly IMicrophone _microphone; // Dependency to get device list\n\n private List _availableDevices = new();\n\n // --- State ---\n private MicrophoneConfiguration _currentConfig;\n\n private bool _loadingDevices = false;\n\n private string? _selectedDeviceName; // Can be null for default device\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The configuration manager.\n /// The editor state manager.\n /// The microphone service.\n public MicrophoneConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IMicrophone microphone)\n : base(configManager, stateManager)\n {\n _microphone = microphone ?? throw new ArgumentNullException(nameof(microphone));\n\n // Load initial configuration\n LoadConfiguration();\n }\n\n // --- ConfigSectionEditorBase Implementation ---\n\n /// \n /// Gets the key for the configuration section managed by this editor.\n /// \n public override string SectionKey => \"Microphone\"; // Or your specific key\n\n /// \n /// Gets the display name for this editor section.\n /// \n public override string DisplayName => \"Microphone Settings\";\n\n /// \n /// Initializes the editor, loading necessary data like available devices.\n /// \n public override void Initialize()\n {\n LoadAvailableDevices(); // Load devices on initialization\n }\n\n /// \n /// Renders the ImGui UI for the microphone configuration.\n /// \n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // --- Device Selection Section ---\n ImGui.Spacing();\n ImGui.SeparatorText(\"Input Device Selection\");\n ImGui.Spacing();\n\n ImGui.BeginGroup(); // Group controls for alignment\n {\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Input Device:\");\n ImGui.SameLine(120); // Adjust spacing as needed\n\n // Combo box for device selection\n ImGui.SetNextItemWidth(availWidth - 120 - 100); // Width calculation: Available - Label - Refresh Button\n\n var currentSelectionDisplay = string.IsNullOrEmpty(_selectedDeviceName)\n ? DefaultDeviceDisplayName\n : _selectedDeviceName;\n\n if ( _loadingDevices )\n {\n // Show loading state\n ImGui.BeginDisabled();\n var loadingText = \"Loading devices...\";\n // Use InputText as a visual placeholder during loading\n ImGui.InputText(\"##DeviceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n // Actual combo box\n if ( ImGui.BeginCombo(\"##DeviceSelector\", currentSelectionDisplay) )\n {\n // Add \"(Default Device)\" option first\n var isDefaultSelected = string.IsNullOrEmpty(_selectedDeviceName);\n if ( ImGui.Selectable(DefaultDeviceDisplayName, isDefaultSelected) )\n {\n if ( _selectedDeviceName != null ) // Check if changed\n {\n _selectedDeviceName = null;\n UpdateConfiguration();\n }\n }\n\n if ( isDefaultSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n\n // Add actual devices if available\n if ( _availableDevices.Count == 0 && !_loadingDevices )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No input devices found.\");\n }\n else\n {\n foreach ( var device in _availableDevices )\n {\n var isSelected = device == _selectedDeviceName;\n if ( ImGui.Selectable(device, isSelected) )\n {\n if ( _selectedDeviceName != device ) // Check if changed\n {\n _selectedDeviceName = device;\n UpdateConfiguration();\n }\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n // Refresh Button\n ImGui.SameLine(0, 10); // Add spacing before button\n if ( ImGui.Button(\"Refresh##Dev\", new Vector2(80, 0)) ) // Unique ID for button\n {\n LoadAvailableDevices();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh the list of available input devices.\");\n }\n }\n\n ImGui.EndGroup(); // End device selection group\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n // --- Action Buttons ---\n // Center the buttons roughly\n float buttonWidth = 150;\n var totalButtonWidth = buttonWidth * 2 + 10; // Two buttons + spacing\n var initialPadding = (availWidth - totalButtonWidth) * 0.5f;\n if ( initialPadding < 0 )\n {\n initialPadding = 0;\n }\n\n ImGui.SetCursorPosX(initialPadding);\n\n // Reset Button\n if ( ImGui.Button(\"Reset\", new Vector2(buttonWidth, 0)) )\n {\n ResetToDefaults();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset microphone settings to default values.\");\n }\n\n ImGui.SameLine(0, 10); // Spacing between buttons\n\n // Save Button (Disabled if no changes)\n var hasChanges = StateManager.HasUnsavedChanges; // Check unsaved state\n if ( !hasChanges )\n {\n ImGui.BeginDisabled();\n }\n\n if ( ImGui.Button(\"Save\", new Vector2(buttonWidth, 0)) )\n {\n SaveConfiguration();\n }\n\n if ( ImGui.IsItemHovered() && hasChanges )\n {\n ImGui.SetTooltip(\"Save the current microphone settings.\");\n }\n\n if ( !hasChanges )\n {\n ImGui.EndDisabled();\n }\n }\n\n /// \n /// Updates the editor state (currently unused for this simple editor).\n /// \n /// Time elapsed since the last frame.\n public override void Update(float deltaTime)\n {\n // No per-frame update logic needed for this editor yet\n }\n\n /// \n /// Handles configuration changes, reloading if necessary.\n /// \n /// Event arguments containing change details.\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args); // Call base implementation\n\n // Reload configuration if the source indicates a full reload\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n // Optionally reload devices if the config might affect them,\n // though usually device list is independent of config.\n // LoadAvailableDevices();\n }\n }\n\n /// \n /// Disposes resources used by the editor (currently none specific).\n /// \n public override void Dispose()\n {\n // Unsubscribe from events if any were added\n base.Dispose(); // Call base implementation\n }\n\n // --- Configuration Management ---\n\n /// \n /// Loads the microphone configuration from the configuration manager.\n /// \n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(SectionKey)\n ?? new MicrophoneConfiguration(); // Get or create default\n\n // Update local state from loaded config\n _selectedDeviceName = _currentConfig.DeviceName;\n\n // Ensure the UI reflects the loaded state without marking as changed initially\n MarkAsSaved(); // Reset change tracking after loading\n }\n\n /// \n /// Fetches the list of available microphone devices.\n /// \n private void LoadAvailableDevices()\n {\n if ( _loadingDevices )\n {\n return; // Prevent concurrent loading\n }\n\n try\n {\n _loadingDevices = true;\n // Consider adding an ActiveOperation to StateManager if this takes time\n // var operation = new ActiveOperation(\"load-mic-devices\", \"Loading Microphones\");\n // StateManager.RegisterActiveOperation(operation);\n\n // Get devices using the injected service\n _availableDevices = _microphone.GetAvailableDevices().ToList();\n\n // Ensure the currently selected device still exists\n if ( !string.IsNullOrEmpty(_selectedDeviceName) &&\n !_availableDevices.Contains(_selectedDeviceName) )\n {\n Debug.WriteLine($\"Warning: Configured microphone '{_selectedDeviceName}' not found. Reverting to default.\");\n // Optionally notify the user here\n _selectedDeviceName = null; // Revert to default\n UpdateConfiguration(); // Update the config state\n }\n\n // StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading microphone devices: {ex.Message}\");\n _availableDevices = new List(); // Clear list on error\n // Optionally show an error message to the user via ImGui or logging\n }\n finally\n {\n _loadingDevices = false;\n }\n }\n\n /// \n /// Updates the configuration object and notifies the manager.\n /// \n private void UpdateConfiguration()\n {\n // Create the updated configuration record\n var updatedConfig = _currentConfig with // Use record 'with' expression\n {\n DeviceName = _selectedDeviceName\n };\n\n // Check if the configuration actually changed before updating\n if ( !_currentConfig.Equals(updatedConfig) )\n {\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(_currentConfig, SectionKey);\n MarkAsChanged(); // Mark that there are unsaved changes\n }\n }\n\n /// \n /// Saves the current configuration changes.\n /// \n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved(); // Mark changes as saved\n }\n\n /// \n /// Resets the microphone configuration to default values.\n /// \n private void ResetToDefaults()\n {\n var defaultConfig = new MicrophoneConfiguration(); // Create default config\n\n // Update local state\n _selectedDeviceName = defaultConfig.DeviceName; // Should be null\n\n // Update configuration only if it differs from current\n if ( !_currentConfig.Equals(defaultConfig) )\n {\n _currentConfig = defaultConfig;\n ConfigManager.UpdateConfiguration(_currentConfig, SectionKey);\n MarkAsChanged(); // Mark changes needing save\n }\n else\n {\n // If already default, just ensure saved state is correct\n MarkAsSaved();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnxSimd.cs", "using System.Buffers;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\nusing System.Runtime.Intrinsics.X86;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnxSimd : IF0Predictor, IDisposable\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n // Preallocated buffers\n private readonly float[] _inputBatchBuffer;\n\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Flattened arrays for better cache locality and SIMD operations\n private readonly float[] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[] _tempBuffer; // Used for temporary calculations\n\n private readonly float[] _transitionMatrix;\n\n private readonly float[] _transOutBuffer;\n\n private readonly float[] _valueBuffer;\n\n // SIMD vector size based on hardware\n private readonly int _vectorSize;\n\n public CrepeOnnxSimd(string modelPath)\n {\n // Determine vector size based on hardware capabilities\n _vectorSize = Vector.Count;\n\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n // Use hardware specific optimizations if available\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Initialize preallocated buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Initialize flattened buffers for Viterbi algorithm\n _logProbBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE * PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE * PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = new float[PITCH_BINS * PITCH_BINS];\n _transOutBuffer = new float[PITCH_BINS * PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n _tempBuffer = new float[Math.Max(BATCH_SIZE, PITCH_BINS) * _vectorSize];\n\n // Initialize logPInitBuffer with equal probabilities\n var logInitProb = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n FillArray(_logPInitBuffer, logInitProb);\n\n // Initialize transition matrix\n InitializeTransitionMatrix(_transitionMatrix);\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n if ( length > f0Output.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Rent buffer from pool for periodicity data\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = pdBuffer.AsSpan(0, length);\n var wavSpan = wav.Span;\n var f0Span = f0Output.Span.Slice(0, length);\n\n // Process audio to extract F0\n Crepe(wavSpan, f0Span, pdSpan);\n\n // Apply post-processing with SIMD\n ApplyPeriodicityThreshold(f0Span, pdSpan, length);\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var totalFrames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < totalFrames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, totalFrames - b);\n\n // Fill the batch input buffer with SIMD\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing with SIMD\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection padding\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection padding\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame using SIMD\n NormalizeAvx(frame);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeSimd(Span input)\n {\n // 1. Calculate mean using SIMD\n float sum = 0;\n var vectorCount = input.Length / _vectorSize;\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var v = new Vector(input.Slice(i * _vectorSize, _vectorSize));\n sum += Vector.Sum(v);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n sum += input[i];\n }\n\n var mean = sum / input.Length;\n\n // 2. Subtract mean and calculate variance using SIMD\n float variance = 0;\n var meanVector = new Vector(mean);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var centered = v - meanVector;\n centered.CopyTo(slice);\n variance += Vector.Sum(centered * centered);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] -= mean;\n variance += input[i] * input[i];\n }\n\n // 3. Calculate stddev and normalize\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVector = new Vector(stddev);\n\n for ( var i = 0; i < vectorCount; i++ )\n {\n var slice = input.Slice(i * _vectorSize, _vectorSize);\n var v = new Vector(slice);\n var normalized = v / stddevVector;\n normalized.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < input.Length; i++ )\n {\n input[i] /= stddev;\n }\n }\n\n // Hardware-specific optimization for AVX2-capable systems\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void NormalizeAvx(Span input)\n {\n if ( !Avx.IsSupported || input.Length < 8 )\n {\n NormalizeSimd(input);\n\n return;\n }\n\n unsafe\n {\n fixed (float* pInput = input)\n {\n // Calculate sum using AVX\n var sumVec = Vector256.Zero;\n var avxVectorCount = input.Length / 8;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n sumVec = Avx.Add(sumVec, v);\n }\n\n // Horizontal sum\n var sumArray = stackalloc float[8];\n Avx.Store(sumArray, sumVec);\n\n float sum = 0;\n for ( var i = 0; i < 8; i++ )\n {\n sum += sumArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n sum += pInput[i];\n }\n\n var mean = sum / input.Length;\n var meanVec = Vector256.Create(mean);\n\n // Subtract mean and compute variance\n var varianceVec = Vector256.Zero;\n\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var centered = Avx.Subtract(v, meanVec);\n Avx.Store(pInput + i * 8, centered);\n varianceVec = Avx.Add(varianceVec, Avx.Multiply(centered, centered));\n }\n\n // Get variance\n var varArray = stackalloc float[8];\n Avx.Store(varArray, varianceVec);\n\n float variance = 0;\n for ( var i = 0; i < 8; i++ )\n {\n variance += varArray[i];\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] -= mean;\n variance += pInput[i] * pInput[i];\n }\n\n var stddev = MathF.Sqrt(variance / input.Length);\n stddev = Math.Max(stddev, 1e-10f);\n\n var stddevVec = Vector256.Create(stddev);\n\n // Normalize\n for ( var i = 0; i < avxVectorCount; i++ )\n {\n var v = Avx.LoadVector256(pInput + i * 8);\n var normalized = Avx.Divide(v, stddevVec);\n Avx.Store(pInput + i * 8, normalized);\n }\n\n // Handle remainder\n for ( var i = avxVectorCount * 8; i < input.Length; i++ )\n {\n pInput[i] /= stddev;\n }\n }\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor using SIMD where possible\n for ( var i = 0; i < batchSize; i++ )\n {\n var inputOffset = i * WINDOW_SIZE;\n var vectorCount = WINDOW_SIZE / _vectorSize;\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var vectorOffset = v * _vectorSize;\n var source = new Vector(_inputBatchBuffer.AsSpan(inputOffset + vectorOffset, _vectorSize));\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n _inputTensor[i, vectorOffset + j] = source[j];\n }\n }\n\n // Handle remainder\n for ( var j = vectorCount * _vectorSize; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[inputOffset + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Apply frequency range limitation using SIMD where possible\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n ApplyFrequencyRangeLimit(probabilities, outputSize, minidx, maxidx);\n\n // Make a safe copy of the spans since we can't capture them in parallel operations\n var f0Array = new float[f0.Length];\n var pdArray = new float[pd.Length];\n f0.CopyTo(f0Array);\n pd.CopyTo(pdArray);\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0Array, pdArray, outputSize, offset);\n\n // Copy results back\n for ( var i = 0; i < outputSize; i++ )\n {\n if ( offset + i < f0.Length )\n {\n f0[offset + i] = f0Array[offset + i];\n pd[offset + i] = pdArray[offset + i];\n }\n }\n }\n\n private void ApplyFrequencyRangeLimit(float[] probabilities, int outputSize, int minIdx, int maxIdx)\n {\n // Set values outside the frequency range to negative infinity\n Parallel.For(0, outputSize, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Handle first part (below minIdx)\n for ( var i = 0; i < minIdx; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n\n // Handle second part (above maxIdx)\n for ( var i = maxIdx; i < PITCH_BINS; i++ )\n {\n probabilities[baseIdx + i] = float.NegativeInfinity;\n }\n });\n }\n\n private void DecodeViterbi(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n // Transfer probabilities to logProbBuffer and apply softmax\n Buffer.BlockCopy(probabilities, 0, _logProbBuffer, 0, nSteps * PITCH_BINS * sizeof(float));\n\n // Apply softmax with SIMD\n SoftmaxSimd(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n ApplyLogToProbs(_logProbBuffer, nSteps);\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[i] = _logProbBuffer[i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm (forward pass)\n for ( var t = 1; t < nSteps; t++ )\n {\n ViterbiForward(t, nSteps);\n }\n\n // Find the most likely final state\n var maxI = FindArgMax(_valueBuffer, (nSteps - 1) * PITCH_BINS, PITCH_BINS);\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[(t + 1) * PITCH_BINS + _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values and apply periodicity\n ConvertToF0(probabilities, f0, pd, nSteps, offset);\n }\n\n private void SoftmaxSimd(float[] data, int nSteps)\n {\n Parallel.For(0, nSteps, t =>\n {\n var baseIdx = t * PITCH_BINS;\n\n // Find max for numerical stability\n var max = float.NegativeInfinity;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n max = Math.Max(max, data[baseIdx + i]);\n }\n\n // Compute exp(x - max) and sum\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[baseIdx + i] = MathF.Exp(data[baseIdx + i] - max);\n sum += data[baseIdx + i];\n }\n\n // Normalize\n var invSum = 1.0f / sum;\n var vecCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var idx = baseIdx + v * _vectorSize;\n var values = new Vector(data.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n data[idx + j] = normalized[j];\n }\n }\n\n // Handle remainder\n for ( var i = baseIdx + vecCount * _vectorSize; i < baseIdx + PITCH_BINS; i++ )\n {\n data[i] *= invSum;\n }\n });\n }\n\n private void ApplyLogToProbs(float[] data, int nSteps)\n {\n var totalSize = nSteps * PITCH_BINS;\n var vecCount = totalSize / _vectorSize;\n var dataSpan = data.AsSpan(0, totalSize);\n\n for ( var v = 0; v < vecCount; v++ )\n {\n var slice = dataSpan.Slice(v * _vectorSize, _vectorSize);\n var values = new Vector(slice);\n var logValues = Vector.Log(values + new Vector(float.Epsilon));\n logValues.CopyTo(slice);\n }\n\n // Handle remainder\n for ( var i = vecCount * _vectorSize; i < totalSize; i++ )\n {\n data[i] = MathF.Log(data[i] + float.Epsilon);\n }\n }\n\n private void ViterbiForward(int t, int nSteps)\n {\n var baseIdxCurrent = t * PITCH_BINS;\n var baseIdxPrev = (t - 1) * PITCH_BINS;\n\n // Fixed number of threads to avoid thread contention\n var threadCount = Math.Min(Environment.ProcessorCount, PITCH_BINS);\n\n Parallel.For(0, threadCount, threadIdx =>\n {\n // Each thread processes a chunk of states\n var statesPerThread = (PITCH_BINS + threadCount - 1) / threadCount;\n var startState = threadIdx * statesPerThread;\n var endState = Math.Min(startState + statesPerThread, PITCH_BINS);\n\n for ( var j = startState; j < endState; j++ )\n {\n var maxI = 0;\n var maxVal = float.NegativeInfinity;\n\n // Find max transition - this could be further vectorized for specific hardware\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n var transVal = _valueBuffer[baseIdxPrev + k] + _transitionMatrix[j * PITCH_BINS + k];\n if ( transVal > maxVal )\n {\n maxVal = transVal;\n maxI = k;\n }\n }\n\n _ptrBuffer[baseIdxCurrent + j] = maxI;\n _valueBuffer[baseIdxCurrent + j] = _logProbBuffer[baseIdxCurrent + j] + maxVal;\n }\n });\n }\n\n private int FindArgMax(float[] data, int offset, int length)\n {\n var maxIdx = 0;\n var maxVal = float.NegativeInfinity;\n\n for ( var i = 0; i < length; i++ )\n {\n if ( data[offset + i] > maxVal )\n {\n maxVal = data[offset + i];\n maxIdx = i;\n }\n }\n\n return maxIdx;\n }\n\n private void ConvertToF0(float[] probabilities, float[] f0, float[] pd, int nSteps, int offset)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n if ( offset + t >= f0.Length )\n {\n break;\n }\n\n var bin = _stateBuffer[t];\n var periodicity = probabilities[t * PITCH_BINS + bin];\n var frequency = ConvertBinToFrequency(bin);\n\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n\n private void ApplyPeriodicityThreshold(Span f0, Span pd, int length)\n {\n const float threshold = 0.1f;\n var vecCount = length / _vectorSize;\n\n // Use SIMD for bulk processing\n for ( var v = 0; v < vecCount; v++ )\n {\n var offset = v * _vectorSize;\n var pdSlice = pd.Slice(offset, _vectorSize);\n var f0Slice = f0.Slice(offset, _vectorSize);\n\n var pdVec = new Vector(pdSlice);\n var thresholdVec = new Vector(threshold);\n var zeroVec = new Vector(0.0f);\n var f0Vec = new Vector(f0Slice);\n\n // Where pd < threshold, set f0 to 0\n var mask = Vector.LessThan(pdVec, thresholdVec);\n var result = Vector.ConditionalSelect(mask, zeroVec, f0Vec);\n\n result.CopyTo(f0Slice);\n }\n\n // Handle remainder with scalar code\n for ( var i = vecCount * _vectorSize; i < length; i++ )\n {\n if ( pd[i] < threshold )\n {\n f0[i] = 0;\n }\n }\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use thread-local window buffers for parallel processing\n Parallel.For(0, length, i =>\n {\n // Allocate a local median buffer for each thread\n var localMedianBuffer = new float[windowSize];\n\n // Get window values\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - radius;\n k = Math.Clamp(k, 0, length - 1);\n localMedianBuffer[j] = original[k];\n }\n\n // Simple sort for small window\n Array.Sort(localMedianBuffer, 0, windowSize);\n result[i] = localMedianBuffer[radius];\n });\n\n // Copy results back to the span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n var original = ArrayPool.Shared.Rent(data.Length);\n var result = ArrayPool.Shared.Rent(data.Length);\n try\n {\n // Copy to array for processing\n data.CopyTo(original.AsSpan(0, data.Length));\n var radius = windowSize / 2;\n var length = data.Length;\n\n // Use arrays instead of spans for parallel processing\n Parallel.For(0, length, i =>\n {\n float sum = 0;\n for ( var j = -radius; j <= radius; j++ )\n {\n var k = Math.Clamp(i + j, 0, length - 1);\n sum += original[k];\n }\n\n result[i] = sum / windowSize;\n });\n\n // Copy back to span\n new Span(result, 0, data.Length).CopyTo(data);\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n ArrayPool.Shared.Return(result);\n }\n }\n\n private void InitializeTransitionMatrix(float[] transitionMatrix)\n {\n Parallel.For(0, PITCH_BINS, y =>\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n float v = 12 - Math.Abs(x - y);\n v = Math.Max(v, 0);\n transitionMatrix[y * PITCH_BINS + x] = v;\n sum += v;\n }\n\n // Normalize and pre-apply log\n var invSum = 1.0f / sum;\n var vectorCount = PITCH_BINS / _vectorSize;\n var invSumVec = new Vector(invSum);\n var epsilonVec = new Vector(float.Epsilon);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n var idx = y * PITCH_BINS + v * _vectorSize;\n var values = new Vector(transitionMatrix.AsSpan(idx, _vectorSize));\n var normalized = values * invSumVec;\n var logValues = Vector.Log(normalized + epsilonVec);\n\n for ( var j = 0; j < _vectorSize; j++ )\n {\n transitionMatrix[idx + j] = logValues[j];\n }\n }\n\n // Handle remainder\n for ( var x = vectorCount * _vectorSize; x < PITCH_BINS; x++ )\n {\n var idx = y * PITCH_BINS + x;\n transitionMatrix[idx] = transitionMatrix[idx] * invSum;\n transitionMatrix[idx] = MathF.Log(transitionMatrix[idx] + float.Epsilon);\n }\n });\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private float ConvertBinToFrequency(int bin)\n {\n const float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n\n return 10 * MathF.Pow(2, cents / 1200);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void FillArray(Span array, float value)\n {\n var vectorCount = array.Length / _vectorSize;\n var valueVec = new Vector(value);\n\n for ( var v = 0; v < vectorCount; v++ )\n {\n valueVec.CopyTo(array.Slice(v * _vectorSize, _vectorSize));\n }\n\n // Handle remainder\n for ( var i = vectorCount * _vectorSize; i < array.Length; i++ )\n {\n array[i] = value;\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/CrepeOnnx.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class CrepeOnnx : IF0Predictor\n{\n private const int SAMPLE_RATE = 16000;\n\n private const int WINDOW_SIZE = 1024;\n\n private const int PITCH_BINS = 360;\n\n private const int HOP_LENGTH = SAMPLE_RATE / 100; // 10ms\n\n private const int BATCH_SIZE = 512;\n\n private readonly float[] _inputBatchBuffer;\n\n // Preallocated buffers for zero-allocation processing\n private readonly DenseTensor _inputTensor;\n\n private readonly float[] _logPInitBuffer;\n\n // Additional preallocated buffers for Viterbi decoding\n private readonly float[,] _logProbBuffer;\n\n private readonly float[] _medianBuffer;\n\n private readonly int[,] _ptrBuffer;\n\n private readonly InferenceSession _session;\n\n private readonly int[] _stateBuffer;\n\n private readonly float[,] _transitionMatrix;\n\n private readonly float[,] _transOutBuffer;\n\n private readonly float[,] _valueBuffer;\n\n private readonly float[] _windowBuffer;\n\n public CrepeOnnx(string modelPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_FATAL\n };\n\n options.AppendExecutionProvider_CPU();\n\n _session = new InferenceSession(modelPath, options);\n\n // Preallocate buffers\n _inputBatchBuffer = new float[BATCH_SIZE * WINDOW_SIZE];\n _inputTensor = new DenseTensor(new[] { BATCH_SIZE, WINDOW_SIZE });\n _windowBuffer = new float[WINDOW_SIZE];\n _medianBuffer = new float[5]; // For median filtering with window size 5\n\n // Preallocate Viterbi algorithm buffers\n _logProbBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _valueBuffer = new float[BATCH_SIZE, PITCH_BINS];\n _ptrBuffer = new int[BATCH_SIZE, PITCH_BINS];\n _logPInitBuffer = new float[PITCH_BINS];\n _transitionMatrix = CreateTransitionMatrix();\n _transOutBuffer = new float[PITCH_BINS, PITCH_BINS];\n _stateBuffer = new int[BATCH_SIZE];\n\n // Initialize _logPInitBuffer with equal probabilities\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _logPInitBuffer[i] = (float)Math.Log(1.0f / PITCH_BINS + float.Epsilon);\n }\n }\n\n public void Dispose() { _session?.Dispose(); }\n\n public void ComputeF0(ReadOnlyMemory wav, Memory f0Output, int length)\n {\n var wavSpan = wav.Span;\n var outputSpan = f0Output.Span;\n\n if ( length > outputSpan.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(f0Output));\n }\n\n // Preallocate periodicity data buffer\n var pdBuffer = ArrayPool.Shared.Rent(length);\n try\n {\n var pdSpan = new Span(pdBuffer, 0, length);\n\n // Process the audio to extract F0\n Crepe(wavSpan, outputSpan.Slice(0, length), pdSpan);\n\n // Apply post-processing\n for ( var i = 0; i < length; i++ )\n {\n if ( pdSpan[i] < 0.1 )\n {\n outputSpan[i] = 0;\n }\n }\n }\n finally\n {\n ArrayPool.Shared.Return(pdBuffer);\n }\n }\n\n private void Crepe(ReadOnlySpan x, Span f0, Span pd)\n {\n var total_frames = 1 + x.Length / HOP_LENGTH;\n\n for ( var b = 0; b < total_frames; b += BATCH_SIZE )\n {\n var currentBatchSize = Math.Min(BATCH_SIZE, total_frames - b);\n\n // Fill the batch input buffer\n FillBatch(x, b, currentBatchSize);\n\n // Run inference on the batch\n var probabilities = Run(currentBatchSize);\n\n // Decode the probabilities into F0 values\n Decode(probabilities, f0, pd, currentBatchSize, b);\n }\n\n // Apply post-processing\n MedianFilter(pd, 3);\n MeanFilter(f0, 3);\n }\n\n private void FillBatch(ReadOnlySpan x, int batchOffset, int batchSize)\n {\n for ( var i = 0; i < batchSize; i++ )\n {\n var frameIndex = batchOffset + i;\n var inputOffset = i * WINDOW_SIZE;\n FillFrame(x, _inputBatchBuffer.AsSpan(inputOffset, WINDOW_SIZE), frameIndex);\n }\n }\n\n private void FillFrame(ReadOnlySpan x, Span frame, int frameIndex)\n {\n var pad = WINDOW_SIZE / 2;\n var start = frameIndex * HOP_LENGTH - pad;\n\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n var k = start + j;\n float v = 0;\n\n if ( k < 0 )\n {\n // Reflection\n k = -k;\n }\n\n if ( k >= x.Length )\n {\n // Reflection\n k = x.Length - 1 - (k - x.Length);\n }\n\n if ( k >= 0 && k < x.Length )\n {\n v = x[k];\n }\n\n frame[j] = v;\n }\n\n // Normalize the frame\n Normalize(frame);\n }\n\n private void Normalize(Span input)\n {\n // Mean center and scale\n float sum = 0;\n for ( var j = 0; j < input.Length; j++ )\n {\n sum += input[j];\n }\n\n var mean = sum / input.Length;\n float stdValue = 0;\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] - mean;\n stdValue += input[j] * input[j];\n }\n\n stdValue = stdValue / input.Length;\n stdValue = (float)Math.Sqrt(stdValue);\n\n if ( stdValue < 1e-10 )\n {\n stdValue = 1e-10f;\n }\n\n for ( var j = 0; j < input.Length; j++ )\n {\n input[j] = input[j] / stdValue;\n }\n }\n\n private float[] Run(int batchSize)\n {\n // Copy the batch data to the input tensor\n for ( var i = 0; i < batchSize; i++ )\n {\n for ( var j = 0; j < WINDOW_SIZE; j++ )\n {\n _inputTensor[i, j] = _inputBatchBuffer[i * WINDOW_SIZE + j];\n }\n }\n\n var inputs = new List { NamedOnnxValue.CreateFromTensor(\"input\", _inputTensor) };\n\n using var results = _session.Run(inputs);\n\n return results[0].AsTensor().ToArray();\n }\n\n private void Decode(float[] probabilities, Span f0, Span pd, int outputSize, int offset)\n {\n // Remove frequencies outside of allowable range\n const int minidx = 39; // 50hz\n const int maxidx = 308; // 2006hz\n\n for ( var t = 0; t < outputSize; t++ )\n {\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n if ( i < minidx || i >= maxidx )\n {\n probabilities[t * PITCH_BINS + i] = float.NegativeInfinity;\n }\n }\n }\n\n // Use Viterbi algorithm to decode the probabilities\n DecodeViterbi(probabilities, f0, pd, outputSize, offset);\n }\n\n private void DecodeViterbi(float[] probabilities, Span f0, Span pd, int nSteps, int offset)\n {\n // Transfer probabilities to log_prob buffer and apply softmax\n for ( var i = 0; i < nSteps * PITCH_BINS; i++ )\n {\n _logProbBuffer[i / PITCH_BINS, i % PITCH_BINS] = probabilities[i];\n }\n\n Softmax(_logProbBuffer, nSteps);\n\n // Apply log to probabilities\n for ( var y = 0; y < nSteps; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _logProbBuffer[y, x] = (float)Math.Log(_logProbBuffer[y, x] + float.Epsilon);\n }\n }\n\n // Initialize first step values\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n _valueBuffer[0, i] = _logProbBuffer[0, i] + _logPInitBuffer[i];\n }\n\n // Viterbi algorithm\n for ( var t = 1; t < nSteps; t++ )\n {\n // Calculate transition outputs\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n _transOutBuffer[y, x] = _valueBuffer[t - 1, x] + _transitionMatrix[x, y]; // Transposed matrix\n }\n }\n\n for ( var j = 0; j < PITCH_BINS; j++ )\n {\n // Find argmax\n var maxI = 0;\n var maxProb = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb < _transOutBuffer[j, k] )\n {\n maxProb = _transOutBuffer[j, k];\n maxI = k;\n }\n }\n\n _ptrBuffer[t, j] = maxI;\n _valueBuffer[t, j] = _logProbBuffer[t, j] + _transOutBuffer[j, _ptrBuffer[t, j]];\n }\n }\n\n // Find the most likely final state\n var maxI2 = 0;\n var maxProb2 = float.NegativeInfinity;\n for ( var k = 0; k < PITCH_BINS; k++ )\n {\n if ( maxProb2 < _valueBuffer[nSteps - 1, k] )\n {\n maxProb2 = _valueBuffer[nSteps - 1, k];\n maxI2 = k;\n }\n }\n\n // Backward pass to find optimal path\n _stateBuffer[nSteps - 1] = maxI2;\n for ( var t = nSteps - 2; t >= 0; t-- )\n {\n _stateBuffer[t] = _ptrBuffer[t + 1, _stateBuffer[t + 1]];\n }\n\n // Convert to f0 values\n for ( var t = 0; t < nSteps; t++ )\n {\n var bins = _stateBuffer[t];\n var periodicity = Periodicity(probabilities, t, bins);\n var frequency = ConvertToFrequency(bins);\n\n if ( offset + t < f0.Length )\n {\n f0[offset + t] = frequency;\n pd[offset + t] = periodicity;\n }\n }\n }\n\n private void Softmax(float[,] data, int nSteps)\n {\n for ( var t = 0; t < nSteps; t++ )\n {\n float sum = 0;\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n sum += (float)Math.Exp(data[t, i]);\n }\n\n for ( var i = 0; i < PITCH_BINS; i++ )\n {\n data[t, i] = (float)Math.Exp(data[t, i]) / sum;\n }\n }\n }\n\n private float[,] CreateTransitionMatrix()\n {\n var transition = new float[PITCH_BINS, PITCH_BINS];\n for ( var y = 0; y < PITCH_BINS; y++ )\n {\n float sum = 0;\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n var v = 12 - Math.Abs(x - y);\n if ( v < 0 )\n {\n v = 0;\n }\n\n transition[y, x] = v;\n sum += v;\n }\n\n for ( var x = 0; x < PITCH_BINS; x++ )\n {\n transition[y, x] = transition[y, x] / sum;\n\n // Pre-apply log to the transition matrix for efficiency\n transition[y, x] = (float)Math.Log(transition[y, x] + float.Epsilon);\n }\n }\n\n return transition;\n }\n\n private float Periodicity(float[] probabilities, int t, int bins) { return probabilities[t * PITCH_BINS + bins]; }\n\n private float ConvertToFrequency(int bin)\n {\n float CENTS_PER_BIN = 20;\n var cents = CENTS_PER_BIN * bin + 1997.3794084376191f;\n var frequency = 10 * (float)Math.Pow(2, cents / 1200);\n\n return frequency;\n }\n\n private void MedianFilter(Span data, int windowSize)\n {\n if ( windowSize > _medianBuffer.Length || windowSize % 2 == 0 )\n {\n throw new ArgumentException(\"Window size must be odd and <= buffer size\", nameof(windowSize));\n }\n\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n // Fill the window buffer\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n _medianBuffer[j] = original[k];\n }\n\n // Sort the window\n Array.Sort(_medianBuffer, 0, windowSize);\n\n // Set the median value\n data[i] = _medianBuffer[windowSize / 2];\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n\n private void MeanFilter(Span data, int windowSize)\n {\n // Create a copy of the original data\n var original = ArrayPool.Shared.Rent(data.Length);\n try\n {\n data.CopyTo(original);\n\n for ( var i = 0; i < data.Length; i++ )\n {\n float sum = 0;\n\n for ( var j = 0; j < windowSize; j++ )\n {\n var k = i + j - windowSize / 2;\n\n // Handle boundary conditions\n if ( k < 0 )\n {\n k = 0;\n }\n\n if ( k >= data.Length )\n {\n k = data.Length - 1;\n }\n\n sum += original[k];\n }\n\n // Set the mean value\n data[i] = sum / windowSize;\n }\n }\n finally\n {\n ArrayPool.Shared.Return(original);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/RouletteWheel/RouletteWheel.cs", "using System.Drawing;\nusing System.Numerics;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.Input;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\n\nnamespace PersonaEngine.Lib.UI.RouletteWheel;\n\npublic partial class RouletteWheel : IRenderComponent\n{\n private const int MAX_VERTICES = 64;\n\n private const int MAX_INDICES = MAX_VERTICES * 6 / 4;\n\n private const float OUTER_RADIUS_FACTOR = 0.8f;\n\n private const float INNER_RADIUS_FACTOR = 0.64f; // OUTER_RADIUS_FACTOR * 0.8f\n\n private const float CENTER_RADIUS_FACTOR = 0.128f; // INNER_RADIUS_FACTOR * 0.2f\n\n private static readonly short[] _indexData = GenerateIndexArray();\n\n private readonly Lock _applyingConfig = new();\n\n private readonly IOptionsMonitor _config;\n\n private readonly FontProvider _fontProvider;\n\n private readonly Dictionary _segmentFontSizes = new();\n\n private readonly float _textSizeAdaptationFactor = 1.0f;\n\n private readonly VertexPositionTexture[] _vertexData = new VertexPositionTexture[MAX_VERTICES];\n\n private GL _gl;\n\n private BufferObject _indexBuffer;\n\n private float _minRotations;\n\n private int _numSections = 0;\n\n private Action? _onSpinCompleteCallback;\n\n private Vector2 _position = Vector2.Zero;\n\n private bool _radialTextOrientation = true;\n\n private string[] _sectionLabels;\n\n private Shader _shader;\n\n private float _spinDuration;\n\n private float _spinStartTime = 0f;\n\n private float _startSegment = 0f;\n\n private float _targetSegment = 0f;\n\n private FSColor _textColor = new(255, 255, 255, 255);\n\n private TextRenderer _textRenderer;\n\n private float _textScale = 1.0f;\n\n private int _textStrokeWidth = 2;\n\n private float _time = 0f;\n\n private bool _useAdaptiveTextSize = true;\n\n private VertexArrayObject _vao;\n\n private BufferObject _vertexBuffer;\n\n private int _vertexIndex = 0;\n\n private int _viewportHeight;\n\n private int _viewportWidth;\n\n private float _wheelSize = 1;\n\n public RouletteWheel(IOptionsMonitor config, FontProvider fontProvider)\n {\n _config = config;\n _fontProvider = fontProvider;\n }\n\n public bool IsSpinning { get; private set; } = false;\n\n public float Progress { get; private set; } = 1f;\n\n public int NumberOfSections\n {\n get => _numSections;\n private set\n {\n _numSections = Math.Clamp(value, 2, 24);\n _targetSegment = Math.Min(_targetSegment, _numSections - 1);\n _startSegment = Math.Min(_startSegment, _numSections - 1);\n ResizeSectionLabels();\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n }\n\n public bool UseSpout => true;\n\n public string SpoutTarget => \"RouletteWheel\";\n\n public int Priority => 0;\n\n public void Initialize(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _textRenderer = new TextRenderer(gl);\n\n // Initialize buffers\n _vertexBuffer = new BufferObject(gl, MAX_VERTICES, BufferTargetARB.ArrayBuffer, true);\n _indexBuffer = new BufferObject(gl, _indexData.Length, BufferTargetARB.ElementArrayBuffer, false);\n _indexBuffer.SetData(_indexData, 0, _indexData.Length);\n\n // Initialize shader\n var vertSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"wheel_shader.vert\"));\n var fragSrc = File.ReadAllText(Path.Combine(@\"Resources/Shaders\", \"wheel_shader.frag\"));\n _shader = new Shader(_gl, vertSrc, fragSrc);\n\n // Setup VAO\n unsafe\n {\n _vao = new VertexArrayObject(gl, sizeof(VertexPositionTexture));\n _vao.Bind();\n }\n\n var location = _shader.GetAttribLocation(\"a_position\");\n _vao.VertexAttribPointer(location, 3, VertexAttribPointerType.Float, false, 0);\n\n location = _shader.GetAttribLocation(\"a_texCoords0\");\n _vao.VertexAttribPointer(location, 2, VertexAttribPointerType.Float, false, 12);\n\n ResizeSectionLabels();\n\n ApplyConfiguration(_config.CurrentValue);\n\n _config.OnChange(ApplyConfiguration);\n\n // Prevent wheel from spinning on creation\n _spinStartTime = -_spinDuration;\n }\n\n public void Update(float deltaTime)\n {\n _time += deltaTime;\n\n if ( IsSpinning )\n {\n var progress = Math.Min((_time - _spinStartTime) / _spinDuration, 1.0f);\n Progress = progress;\n }\n\n if ( IsSpinning && _time - _spinStartTime >= _spinDuration )\n {\n IsSpinning = false;\n _onSpinCompleteCallback?.Invoke((int)_targetSegment);\n _onSpinCompleteCallback = null;\n }\n\n UpdateVisibilityAnimation();\n }\n\n public void Render(float deltaTime)\n {\n lock (_applyingConfig)\n {\n // Skip rendering if wheel is disabled and not animating\n if ( !IsEnabled && CurrentAnimationState == AnimationState.Idle )\n {\n return;\n }\n\n var originalWheelSize = _wheelSize;\n _wheelSize *= _animationCurrentScale;\n\n Begin();\n DrawWheel();\n End();\n\n // Only render labels if wheel is sufficiently visible\n if ( _animationCurrentScale > 0.25f )\n {\n RenderSectionLabels();\n }\n\n _wheelSize = originalWheelSize;\n }\n }\n\n public void Dispose()\n {\n // Context is destroyed anyway when app closes.\n\n return;\n\n _vao.Dispose();\n _vertexBuffer.Dispose();\n _indexBuffer.Dispose();\n _shader.Dispose();\n _textRenderer.Dispose();\n }\n\n public string GetLabel(int index) { return _sectionLabels[index]; }\n\n public string[] GetLabels() { return _sectionLabels.ToArray(); }\n\n public void Spin(int targetSection, Action? onSpinComplete = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return;\n }\n\n _targetSegment = Math.Clamp(targetSection, 0, _numSections - 1);\n _startSegment = GetCurrentWheelPosition();\n _spinStartTime = _time;\n IsSpinning = true;\n _onSpinCompleteCallback = onSpinComplete;\n Progress = 0;\n }\n\n public int SpinRandom(Action? onSpinComplete = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return -1;\n }\n\n var target = Random.Shared.Next(_numSections);\n Spin(target, onSpinComplete);\n\n return target;\n }\n\n public Task SpinAsync(int? targetSection = null)\n {\n if ( IsSpinning || !IsEnabled || CurrentAnimationState != AnimationState.Idle )\n {\n return Task.FromResult(-1);\n }\n\n var tcs = new TaskCompletionSource();\n var target = targetSection ?? Random.Shared.Next(_numSections);\n\n Spin(target, result => tcs.SetResult(result));\n\n return tcs.Task;\n }\n\n public void SetSectionLabels(string[] labels)\n {\n if ( labels.Length == 0 )\n {\n return;\n }\n\n if ( labels.Length != _numSections )\n {\n NumberOfSections = labels.Length;\n }\n\n for ( var i = 0; i < _numSections; i++ )\n {\n _sectionLabels[i] = labels[i];\n }\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n public void ConfigureTextStyle(\n bool radialText = true,\n Color? textColor = null,\n float scale = 1.0f,\n int strokeWidth = 2,\n bool useAdaptiveSize = true)\n {\n var color = textColor ?? Color.White;\n\n _textColor = new FSColor(color.R, color.G, color.B, color.A);\n _textScale = scale;\n _textStrokeWidth = strokeWidth;\n _radialTextOrientation = radialText;\n _useAdaptiveTextSize = useAdaptiveSize;\n\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n\n private static short[] GenerateIndexArray()\n {\n var result = new short[MAX_INDICES];\n for ( int i = 0,\n vi = 0; i < MAX_INDICES; i += 6, vi += 4 )\n {\n result[i] = (short)vi;\n result[i + 1] = (short)(vi + 1);\n result[i + 2] = (short)(vi + 2);\n result[i + 3] = (short)(vi + 1);\n result[i + 4] = (short)(vi + 3);\n result[i + 5] = (short)(vi + 2);\n }\n\n return result;\n }\n\n private void Begin()\n {\n _gl.Disable(EnableCap.DepthTest);\n _gl.Enable(EnableCap.Blend);\n _gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);\n\n _shader.Use();\n UpdateShaderParameters();\n\n var projectionMatrix = Matrix4x4.CreateOrthographicOffCenter(0, _viewportWidth, _viewportHeight, 0, -1, 1);\n _shader.SetUniform(\"MatrixTransform\", projectionMatrix);\n\n _vao.Bind();\n _vertexBuffer.Bind();\n _indexBuffer.Bind();\n }\n\n private void End() { FlushBuffer(); }\n\n private unsafe void FlushBuffer()\n {\n if ( _vertexIndex == 0 )\n {\n return;\n }\n\n _vertexBuffer.SetData(_vertexData, 0, _vertexIndex);\n _gl.DrawElements(PrimitiveType.Triangles, (uint)(_vertexIndex * 6 / 4), DrawElementsType.UnsignedShort, null);\n _vertexIndex = 0;\n }\n\n private void DrawWheel()\n {\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var centerX = _position.X;\n var centerY = _position.Y;\n var cosR = (float)Math.Cos(Rotation);\n var sinR = (float)Math.Sin(Rotation);\n var left = centerX - radius;\n var right = centerX + radius;\n var top = centerY - radius;\n var bottom = centerY + radius;\n\n // Top-left vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(left, top, 0), centerX, centerY, cosR, sinR),\n new Vector2(0, 0));\n\n // Top-right vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(right, top, 0), centerX, centerY, cosR, sinR),\n new Vector2(1, 0));\n\n // Bottom-left vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(left, bottom, 0), centerX, centerY, cosR, sinR),\n new Vector2(0, 1));\n\n // Bottom-right vertex\n _vertexData[_vertexIndex++] = new VertexPositionTexture(\n RotatePoint(new Vector3(right, bottom, 0), centerX, centerY, cosR, sinR),\n new Vector2(1, 1));\n }\n\n private void RenderSectionLabels()\n {\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var innerRadius = radius * INNER_RADIUS_FACTOR;\n var centerRadius = radius * CENTER_RADIUS_FACTOR;\n var centerX = _position.X != 0 ? _position.X : _viewportWidth / 2.0f;\n var centerY = _position.Y != 0 ? _position.Y : _viewportHeight / 2.0f;\n var availableRadialSpace = innerRadius - centerRadius;\n var textRadius = centerRadius + availableRadialSpace * 0.5f;\n var currentRotation = GetCurrentWheelRotation();\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n\n if ( _useAdaptiveTextSize && _segmentFontSizes.Count != _numSections )\n {\n CalculateAllSegmentFontSizes();\n }\n\n _textRenderer.Begin();\n\n var fontSystem = _fontProvider.GetFontSystem(_config.CurrentValue.Font);\n\n // Reusable Vector2 for text position to avoid allocation in the loop\n var position = new Vector2();\n\n for ( var i = 0; i < _numSections; i++ )\n {\n if ( string.IsNullOrEmpty(_sectionLabels[i]) )\n {\n continue;\n }\n\n var fontSize = _useAdaptiveTextSize ? _segmentFontSizes[i] : _config.CurrentValue.FontSize;\n var segmentFont = fontSystem.GetFont(fontSize);\n\n var rotatedStartAngle = -currentRotation;\n var rotatedEndAngle = segmentAngle - currentRotation;\n var segmentCenter = (rotatedStartAngle + rotatedEndAngle) / 2.0f + (_numSections - 1 - i) * segmentAngle;\n\n // Position text\n var textX = centerX + textRadius * MathF.Cos(segmentCenter);\n var textY = centerY + textRadius * MathF.Sin(segmentCenter);\n var textSize = segmentFont.MeasureString(_sectionLabels[i]);\n\n // Update position instead of creating a new Vector2\n position.X = textX;\n position.Y = textY;\n\n // Calculate text rotation\n var textRotation = _radialTextOrientation\n ? MathF.Atan2(textY - centerY, textX - centerX)\n : 0.0f;\n\n // Draw text\n segmentFont.DrawText(\n _textRenderer,\n _sectionLabels[i],\n position,\n _textColor,\n textRotation,\n scale: new Vector2(_textScale),\n effect: FontSystemEffect.Stroked,\n effectAmount: _textStrokeWidth,\n origin: textSize / 2);\n }\n\n _textRenderer.End();\n }\n\n private Vector3 RotatePoint(Vector3 point, float centerX, float centerY, float cosR, float sinR)\n {\n var x = point.X - centerX;\n var y = point.Y - centerY;\n\n var newX = x * cosR - y * sinR + centerX;\n var newY = x * sinR + y * cosR + centerY;\n\n return new Vector3(newX, newY, point.Z);\n }\n\n private float GetCurrentWheelPosition()\n {\n if ( !IsSpinning )\n {\n return _targetSegment;\n }\n\n if ( Progress >= 1.0f )\n {\n IsSpinning = false;\n\n return _targetSegment;\n }\n\n var easedProgress = EaseOutQuint(Progress);\n\n var segmentDiff = (_targetSegment - _startSegment + _numSections) % _numSections;\n if ( segmentDiff > _numSections / 2.0f )\n {\n segmentDiff -= _numSections;\n }\n\n return (_startSegment + segmentDiff * easedProgress + _numSections) % _numSections;\n }\n\n private float GetCurrentWheelRotation()\n {\n var baseRotation = -Rotation;\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n\n var targetAngle = baseRotation + -(_targetSegment + 0.5f) * segmentAngle + MathF.PI * 1.5f;\n\n if ( !IsSpinning )\n {\n return targetAngle;\n }\n\n var startAngle = baseRotation + -(_startSegment + 0.5f) * segmentAngle + MathF.PI * 1.5f;\n var easedProgress = EaseOutQuint(Progress);\n\n var adjustedExtraAngle = targetAngle - startAngle;\n if ( adjustedExtraAngle > 0.0 )\n {\n adjustedExtraAngle -= 2.0f * MathF.PI;\n }\n\n var spinningAngle = startAngle + (adjustedExtraAngle - _minRotations * 2.0f * MathF.PI) * easedProgress;\n\n return spinningAngle;\n }\n\n private void UpdateShaderParameters()\n {\n _shader.SetUniform(\"u_targetSegment\", _targetSegment);\n _shader.SetUniform(\"u_startSegment\", _startSegment);\n _shader.SetUniform(\"u_spinDuration\", _spinDuration);\n _shader.SetUniform(\"u_minRotations\", _minRotations);\n _shader.SetUniform(\"u_spinStartTime\", _spinStartTime);\n _shader.SetUniform(\"u_time\", _time);\n _shader.SetUniform(\"u_numSlices\", (float)_numSections);\n\n float size = Math.Min(_viewportWidth, _viewportHeight);\n _shader.SetUniform(\"u_resolution\", size, size);\n }\n\n private int CalculateOptimalTextSizeForSegment(string label, int segmentIndex)\n {\n if ( string.IsNullOrEmpty(label) )\n {\n return 24;\n }\n\n // Cache these calculations for performance\n float minDimension = Math.Min(_viewportWidth, _viewportHeight);\n var radius = minDimension * _wheelSize * OUTER_RADIUS_FACTOR / 2.0f;\n var innerRadius = radius * INNER_RADIUS_FACTOR;\n var centerRadius = radius * CENTER_RADIUS_FACTOR;\n var availableRadialSpace = innerRadius - centerRadius;\n var textRadius = centerRadius + availableRadialSpace * 0.5f;\n var segmentAngle = 2.0f * MathF.PI / _numSections;\n var maxWidth = 2.0f * textRadius * MathF.Sin(segmentAngle / 2.0f);\n\n var fontSystem = _fontProvider.GetFontSystem(_config.CurrentValue.Font);\n\n // Binary search for optimal font size\n var minFontSize = 1;\n var maxFontSize = 72;\n var optimalFontSize = _config.CurrentValue.FontSize;\n\n while ( minFontSize <= maxFontSize )\n {\n var currentFontSize = (minFontSize + maxFontSize) / 2;\n\n var testFont = fontSystem.GetFont(currentFontSize);\n var textSize = testFont.MeasureString(label);\n var scaledWidth = textSize.X * _textScale * _textSizeAdaptationFactor;\n\n if ( scaledWidth <= maxWidth * INNER_RADIUS_FACTOR )\n {\n optimalFontSize = currentFontSize;\n minFontSize = currentFontSize + 1;\n }\n else\n {\n maxFontSize = currentFontSize - 1;\n }\n }\n\n return optimalFontSize;\n }\n\n private void CalculateAllSegmentFontSizes()\n {\n if ( !_useAdaptiveTextSize )\n {\n return;\n }\n\n _segmentFontSizes.Clear();\n\n for ( var i = 0; i < _numSections; i++ )\n {\n _segmentFontSizes[i] = string.IsNullOrEmpty(_sectionLabels[i])\n ? 24\n : CalculateOptimalTextSizeForSegment(_sectionLabels[i], i);\n }\n }\n\n private void ResizeSectionLabels()\n {\n var newLabels = new string[_numSections];\n for ( var i = 0; i < _numSections; i++ )\n {\n newLabels[i] = i < _sectionLabels?.Length ? _sectionLabels[i] : $\"Section {i + 1}\";\n }\n\n _sectionLabels = newLabels;\n }\n\n private static float EaseOutQuint(float t) { return 1.0f - MathF.Pow(1.0f - t, 5); }\n\n private void ApplyConfiguration(RouletteWheelOptions options)\n {\n lock (_applyingConfig)\n {\n // Apply text configuration\n _radialTextOrientation = options.RadialTextOrientation;\n _textScale = options.TextScale;\n _textStrokeWidth = options.TextStroke;\n _useAdaptiveTextSize = options.AdaptiveText;\n\n if ( !string.IsNullOrEmpty(options.TextColor) )\n {\n var color = ColorTranslator.FromHtml(options.TextColor);\n _textColor = new FSColor(color.R, color.G, color.B, color.A);\n }\n\n // Apply section labels\n if ( options.SectionLabels?.Length > 0 )\n {\n SetSectionLabels(options.SectionLabels);\n }\n\n // Apply spin parameters\n _spinDuration = Math.Max(options.SpinDuration, 0.1f);\n _minRotations = Math.Max(options.MinRotations, 1.0f);\n\n // Apply wheel size\n _wheelSize = Math.Clamp(options.WheelSizePercentage, 0.1f, 1.0f);\n\n // Apply positioning\n if ( !string.IsNullOrEmpty(options.PositionMode) )\n {\n switch ( options.PositionMode )\n {\n case \"Absolute\":\n _positionMode = PositionMode.Absolute;\n SetAbsolutePosition(options.AbsolutePositionX, options.AbsolutePositionY);\n\n break;\n case \"Percentage\":\n _positionMode = PositionMode.Percentage;\n PositionByPercentage(options.PositionXPercentage, options.PositionYPercentage);\n\n break;\n case \"Anchored\":\n _positionMode = PositionMode.Anchored;\n if ( Enum.TryParse(options.ViewportAnchor, out ViewportAnchor anchor) )\n {\n PositionAt(anchor, new Vector2(options.AnchorOffsetX, options.AnchorOffsetY));\n }\n else\n {\n PositionAt(ViewportAnchor.Center);\n }\n\n break;\n }\n }\n\n // Apply rotation\n Rotation = options.RotationDegrees * MathF.PI / 180;\n\n // Handle viewport size changes\n var viewportChanged = _viewportWidth != options.Width || _viewportHeight != options.Height;\n if ( viewportChanged )\n {\n _viewportWidth = options.Width;\n _viewportHeight = options.Height;\n\n // Update text renderer viewport\n _textRenderer.OnViewportChanged(_viewportWidth, _viewportHeight);\n\n // Update position based on mode\n switch ( _positionMode )\n {\n case PositionMode.Anchored:\n UpdatePositionFromAnchor();\n\n break;\n case PositionMode.Percentage:\n UpdatePositionFromPercentage();\n\n break;\n }\n }\n\n // Apply enabled state (if changed)\n if ( options.Enabled != IsEnabled )\n {\n if ( options.Enabled )\n {\n Enable();\n }\n else\n {\n Disable();\n }\n }\n\n // Recalculate font sizes if needed (after all other changes)\n if ( _useAdaptiveTextSize )\n {\n CalculateAllSegmentFontSizes();\n }\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ChatEditor.cs", "using System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nusing OpenAI.Chat;\n\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Context;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Session;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class ChatEditor : ConfigSectionEditorBase\n{\n private readonly FontProvider _fontProvider;\n\n private readonly IConversationOrchestrator _orchestrator;\n\n private readonly float _participantsPanelWidth = 200f;\n\n private readonly IUiThemeManager _themeManager;\n\n private IConversationContext? _currentContext;\n\n private string _editMessageContent = string.Empty;\n\n private Guid _editMessageId = Guid.Empty;\n\n private Guid _editTurnId = Guid.Empty;\n\n private IReadOnlyList _historySnapshot = Array.Empty();\n\n private bool _needsRedraw = true;\n\n private IReadOnlyDictionary _participantsSnapshot = new Dictionary();\n\n private InteractionTurn? _pendingTurnSnapshot;\n\n private bool _showConfirmClearPopup = false;\n\n private bool _showEditPopup = false;\n\n public ChatEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IUiThemeManager themeManager,\n IConversationOrchestrator orchestrator,\n FontProvider fontProvider)\n : base(configManager, stateManager)\n {\n _orchestrator = orchestrator;\n _themeManager = themeManager;\n _fontProvider = fontProvider;\n\n _orchestrator.SessionsUpdated += OnCurrentContextChanged;\n OnCurrentContextChanged(null, EventArgs.Empty);\n }\n\n public override string SectionKey => \"Chat\";\n\n public override string DisplayName => \"Conversation\";\n\n private void OnCurrentContextChanged(object? sender, EventArgs e)\n {\n var sessionId = _orchestrator.GetActiveSessionIds().FirstOrDefault();\n if ( sessionId == Guid.Empty )\n {\n return;\n }\n\n var context = _orchestrator.GetSession(sessionId).Context;\n SetCurrentContext(context);\n }\n\n private void SetCurrentContext(IConversationContext? newContext)\n {\n if ( _currentContext == newContext )\n {\n return;\n }\n\n if ( _currentContext != null )\n {\n _currentContext.ConversationUpdated -= OnConversationUpdated;\n }\n\n _currentContext = newContext;\n\n if ( _currentContext != null )\n {\n _currentContext.ConversationUpdated += OnConversationUpdated;\n UpdateSnapshots();\n }\n else\n {\n _historySnapshot = Array.Empty();\n _participantsSnapshot = new Dictionary();\n _pendingTurnSnapshot = null;\n }\n\n _needsRedraw = true;\n }\n\n private void OnConversationUpdated(object? sender, EventArgs e)\n {\n UpdateSnapshots();\n _needsRedraw = true;\n }\n\n private void UpdateSnapshots()\n {\n if ( _currentContext == null )\n {\n return;\n }\n\n _participantsSnapshot = new Dictionary(_currentContext.Participants);\n _historySnapshot = _currentContext.History.Select(turn => turn.CreateSnapshot()).ToList();\n _pendingTurnSnapshot = _currentContext.PendingTurn;\n }\n\n public override void Render()\n {\n if ( _needsRedraw )\n {\n _needsRedraw = false;\n }\n\n var availWidth = ImGui.GetContentRegionAvail().X;\n if ( _currentContext == null )\n {\n ImGui.TextWrapped(\"No active conversation selected.\");\n\n return;\n }\n\n // --- Left Panel: Participants and Controls ---\n ImGui.BeginChild(\"ParticipantsPanel\", new Vector2(_participantsPanelWidth, 700), ImGuiChildFlags.Borders);\n {\n RenderParticipantsPanel(_currentContext);\n RenderControlsPanel(_currentContext);\n }\n\n ImGui.EndChild();\n\n ImGui.SameLine();\n\n // --- Right Panel: Chat History ---\n var chatAreaWidth = availWidth - _participantsPanelWidth - ImGui.GetStyle().ItemSpacing.X;\n ImGui.BeginChild(\"ChatHistoryPanel\", new Vector2(chatAreaWidth, 700), ImGuiChildFlags.None);\n {\n RenderChatHistory(_currentContext, chatAreaWidth);\n }\n\n ImGui.EndChild();\n\n // --- Popups ---\n RenderEditPopup(_currentContext);\n RenderConfirmClearPopup(_currentContext);\n }\n\n private void RenderParticipantsPanel(IConversationContext context)\n {\n ImGui.Text(\"Participants\");\n ImGui.Separator();\n\n if ( !_participantsSnapshot.Any() )\n {\n ImGui.TextDisabled(\"No participants.\");\n\n return;\n }\n\n foreach ( var participant in _participantsSnapshot.Values )\n {\n // Simple display: Icon (optional) + Name + Role\n ImGui.BulletText($\"{participant.Name} ({participant.Role})\");\n // Optional: Add context menu to remove participant?\n // if (ImGui.BeginPopupContextItem($\"participant_{participant.Id}\")) { ... }\n }\n }\n\n private void RenderControlsPanel(IConversationContext context)\n {\n ImGui.Separator();\n ImGui.Spacing();\n ImGui.Text(\"Controls\");\n ImGui.Separator();\n\n if ( ImGui.Button(\"Clear Conversation\", new Vector2(-1, 0)) )\n {\n _showConfirmClearPopup = true;\n }\n\n // Optional: Add other controls like Apply Cleanup Strategy\n if ( ImGui.Button(\"Apply Cleanup\", new Vector2(-1, 0)) )\n {\n _currentContext?.ApplyCleanupStrategy();\n }\n }\n\n private void RenderChatHistory(IConversationContext context, float availableWidth)\n {\n var maxBubbleWidth = availableWidth * 0.75f;\n var style = ImGui.GetStyle();\n\n ImGui.Text(\"Conversation: Main\");\n ImGui.Separator();\n\n ImGui.BeginChild(\"ChatScrollRegion\", new Vector2(availableWidth, -1), ImGuiChildFlags.None);\n {\n for ( var turnIndex = 0; turnIndex < _historySnapshot.Count; turnIndex++ )\n {\n var turn = _historySnapshot[turnIndex];\n RenderTurn(context, turn, turnIndex, maxBubbleWidth, availableWidth);\n\n ImGui.Separator();\n ImGui.Spacing();\n }\n\n // if ( _pendingTurnSnapshot != null )\n // {\n // ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.6f, 0.6f, 0.6f, 1.0f));\n // RenderTurn(context, _pendingTurnSnapshot, -1, maxBubbleWidth, availableWidth, true);\n // ImGui.PopStyleColor();\n // }\n\n if ( ImGui.GetScrollY() >= ImGui.GetScrollMaxY() - 10 )\n {\n ImGui.SetScrollHereY(1.0f);\n }\n }\n\n ImGui.EndChild();\n }\n\n private void RenderTurn(IConversationContext context, InteractionTurn turn, int turnIndex, float maxBubbleWidth, float availableWidth, bool isPending = false)\n {\n var style = ImGui.GetStyle();\n\n ImGui.TextDisabled($\"Turn {turnIndex + 1} ({turn.StartTime.ToLocalTime():g})\");\n ImGui.Spacing();\n\n for ( var msgIndex = 0; msgIndex < turn.Messages.Count; msgIndex++ )\n {\n var message = turn.Messages[msgIndex];\n var participant = _participantsSnapshot.GetValueOrDefault(message.ParticipantId);\n var role = participant?.Role ?? message.Role;\n\n var isUserMessage = role == ChatMessageRole.User;\n\n var messageText = message.Text;\n if ( message.IsPartial && isPending )\n {\n messageText += \" ...\";\n }\n\n ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));\n ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, 8.0f);\n\n var textSize = ImGui.CalcTextSize(messageText, false, maxBubbleWidth - style.WindowPadding.X * 2);\n var nameSize = ImGui.CalcTextSize(message.ParticipantName, false, maxBubbleWidth - style.WindowPadding.X * 2);\n var bubbleWidth = Math.Min(textSize.X + style.WindowPadding.X * 2, maxBubbleWidth);\n var bubbleHeight = nameSize.Y + textSize.Y + style.WindowPadding.Y * 2 + (isUserMessage ? ImGui.GetTextLineHeight() : 0);\n\n var startPosX = style.WindowPadding.X;\n if ( isUserMessage )\n {\n startPosX = availableWidth - bubbleWidth - style.WindowPadding.X - style.ScrollbarSize;\n }\n\n ImGui.SetCursorPosX(startPosX);\n\n // --- Styling ---\n Vector4 bgColor,\n textColor;\n\n if ( isUserMessage )\n {\n bgColor = new Vector4(0.15f, 0.48f, 0.88f, 1.0f); // Blueish\n textColor = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); // White text\n }\n else\n {\n bgColor = new Vector4(0.92f, 0.92f, 0.92f, 1.0f); // Light gray\n textColor = new Vector4(0.1f, 0.1f, 0.1f, 1.0f); // Dark text\n }\n\n ImGui.PushStyleColor(ImGuiCol.ChildBg, bgColor);\n ImGui.PushStyleColor(ImGuiCol.Text, textColor);\n\n // --- Render Bubble ---\n var childId = $\"msg_{turn.TurnId}_{message.MessageId}\";\n ImGui.BeginChild(childId, new Vector2(bubbleWidth, bubbleHeight), ImGuiChildFlags.Borders, ImGuiWindowFlags.None);\n {\n if ( isUserMessage )\n {\n ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.52f, 0.92f, 0.89f, 1f));\n ImGui.TextWrapped(message.ParticipantName);\n ImGui.PopStyleColor();\n }\n\n ImGui.TextWrapped(messageText);\n\n ImGui.EndChild();\n }\n\n ImGui.PopStyleColor(2);\n ImGui.PopStyleVar(2);\n\n // --- Context Menu (Edit/Delete) - Only for committed messages ---\n if ( !isPending && ImGui.BeginPopupContextItem($\"ctx_{childId}\") )\n {\n if ( ImGui.MenuItem(\"Edit\") )\n {\n _editTurnId = turn.TurnId;\n _editMessageId = message.MessageId;\n _editMessageContent = message.Text;\n _showEditPopup = true;\n }\n\n ImGui.Separator();\n if ( ImGui.MenuItem(\"Delete\") )\n {\n context.TryDeleteMessage(turn.TurnId, message.MessageId);\n }\n\n ImGui.EndPopup();\n }\n\n ImGui.Dummy(new Vector2(0, style.ItemSpacing.Y));\n }\n }\n\n private void RenderEditPopup(IConversationContext context)\n {\n if ( _showEditPopup )\n {\n ImGui.OpenPopup(\"Edit Message\");\n _showEditPopup = false;\n }\n\n var viewport = ImGui.GetMainViewport();\n ImGui.SetNextWindowPos(viewport.Pos + viewport.Size * 0.5f, ImGuiCond.Appearing, new Vector2(0.5f, 0.5f));\n ImGui.SetNextWindowSize(new Vector2(500, 0), ImGuiCond.Appearing);\n\n if ( ImGui.BeginPopupModal(\"Edit Message\", ImGuiWindowFlags.NoResize) )\n {\n ImGui.InputTextMultiline(\"##edit_content\", ref _editMessageContent, 1024 * 4, new Vector2(0, 150));\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n var buttonWidth = 120f;\n var totalButtonsWidth = buttonWidth * 2 + ImGui.GetStyle().ItemSpacing.X;\n ImGui.SetCursorPosX((ImGui.GetWindowWidth() - totalButtonsWidth) * 0.5f);\n\n if ( ImGui.Button(\"Save\", new Vector2(buttonWidth, 0)) )\n {\n if ( _editMessageId != Guid.Empty && _editTurnId != Guid.Empty )\n {\n context.TryUpdateMessage(_editTurnId, _editMessageId, _editMessageContent);\n\n _editMessageId = Guid.Empty;\n _editTurnId = Guid.Empty;\n _editMessageContent = string.Empty;\n }\n\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"Cancel\", new Vector2(buttonWidth, 0)) )\n {\n _editMessageId = Guid.Empty;\n _editTurnId = Guid.Empty;\n _editMessageContent = string.Empty;\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.EndPopup();\n }\n else\n {\n if ( _editMessageId == Guid.Empty )\n {\n return;\n }\n\n _editMessageId = Guid.Empty;\n _editTurnId = Guid.Empty;\n _editMessageContent = string.Empty;\n }\n }\n\n private void RenderConfirmClearPopup(IConversationContext context)\n {\n if ( _showConfirmClearPopup )\n {\n ImGui.OpenPopup(\"Confirm Clear\");\n _showConfirmClearPopup = false;\n }\n\n var viewport = ImGui.GetMainViewport();\n ImGui.SetNextWindowPos(viewport.Pos + viewport.Size * 0.5f, ImGuiCond.Appearing, new Vector2(0.5f, 0.5f));\n\n if ( ImGui.BeginPopupModal(\"Confirm Clear\", ImGuiWindowFlags.NoResize | ImGuiWindowFlags.AlwaysAutoResize) )\n {\n ImGui.TextWrapped(\"Are you sure you want to clear the entire conversation history?\");\n ImGui.TextWrapped(\"This action cannot be undone.\");\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n var buttonWidth = 120f;\n var totalButtonsWidth = buttonWidth * 2 + ImGui.GetStyle().ItemSpacing.X;\n ImGui.SetCursorPosX((ImGui.GetWindowWidth() - totalButtonsWidth) * 0.5f);\n\n if ( ImGui.Button(\"Yes, Clear\", new Vector2(buttonWidth, 0)) )\n {\n _currentContext?.ClearHistory();\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.SameLine();\n\n if ( ImGui.Button(\"No, Cancel\", new Vector2(buttonWidth, 0)) )\n {\n ImGui.CloseCurrentPopup();\n }\n\n ImGui.EndPopup();\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/ImGuiController.cs", "using System.Diagnostics;\nusing System.Drawing;\nusing System.Numerics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Utilities;\nusing Hexa.NET.ImNodes;\n\nusing PersonaEngine.Lib.UI.Common;\n\nusing Silk.NET.Input;\nusing Silk.NET.Input.Extensions;\nusing Silk.NET.Maths;\nusing Silk.NET.OpenGL;\nusing Silk.NET.Windowing;\n\nusing Shader = PersonaEngine.Lib.UI.Common.Shader;\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class ImGuiController : IDisposable\n{\n [FixedAddressValueType] private static SetClipboardDelegate setClipboardFn;\n\n [FixedAddressValueType] private static GetClipboardDelegate getClipboardFn;\n\n private readonly List _pressedChars = new();\n\n private int _attribLocationProjMtx;\n\n private int _attribLocationTex;\n\n private int _attribLocationVtxColor;\n\n private int _attribLocationVtxPos;\n\n private int _attribLocationVtxUV;\n\n private IntPtr _clipboardTextPtr = IntPtr.Zero;\n\n private bool _ctrlVProcessed = false;\n\n private uint _elementsHandle;\n\n private Texture _fontTexture;\n\n private bool _frameBegun;\n\n private GL _gl;\n\n private IInputContext _input;\n\n private IKeyboard _keyboard;\n\n private ImGuiPlatformIOPtr _platform;\n\n private Shader _shader;\n\n private uint _vboHandle;\n\n private uint _vertexArrayObject;\n\n private IView _view;\n\n private bool _wasCtrlVPressed = false;\n\n private int _windowHeight;\n\n private int _windowWidth;\n\n public ImGuiContextPtr Context;\n\n /// \n /// Constructs a new ImGuiController.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input) : this(gl, view, input, null, null) { }\n\n /// \n /// Constructs a new ImGuiController with font configuration.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input, string primaryFontPath, string emojiFontPath) : this(gl, view, input, primaryFontPath, emojiFontPath, null) { }\n\n /// \n /// Constructs a new ImGuiController with an onConfigureIO Action.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input, Action? onConfigureIO) : this(gl, view, input, null, null, onConfigureIO) { }\n\n /// \n /// Constructs a new ImGuiController with font configuration and onConfigure Action.\n /// \n public ImGuiController(GL gl, IView view, IInputContext input, string? primaryFontPath = null, string? emojiFontPath = null, Action? onConfigureIO = null)\n {\n Init(gl, view, input);\n\n var io = ImGui.GetIO();\n var fontBuilder = new ImGuiFontBuilder();\n\n if ( primaryFontPath != null )\n {\n \n fontBuilder.AddFontFromFileTTF(primaryFontPath, 18f, [0x1, 0x1FFFF]);\n \n }\n else\n {\n fontBuilder.AddDefaultFont();\n }\n\n if ( emojiFontPath != null )\n {\n fontBuilder.SetOption(config =>\n {\n config.FontBuilderFlags |= (uint)ImGuiFreeTypeBuilderFlags.LoadColor;\n config.MergeMode = true;\n config.PixelSnapH = true;\n });\n\n fontBuilder.AddFontFromFileTTF(emojiFontPath, 14f, [0x1, 0x1FFFF]);\n }\n\n _ = fontBuilder.Build();\n io.Fonts.Build();\n\n io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset;\n io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;\n io.ConfigViewportsNoAutoMerge = false;\n io.ConfigViewportsNoTaskBarIcon = false;\n\n CreateDeviceResources();\n\n SetPerFrameImGuiData(1f / 60f);\n\n // Initialize ImNodes as you're already doing\n ImNodes.SetImGuiContext(Context);\n ImNodes.SetCurrentContext(ImNodes.CreateContext());\n ImNodes.StyleColorsDark(ImNodes.GetStyle());\n\n BeginFrame();\n }\n\n /// \n /// Frees all graphics resources used by the renderer.\n /// \n public void Dispose()\n {\n _view.Resize -= WindowResized;\n _keyboard.KeyChar -= OnKeyChar;\n\n _gl.DeleteBuffer(_vboHandle);\n _gl.DeleteBuffer(_elementsHandle);\n _gl.DeleteVertexArray(_vertexArrayObject);\n\n _fontTexture.Dispose();\n _shader.Dispose();\n\n ImGui.DestroyContext(Context);\n }\n\n public void MakeCurrent() { ImGui.SetCurrentContext(Context); }\n\n private unsafe void Init(GL gl, IView view, IInputContext input)\n {\n _gl = gl;\n _view = view;\n _input = input;\n _windowWidth = view.Size.X;\n _windowHeight = view.Size.Y;\n\n Context = ImGui.CreateContext();\n ImGui.SetCurrentContext(Context);\n ImGui.StyleColorsDark();\n\n _platform = ImGui.GetPlatformIO();\n var io = ImGui.GetIO();\n\n setClipboardFn = SetClipboard;\n getClipboardFn = GetClipboard;\n\n // Register clipboard handlers with both IO and PlatformIO\n _platform.PlatformSetClipboardTextFn = (void*)Marshal.GetFunctionPointerForDelegate(setClipboardFn);\n _platform.PlatformGetClipboardTextFn = (void*)Marshal.GetFunctionPointerForDelegate(getClipboardFn);\n }\n\n private void SetClipboard(IntPtr data)\n {\n Debug.WriteLine(\"SetClipboard called\");\n\n if ( data == IntPtr.Zero )\n {\n return;\n }\n\n var text = Marshal.PtrToStringUTF8(data) ?? string.Empty;\n try\n {\n // Try the Silk.NET method first\n if ( _keyboard != null )\n {\n _keyboard.ClipboardText = text;\n }\n else\n {\n Debug.WriteLine(\"Keyboard reference is null when setting clipboard text\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to set clipboard text via Silk.NET: {ex.Message}\");\n }\n }\n\n private IntPtr GetClipboard()\n {\n Debug.WriteLine(\"GetClipboard called\");\n\n if ( _clipboardTextPtr != IntPtr.Zero )\n {\n Marshal.FreeHGlobal(_clipboardTextPtr);\n _clipboardTextPtr = IntPtr.Zero;\n }\n\n var text = string.Empty;\n var success = false;\n\n // Try primary method\n if ( _keyboard != null )\n {\n try\n {\n text = _keyboard.ClipboardText ?? string.Empty;\n success = true;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to get clipboard text via Silk.NET: {ex.Message}\");\n }\n }\n\n // Convert to UTF-8 and allocate memory\n try\n {\n // Ensure null termination for C strings\n var bytes = Encoding.UTF8.GetBytes(text + '\\0');\n _clipboardTextPtr = Marshal.AllocHGlobal(bytes.Length);\n Marshal.Copy(bytes, 0, _clipboardTextPtr, bytes.Length);\n\n return _clipboardTextPtr;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to allocate memory for clipboard text: {ex.Message}\");\n\n return IntPtr.Zero;\n }\n }\n\n private void BeginFrame()\n {\n ImGui.NewFrame();\n _frameBegun = true;\n _keyboard = _input.Keyboards[0];\n _view.Resize += WindowResized;\n _keyboard.KeyDown += OnKeyDown;\n _keyboard.KeyUp += OnKeyUp;\n _keyboard.KeyChar += OnKeyChar;\n }\n\n private static void OnKeyDown(IKeyboard keyboard, Key keycode, int scancode) { OnKeyEvent(keyboard, keycode, scancode, true); }\n\n private static void OnKeyUp(IKeyboard keyboard, Key keycode, int scancode) { OnKeyEvent(keyboard, keycode, scancode, false); }\n\n private static void OnKeyEvent(IKeyboard keyboard, Key keycode, int scancode, bool down)\n {\n var io = ImGui.GetIO();\n var imGuiKey = TranslateInputKeyToImGuiKey(keycode);\n io.AddKeyEvent(imGuiKey, down);\n io.SetKeyEventNativeData(imGuiKey, (int)keycode, scancode);\n }\n\n private void OnKeyChar(IKeyboard arg1, char arg2) { _pressedChars.Add(arg2); }\n\n private void WindowResized(Vector2D size)\n {\n _windowWidth = size.X;\n _windowHeight = size.Y;\n }\n\n /// \n /// Renders the ImGui draw list data.\n /// This method requires a because it may create new DeviceBuffers if the size of vertex\n /// or index data has increased beyond the capacity of the existing buffers.\n /// A is needed to submit drawing and resource update commands.\n /// \n public void Render()\n {\n if ( _frameBegun )\n {\n ImGui.End();\n\n var oldCtx = ImGui.GetCurrentContext();\n\n if ( oldCtx != Context )\n {\n ImGui.SetCurrentContext(Context);\n }\n\n _frameBegun = false;\n ImGui.Render();\n RenderImDrawData(ImGui.GetDrawData());\n\n if ( oldCtx != Context )\n {\n ImGui.SetCurrentContext(oldCtx);\n }\n }\n }\n\n /// \n /// Updates ImGui input and IO configuration state.\n /// \n public void Update(float deltaSeconds)\n {\n var oldCtx = ImGui.GetCurrentContext();\n\n if ( oldCtx != Context )\n {\n ImGui.SetCurrentContext(Context);\n }\n\n if ( _frameBegun )\n {\n ImGui.Render();\n }\n\n SetPerFrameImGuiData(deltaSeconds);\n UpdateImGuiInput();\n SetDocking();\n\n _frameBegun = true;\n }\n\n private void SetDocking()\n {\n ImGui.NewFrame();\n var viewport = ImGui.GetMainViewport();\n\n var windowFlags = ImGuiWindowFlags.NoTitleBar |\n ImGuiWindowFlags.NoResize |\n ImGuiWindowFlags.NoMove |\n ImGuiWindowFlags.NoBringToFrontOnFocus |\n ImGuiWindowFlags.NoNavFocus;\n\n ImGui.SetNextWindowPos(viewport.Pos);\n ImGui.SetNextWindowSize(viewport.Size);\n ImGui.SetNextWindowViewport(viewport.ID);\n ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0.0f);\n ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0.0f);\n ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0));\n\n ImGui.Begin(\"DockSpace\", windowFlags);\n ImGui.PopStyleVar(3);\n var dockspaceId = ImGui.GetID(\"MyDockSpace\");\n ImGui.DockSpace(dockspaceId, new Vector2(0.0f, 0.0f), ImGuiDockNodeFlags.AutoHideTabBar);\n }\n\n /// \n /// Sets per-frame data based on the associated window.\n /// This is called by Update(float).\n /// \n private void SetPerFrameImGuiData(float deltaSeconds)\n {\n var io = ImGui.GetIO();\n io.DisplaySize = new Vector2(_windowWidth, _windowHeight);\n\n if ( _windowWidth > 0 && _windowHeight > 0 )\n {\n io.DisplayFramebufferScale = new Vector2(_view.FramebufferSize.X / _windowWidth,\n _view.FramebufferSize.Y / _windowHeight);\n }\n\n io.DeltaTime = deltaSeconds; // DeltaTime is in seconds.\n }\n\n private void UpdateImGuiInput()\n {\n var io = ImGui.GetIO();\n\n using var mouseState = _input.Mice[0].CaptureState();\n\n io.MouseDown[0] = mouseState.IsButtonPressed(MouseButton.Left);\n io.MouseDown[1] = mouseState.IsButtonPressed(MouseButton.Right);\n io.MouseDown[2] = mouseState.IsButtonPressed(MouseButton.Middle);\n\n var point = new Point((int)mouseState.Position.X, (int)mouseState.Position.Y);\n io.MousePos = new Vector2(point.X, point.Y);\n\n var wheel = mouseState.GetScrollWheels()[0];\n io.MouseWheel = wheel.Y;\n io.MouseWheelH = wheel.X;\n\n foreach ( var c in _pressedChars )\n {\n io.AddInputCharacter(c);\n }\n\n _pressedChars.Clear();\n\n io.KeyCtrl = _keyboard.IsKeyPressed(Key.ControlLeft) || _keyboard.IsKeyPressed(Key.ControlRight);\n io.KeyAlt = _keyboard.IsKeyPressed(Key.AltLeft) || _keyboard.IsKeyPressed(Key.AltRight);\n io.KeyShift = _keyboard.IsKeyPressed(Key.ShiftLeft) || _keyboard.IsKeyPressed(Key.ShiftRight);\n io.KeySuper = _keyboard.IsKeyPressed(Key.SuperLeft) || _keyboard.IsKeyPressed(Key.SuperRight);\n\n if ( io.KeyCtrl && _keyboard.IsKeyPressed(Key.C) )\n {\n io.AddKeyEvent(ImGuiKey.C, true);\n io.AddKeyEvent(ImGuiKey.LeftCtrl, true);\n\n Debug.WriteLine(\"Adding Ctrl+C event to ImGui\");\n }\n\n var isCtrlVPressed = io.KeyCtrl && _keyboard.IsKeyPressed(Key.V);\n\n if ( isCtrlVPressed && !_wasCtrlVPressed )\n {\n _ctrlVProcessed = false;\n }\n\n if ( isCtrlVPressed && !_ctrlVProcessed )\n {\n io.AddKeyEvent(ImGuiKey.V, true);\n io.AddKeyEvent(ImGuiKey.LeftCtrl, true);\n\n var clipboardText = ImGui.GetClipboardTextS();\n if ( ImGui.IsAnyItemActive() )\n {\n foreach ( var c in clipboardText )\n {\n io.AddInputCharacter(c);\n }\n }\n\n io.AddKeyEvent(ImGuiKey.V, false);\n io.AddKeyEvent(ImGuiKey.LeftCtrl, false);\n\n _ctrlVProcessed = true;\n }\n\n _wasCtrlVPressed = isCtrlVPressed;\n }\n\n internal void PressChar(char keyChar) { _pressedChars.Add(keyChar); }\n\n /// \n /// Translates a Silk.NET.Input.Key to an ImGuiKey.\n /// \n /// The Silk.NET.Input.Key to translate.\n /// The corresponding ImGuiKey.\n /// When the key has not been implemented yet.\n private static ImGuiKey TranslateInputKeyToImGuiKey(Key key)\n {\n return key switch {\n Key.Tab => ImGuiKey.Tab,\n Key.Left => ImGuiKey.LeftArrow,\n Key.Right => ImGuiKey.RightArrow,\n Key.Up => ImGuiKey.UpArrow,\n Key.Down => ImGuiKey.DownArrow,\n Key.PageUp => ImGuiKey.PageUp,\n Key.PageDown => ImGuiKey.PageDown,\n Key.Home => ImGuiKey.Home,\n Key.End => ImGuiKey.End,\n Key.Insert => ImGuiKey.Insert,\n Key.Delete => ImGuiKey.Delete,\n Key.Backspace => ImGuiKey.Backspace,\n Key.Space => ImGuiKey.Space,\n Key.Enter => ImGuiKey.Enter,\n Key.Escape => ImGuiKey.Escape,\n Key.Apostrophe => ImGuiKey.Apostrophe,\n Key.Comma => ImGuiKey.Comma,\n Key.Minus => ImGuiKey.Minus,\n Key.Period => ImGuiKey.Period,\n Key.Slash => ImGuiKey.Slash,\n Key.Semicolon => ImGuiKey.Semicolon,\n Key.Equal => ImGuiKey.Equal,\n Key.LeftBracket => ImGuiKey.LeftBracket,\n Key.BackSlash => ImGuiKey.Backslash,\n Key.RightBracket => ImGuiKey.RightBracket,\n Key.GraveAccent => ImGuiKey.GraveAccent,\n Key.CapsLock => ImGuiKey.CapsLock,\n Key.ScrollLock => ImGuiKey.ScrollLock,\n Key.NumLock => ImGuiKey.NumLock,\n Key.PrintScreen => ImGuiKey.PrintScreen,\n Key.Pause => ImGuiKey.Pause,\n Key.Keypad0 => ImGuiKey.Keypad0,\n Key.Keypad1 => ImGuiKey.Keypad1,\n Key.Keypad2 => ImGuiKey.Keypad2,\n Key.Keypad3 => ImGuiKey.Keypad3,\n Key.Keypad4 => ImGuiKey.Keypad4,\n Key.Keypad5 => ImGuiKey.Keypad5,\n Key.Keypad6 => ImGuiKey.Keypad6,\n Key.Keypad7 => ImGuiKey.Keypad7,\n Key.Keypad8 => ImGuiKey.Keypad8,\n Key.Keypad9 => ImGuiKey.Keypad9,\n Key.KeypadDecimal => ImGuiKey.KeypadDecimal,\n Key.KeypadDivide => ImGuiKey.KeypadDivide,\n Key.KeypadMultiply => ImGuiKey.KeypadMultiply,\n Key.KeypadSubtract => ImGuiKey.KeypadSubtract,\n Key.KeypadAdd => ImGuiKey.KeypadAdd,\n Key.KeypadEnter => ImGuiKey.KeypadEnter,\n Key.KeypadEqual => ImGuiKey.KeypadEqual,\n Key.ShiftLeft => ImGuiKey.LeftShift,\n Key.ControlLeft => ImGuiKey.LeftCtrl,\n Key.AltLeft => ImGuiKey.LeftAlt,\n Key.SuperLeft => ImGuiKey.LeftSuper,\n Key.ShiftRight => ImGuiKey.RightShift,\n Key.ControlRight => ImGuiKey.RightCtrl,\n Key.AltRight => ImGuiKey.RightAlt,\n Key.SuperRight => ImGuiKey.RightSuper,\n Key.Menu => ImGuiKey.Menu,\n Key.Number0 => ImGuiKey.Key0,\n Key.Number1 => ImGuiKey.Key1,\n Key.Number2 => ImGuiKey.Key2,\n Key.Number3 => ImGuiKey.Key3,\n Key.Number4 => ImGuiKey.Key4,\n Key.Number5 => ImGuiKey.Key5,\n Key.Number6 => ImGuiKey.Key6,\n Key.Number7 => ImGuiKey.Key7,\n Key.Number8 => ImGuiKey.Key8,\n Key.Number9 => ImGuiKey.Key9,\n Key.A => ImGuiKey.A,\n Key.B => ImGuiKey.B,\n Key.C => ImGuiKey.C,\n Key.D => ImGuiKey.D,\n Key.E => ImGuiKey.E,\n Key.F => ImGuiKey.F,\n Key.G => ImGuiKey.G,\n Key.H => ImGuiKey.H,\n Key.I => ImGuiKey.I,\n Key.J => ImGuiKey.J,\n Key.K => ImGuiKey.K,\n Key.L => ImGuiKey.L,\n Key.M => ImGuiKey.M,\n Key.N => ImGuiKey.N,\n Key.O => ImGuiKey.O,\n Key.P => ImGuiKey.P,\n Key.Q => ImGuiKey.Q,\n Key.R => ImGuiKey.R,\n Key.S => ImGuiKey.S,\n Key.T => ImGuiKey.T,\n Key.U => ImGuiKey.U,\n Key.V => ImGuiKey.V,\n Key.W => ImGuiKey.W,\n Key.X => ImGuiKey.X,\n Key.Y => ImGuiKey.Y,\n Key.Z => ImGuiKey.Z,\n Key.F1 => ImGuiKey.F1,\n Key.F2 => ImGuiKey.F2,\n Key.F3 => ImGuiKey.F3,\n Key.F4 => ImGuiKey.F4,\n Key.F5 => ImGuiKey.F5,\n Key.F6 => ImGuiKey.F6,\n Key.F7 => ImGuiKey.F7,\n Key.F8 => ImGuiKey.F8,\n Key.F9 => ImGuiKey.F9,\n Key.F10 => ImGuiKey.F10,\n Key.F11 => ImGuiKey.F11,\n Key.F12 => ImGuiKey.F12,\n Key.F13 => ImGuiKey.F13,\n Key.F14 => ImGuiKey.F14,\n Key.F15 => ImGuiKey.F15,\n Key.F16 => ImGuiKey.F16,\n Key.F17 => ImGuiKey.F17,\n Key.F18 => ImGuiKey.F18,\n Key.F19 => ImGuiKey.F19,\n Key.F20 => ImGuiKey.F20,\n Key.F21 => ImGuiKey.F21,\n Key.F22 => ImGuiKey.F22,\n Key.F23 => ImGuiKey.F23,\n Key.F24 => ImGuiKey.F24,\n _ => ImGuiKey.None\n };\n }\n\n private unsafe void SetupRenderState(ImDrawDataPtr drawDataPtr, int framebufferWidth, int framebufferHeight)\n {\n // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill\n _gl.Enable(GLEnum.Blend);\n _gl.BlendEquation(GLEnum.FuncAdd);\n _gl.BlendFuncSeparate(GLEnum.SrcAlpha, GLEnum.OneMinusSrcAlpha, GLEnum.One, GLEnum.OneMinusSrcAlpha);\n _gl.Disable(GLEnum.CullFace);\n _gl.Disable(GLEnum.DepthTest);\n _gl.Disable(GLEnum.StencilTest);\n _gl.Enable(GLEnum.ScissorTest);\n#if !GLES && !LEGACY\n _gl.Disable(GLEnum.PrimitiveRestart);\n _gl.PolygonMode(GLEnum.FrontAndBack, GLEnum.Fill);\n#endif\n\n var L = drawDataPtr.DisplayPos.X;\n var R = drawDataPtr.DisplayPos.X + drawDataPtr.DisplaySize.X;\n var T = drawDataPtr.DisplayPos.Y;\n var B = drawDataPtr.DisplayPos.Y + drawDataPtr.DisplaySize.Y;\n\n Span orthoProjection = stackalloc float[] { 2.0f / (R - L), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (T - B), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, (R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f };\n\n _shader.Use();\n _gl.Uniform1(_attribLocationTex, 0);\n _gl.UniformMatrix4(_attribLocationProjMtx, 1, false, orthoProjection);\n _gl.CheckError(\"Projection\");\n\n _gl.BindSampler(0, 0);\n\n // Setup desired GL state\n // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)\n // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.\n _vertexArrayObject = _gl.GenVertexArray();\n _gl.BindVertexArray(_vertexArrayObject);\n _gl.CheckError(\"VAO\");\n\n // Bind vertex/index buffers and setup attributes for ImDrawVert\n _gl.BindBuffer(GLEnum.ArrayBuffer, _vboHandle);\n _gl.BindBuffer(GLEnum.ElementArrayBuffer, _elementsHandle);\n _gl.EnableVertexAttribArray((uint)_attribLocationVtxPos);\n _gl.EnableVertexAttribArray((uint)_attribLocationVtxUV);\n _gl.EnableVertexAttribArray((uint)_attribLocationVtxColor);\n _gl.VertexAttribPointer((uint)_attribLocationVtxPos, 2, GLEnum.Float, false, (uint)sizeof(ImDrawVert), (void*)0);\n _gl.VertexAttribPointer((uint)_attribLocationVtxUV, 2, GLEnum.Float, false, (uint)sizeof(ImDrawVert), (void*)8);\n _gl.VertexAttribPointer((uint)_attribLocationVtxColor, 4, GLEnum.UnsignedByte, true, (uint)sizeof(ImDrawVert), (void*)16);\n }\n\n private unsafe void RenderImDrawData(ImDrawDataPtr drawDataPtr)\n {\n var framebufferWidth = (int)(drawDataPtr.DisplaySize.X * drawDataPtr.FramebufferScale.X);\n var framebufferHeight = (int)(drawDataPtr.DisplaySize.Y * drawDataPtr.FramebufferScale.Y);\n if ( framebufferWidth <= 0 || framebufferHeight <= 0 )\n {\n return;\n }\n\n // Backup GL state\n _gl.GetInteger(GLEnum.ActiveTexture, out var lastActiveTexture);\n _gl.ActiveTexture(GLEnum.Texture0);\n\n _gl.GetInteger(GLEnum.CurrentProgram, out var lastProgram);\n _gl.GetInteger(GLEnum.TextureBinding2D, out var lastTexture);\n\n _gl.GetInteger(GLEnum.SamplerBinding, out var lastSampler);\n\n _gl.GetInteger(GLEnum.ArrayBufferBinding, out var lastArrayBuffer);\n _gl.GetInteger(GLEnum.VertexArrayBinding, out var lastVertexArrayObject);\n\n#if !GLES\n Span lastPolygonMode = stackalloc int[2];\n _gl.GetInteger(GLEnum.PolygonMode, lastPolygonMode);\n#endif\n\n Span lastScissorBox = stackalloc int[4];\n _gl.GetInteger(GLEnum.ScissorBox, lastScissorBox);\n\n _gl.GetInteger(GLEnum.BlendSrcRgb, out var lastBlendSrcRgb);\n _gl.GetInteger(GLEnum.BlendDstRgb, out var lastBlendDstRgb);\n\n _gl.GetInteger(GLEnum.BlendSrcAlpha, out var lastBlendSrcAlpha);\n _gl.GetInteger(GLEnum.BlendDstAlpha, out var lastBlendDstAlpha);\n\n _gl.GetInteger(GLEnum.BlendEquationRgb, out var lastBlendEquationRgb);\n _gl.GetInteger(GLEnum.BlendEquationAlpha, out var lastBlendEquationAlpha);\n\n var lastEnableBlend = _gl.IsEnabled(GLEnum.Blend);\n var lastEnableCullFace = _gl.IsEnabled(GLEnum.CullFace);\n var lastEnableDepthTest = _gl.IsEnabled(GLEnum.DepthTest);\n var lastEnableStencilTest = _gl.IsEnabled(GLEnum.StencilTest);\n var lastEnableScissorTest = _gl.IsEnabled(GLEnum.ScissorTest);\n\n#if !GLES && !LEGACY\n var lastEnablePrimitiveRestart = _gl.IsEnabled(GLEnum.PrimitiveRestart);\n#endif\n\n SetupRenderState(drawDataPtr, framebufferWidth, framebufferHeight);\n\n // Will project scissor/clipping rectangles into framebuffer space\n var clipOff = drawDataPtr.DisplayPos; // (0,0) unless using multi-viewports\n var clipScale = drawDataPtr.FramebufferScale; // (1,1) unless using retina display which are often (2,2)\n\n // Render command lists\n for ( var n = 0; n < drawDataPtr.CmdListsCount; n++ )\n {\n var cmdListPtr = drawDataPtr.CmdLists[n];\n\n // Upload vertex/index buffers\n\n _gl.BufferData(GLEnum.ArrayBuffer, (nuint)(cmdListPtr.VtxBuffer.Size * sizeof(ImDrawVert)), cmdListPtr.VtxBuffer.Data, GLEnum.StreamDraw);\n _gl.CheckError($\"Data Vert {n}\");\n _gl.BufferData(GLEnum.ElementArrayBuffer, (nuint)(cmdListPtr.IdxBuffer.Size * sizeof(ushort)), cmdListPtr.IdxBuffer.Data, GLEnum.StreamDraw);\n _gl.CheckError($\"Data Idx {n}\");\n\n for ( var cmd_i = 0; cmd_i < cmdListPtr.CmdBuffer.Size; cmd_i++ )\n {\n var cmdPtr = cmdListPtr.CmdBuffer[cmd_i];\n\n if ( cmdPtr.UserCallback != null )\n {\n throw new NotImplementedException();\n }\n\n Vector4 clipRect;\n clipRect.X = (cmdPtr.ClipRect.X - clipOff.X) * clipScale.X;\n clipRect.Y = (cmdPtr.ClipRect.Y - clipOff.Y) * clipScale.Y;\n clipRect.Z = (cmdPtr.ClipRect.Z - clipOff.X) * clipScale.X;\n clipRect.W = (cmdPtr.ClipRect.W - clipOff.Y) * clipScale.Y;\n\n if ( clipRect.X < framebufferWidth && clipRect.Y < framebufferHeight && clipRect.Z >= 0.0f && clipRect.W >= 0.0f )\n {\n // Apply scissor/clipping rectangle\n _gl.Scissor((int)clipRect.X, (int)(framebufferHeight - clipRect.W), (uint)(clipRect.Z - clipRect.X), (uint)(clipRect.W - clipRect.Y));\n _gl.CheckError(\"Scissor\");\n\n // Bind texture, Draw\n _gl.BindTexture(GLEnum.Texture2D, (uint)cmdPtr.TextureId.Handle);\n _gl.CheckError(\"Texture\");\n\n _gl.DrawElementsBaseVertex(GLEnum.Triangles, cmdPtr.ElemCount, GLEnum.UnsignedShort, (void*)(cmdPtr.IdxOffset * sizeof(ushort)), (int)cmdPtr.VtxOffset);\n _gl.CheckError(\"Draw\");\n }\n }\n }\n\n // Destroy the temporary VAO\n _gl.DeleteVertexArray(_vertexArrayObject);\n _vertexArrayObject = 0;\n\n // Restore modified GL state\n _gl.UseProgram((uint)lastProgram);\n _gl.BindTexture(GLEnum.Texture2D, (uint)lastTexture);\n\n _gl.BindSampler(0, (uint)lastSampler);\n\n _gl.ActiveTexture((GLEnum)lastActiveTexture);\n\n _gl.BindVertexArray((uint)lastVertexArrayObject);\n\n _gl.BindBuffer(GLEnum.ArrayBuffer, (uint)lastArrayBuffer);\n _gl.BlendEquationSeparate((GLEnum)lastBlendEquationRgb, (GLEnum)lastBlendEquationAlpha);\n _gl.BlendFuncSeparate((GLEnum)lastBlendSrcRgb, (GLEnum)lastBlendDstRgb, (GLEnum)lastBlendSrcAlpha, (GLEnum)lastBlendDstAlpha);\n\n if ( lastEnableBlend )\n {\n _gl.Enable(GLEnum.Blend);\n }\n else\n {\n _gl.Disable(GLEnum.Blend);\n }\n\n if ( lastEnableCullFace )\n {\n _gl.Enable(GLEnum.CullFace);\n }\n else\n {\n _gl.Disable(GLEnum.CullFace);\n }\n\n if ( lastEnableDepthTest )\n {\n _gl.Enable(GLEnum.DepthTest);\n }\n else\n {\n _gl.Disable(GLEnum.DepthTest);\n }\n\n if ( lastEnableStencilTest )\n {\n _gl.Enable(GLEnum.StencilTest);\n }\n else\n {\n _gl.Disable(GLEnum.StencilTest);\n }\n\n if ( lastEnableScissorTest )\n {\n _gl.Enable(GLEnum.ScissorTest);\n }\n else\n {\n _gl.Disable(GLEnum.ScissorTest);\n }\n\n#if !GLES && !LEGACY\n if ( lastEnablePrimitiveRestart )\n {\n _gl.Enable(GLEnum.PrimitiveRestart);\n }\n else\n {\n _gl.Disable(GLEnum.PrimitiveRestart);\n }\n\n _gl.PolygonMode(GLEnum.FrontAndBack, (GLEnum)lastPolygonMode[0]);\n#endif\n\n _gl.Scissor(lastScissorBox[0], lastScissorBox[1], (uint)lastScissorBox[2], (uint)lastScissorBox[3]);\n }\n\n private void CreateDeviceResources()\n {\n // Backup GL state\n\n _gl.GetInteger(GLEnum.TextureBinding2D, out var lastTexture);\n _gl.GetInteger(GLEnum.ArrayBufferBinding, out var lastArrayBuffer);\n _gl.GetInteger(GLEnum.VertexArrayBinding, out var lastVertexArray);\n\n var vertexSource =\n @\"#version 330\n layout (location = 0) in vec2 Position;\n layout (location = 1) in vec2 UV;\n layout (location = 2) in vec4 Color;\n uniform mat4 ProjMtx;\n out vec2 Frag_UV;\n out vec4 Frag_Color;\n void main()\n {\n Frag_UV = UV;\n Frag_Color = Color;\n gl_Position = ProjMtx * vec4(Position.xy,0,1);\n }\";\n\n var fragmentSource =\n @\"#version 330\n in vec2 Frag_UV;\n in vec4 Frag_Color;\n uniform sampler2D Texture;\n layout (location = 0) out vec4 Out_Color;\n void main()\n {\n Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n }\";\n\n _shader = new Shader(_gl, vertexSource, fragmentSource);\n\n _attribLocationTex = _shader.GetUniformLocation(\"Texture\");\n _attribLocationProjMtx = _shader.GetUniformLocation(\"ProjMtx\");\n _attribLocationVtxPos = _shader.GetAttribLocation(\"Position\");\n _attribLocationVtxUV = _shader.GetAttribLocation(\"UV\");\n _attribLocationVtxColor = _shader.GetAttribLocation(\"Color\");\n\n _vboHandle = _gl.GenBuffer();\n _elementsHandle = _gl.GenBuffer();\n\n RecreateFontDeviceTexture();\n\n // Restore modified GL state\n _gl.BindTexture(GLEnum.Texture2D, (uint)lastTexture);\n _gl.BindBuffer(GLEnum.ArrayBuffer, (uint)lastArrayBuffer);\n\n _gl.BindVertexArray((uint)lastVertexArray);\n\n _gl.CheckError(\"End of ImGui setup\");\n }\n\n /// \n /// Creates the texture used to render text.\n /// \n private unsafe void RecreateFontDeviceTexture()\n {\n // Build texture atlas\n var io = ImGui.GetIO();\n byte* pixels = null;\n var width = 0;\n var height = 0;\n var bytesPerPixel = 0;\n io.Fonts.GetTexDataAsRGBA32(ref pixels, ref width, ref height, ref bytesPerPixel); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.\n\n // Upload texture to graphics system\n _gl.GetInteger(GLEnum.TextureBinding2D, out var lastTexture);\n\n _fontTexture = new Texture(_gl, width, height, new IntPtr(pixels));\n _fontTexture.Bind();\n _fontTexture.SetMagFilter(TextureMagFilter.Linear);\n _fontTexture.SetMinFilter(TextureMinFilter.Linear);\n\n // Store our identifier\n io.Fonts.SetTexID(new ImTextureID(_fontTexture.GlTexture));\n\n // Restore state\n _gl.BindTexture(GLEnum.Texture2D, (uint)lastTexture);\n }\n\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n private delegate void SetClipboardDelegate(IntPtr data);\n\n [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n private delegate IntPtr GetClipboardDelegate();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Utils/TextExtensions.cs", "using System.Text;\n\nnamespace PersonaEngine.Lib.Utils;\n\npublic static class TextExtensions\n{\n public static string SafeNormalizeUnicode(this string input)\n {\n if ( string.IsNullOrEmpty(input) )\n {\n return input;\n }\n\n try\n {\n return input.Normalize(NormalizationForm.FormKC);\n }\n catch (ArgumentException)\n {\n // Failed,try to remove invalid unicode chars\n }\n\n // Remove invalid characters\n var result = new StringBuilder(input.Length);\n var currentPos = 0;\n\n while ( currentPos < input.Length )\n {\n var invalidPos = FindInvalidCharIndex(input[currentPos..]);\n if ( invalidPos == -1 )\n {\n // No more invalid characters found, add the rest\n result.Append(input.AsSpan(currentPos));\n\n break;\n }\n\n // Add the valid portion before the invalid character\n if ( invalidPos > 0 )\n {\n result.Append(input.AsSpan(currentPos, invalidPos));\n }\n\n // Skip the invalid character (or pair)\n if ( input[currentPos + invalidPos] >= 0xD800 && input[currentPos + invalidPos] <= 0xDBFF )\n {\n // Skip surrogate pair\n currentPos += invalidPos + 2;\n }\n else\n {\n // Skip single character\n currentPos += invalidPos + 1;\n }\n }\n\n // Now normalize the cleaned string\n return result.ToString().Normalize(NormalizationForm.FormKC);\n }\n\n /// \n /// Searches invalid charachters (non-chars defined in Unicode standard and invalid surrogate pairs) in a string\n /// \n /// the string to search for invalid chars \n /// the index of the first bad char or -1 if no bad char is found\n private static int FindInvalidCharIndex(string aString)\n {\n for ( var i = 0; i < aString.Length; i++ )\n {\n int ch = aString[i];\n if ( ch < 0xD800 ) // char is up to first high surrogate\n {\n continue;\n }\n\n if ( ch is >= 0xD800 and <= 0xDBFF )\n {\n // found high surrogate -> check surrogate pair\n i++;\n if ( i == aString.Length )\n {\n // last char is high surrogate, so it is missing its pair\n return i - 1;\n }\n\n int chlow = aString[i];\n if ( chlow is < 0xDC00 or > 0xDFFF )\n {\n // did not found a low surrogate after the high surrogate\n return i - 1;\n }\n\n // convert to UTF32 - like in Char.ConvertToUtf32(highSurrogate, lowSurrogate)\n ch = (ch - 0xD800) * 0x400 + (chlow - 0xDC00) + 0x10000;\n if ( ch > 0x10FFFF )\n {\n // invalid Unicode code point - maximum excedeed\n return i;\n }\n\n if ( (ch & 0xFFFE) == 0xFFFE )\n {\n // other non-char found\n return i;\n }\n\n // found a good surrogate pair\n continue;\n }\n\n if ( ch is >= 0xDC00 and <= 0xDFFF )\n {\n // unexpected low surrogate\n return i;\n }\n\n if ( ch is >= 0xFDD0 and <= 0xFDEF )\n {\n // non-chars are considered invalid by System.Text.Encoding.GetBytes() and String.Normalize()\n return i;\n }\n\n if ( (ch & 0xFFFE) == 0xFFFE )\n {\n // other non-char found\n return i;\n }\n }\n\n return -1;\n }\n\n public static int GetWordCount(this string text)\n {\n if ( string.IsNullOrWhiteSpace(text) )\n {\n return 0;\n }\n\n var wordCount = 0;\n var inWord = false;\n\n foreach ( var c in text )\n {\n if ( char.IsWhiteSpace(c) )\n {\n inWord = false;\n }\n else\n {\n if ( inWord )\n {\n continue;\n }\n\n wordCount++;\n inWord = true;\n }\n }\n\n return wordCount;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/OnnxRVC.cs", "using System.Buffers;\n\nusing Microsoft.ML.OnnxRuntime;\nusing Microsoft.ML.OnnxRuntime.Tensors;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class OnnxRVC : IDisposable\n{\n private readonly ArrayPool _arrayPool;\n\n private readonly int _hopSize;\n\n private readonly InferenceSession _model;\n\n private readonly ArrayPool _shortArrayPool;\n\n // Preallocated buffers and tensors\n private readonly DenseTensor _speakerIdTensor;\n\n private readonly ContentVec _vecModel;\n\n public OnnxRVC(string modelPath, int hopsize, string vecPath)\n {\n var options = new SessionOptions {\n EnableMemoryPattern = true,\n ExecutionMode = ExecutionMode.ORT_PARALLEL,\n InterOpNumThreads = Environment.ProcessorCount,\n IntraOpNumThreads = Environment.ProcessorCount,\n GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,\n LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR\n };\n\n options.AppendExecutionProvider_CUDA();\n \n _model = new InferenceSession(modelPath, options);\n _hopSize = hopsize;\n _vecModel = new ContentVec(vecPath);\n\n // Preallocate the speaker ID tensor\n _speakerIdTensor = new DenseTensor(new[] { 1 });\n\n // Create array pools for temporary buffers\n _arrayPool = ArrayPool.Shared;\n _shortArrayPool = ArrayPool.Shared;\n }\n\n public void Dispose()\n {\n _model?.Dispose();\n _vecModel?.Dispose();\n }\n\n public int ProcessAudio(ReadOnlyMemory inputAudio, Memory outputAudio,\n IF0Predictor f0Predictor, int speakerId, int f0UpKey)\n {\n // Early exit if input is empty\n if ( inputAudio.Length == 0 )\n {\n return 0;\n }\n\n // Check if output buffer is large enough\n if ( outputAudio.Length < inputAudio.Length )\n {\n throw new ArgumentException(\"Output buffer is too small\", nameof(outputAudio));\n }\n\n // Set the speaker ID\n _speakerIdTensor[0] = speakerId;\n\n // Process the audio\n return ProcessInPlace(inputAudio, outputAudio, f0Predictor, _speakerIdTensor, f0UpKey);\n }\n\n private int ProcessInPlace(ReadOnlyMemory input, Memory output,\n IF0Predictor f0Predictor,\n DenseTensor speakerIdTensor, int f0UpKey)\n {\n const int f0Min = 50;\n const int f0Max = 1100;\n var f0MelMin = 1127 * Math.Log(1 + f0Min / 700.0);\n var f0MelMax = 1127 * Math.Log(1 + f0Max / 700.0);\n\n if ( input.Length / 16000.0 > 30.0 )\n {\n throw new Exception(\"Audio segment is too long (>30s)\");\n }\n\n // Calculate original scale for normalization (matching original implementation)\n var minValue = float.MaxValue;\n var maxValue = float.MinValue;\n var inputSpan = input.Span;\n for ( var i = 0; i < input.Length; i++ )\n {\n minValue = Math.Min(minValue, inputSpan[i]);\n maxValue = Math.Max(maxValue, inputSpan[i]);\n }\n\n var originalScale = maxValue - minValue;\n\n // Get the hubert features\n var hubert = _vecModel.Forward(input);\n\n // Repeat and transpose the features\n var hubertRepeated = RVCUtils.RepeatTensor(hubert, 2);\n hubertRepeated = RVCUtils.Transpose(hubertRepeated, 0, 2, 1);\n\n hubert = null; // Allow for garbage collection\n\n var hubertLength = hubertRepeated.Dimensions[1];\n var hubertLengthTensor = new DenseTensor(new[] { 1 }) { [0] = hubertLength };\n\n // Allocate buffers for F0 calculations\n var f0Buffer = _arrayPool.Rent(hubertLength);\n var f0Memory = new Memory(f0Buffer, 0, hubertLength);\n\n try\n {\n // Calculate F0 directly into buffer\n f0Predictor.ComputeF0(input, f0Memory, hubertLength);\n\n // Create pitch tensors\n var pitchBuffer = _arrayPool.Rent(hubertLength);\n var pitchTensor = new DenseTensor(new[] { 1, hubertLength });\n var pitchfTensor = new DenseTensor(new[] { 1, hubertLength });\n\n try\n {\n // Apply pitch shift and convert to mel scale\n for ( var i = 0; i < hubertLength; i++ )\n {\n // Apply pitch shift\n var shiftedF0 = f0Buffer[i] * (float)Math.Pow(2, f0UpKey / 12.0);\n pitchfTensor[0, i] = shiftedF0;\n\n // Convert to mel scale for pitch\n var f0Mel = 1127 * Math.Log(1 + shiftedF0 / 700.0);\n if ( f0Mel > 0 )\n {\n f0Mel = (f0Mel - f0MelMin) * 254 / (f0MelMax - f0MelMin) + 1;\n f0Mel = Math.Round(f0Mel);\n }\n\n if ( f0Mel <= 1 )\n {\n f0Mel = 1;\n }\n\n if ( f0Mel > 255 )\n {\n f0Mel = 255;\n }\n\n pitchTensor[0, i] = (long)f0Mel;\n }\n\n // Generate random noise tensor\n var rndTensor = new DenseTensor(new[] { 1, 192, hubertLength });\n var random = new Random();\n for ( var i = 0; i < 192 * hubertLength; i++ )\n {\n rndTensor[0, i / hubertLength, i % hubertLength] = (float)random.NextDouble();\n }\n\n // Run the model\n var outWav = Forward(hubertRepeated, hubertLengthTensor, pitchTensor,\n pitchfTensor, speakerIdTensor, rndTensor);\n\n // Apply padding to match original implementation\n // (adding padding at the end only, like in original Pad method)\n var paddedSize = outWav.Length + 2 * _hopSize;\n var paddedOutput = _shortArrayPool.Rent(paddedSize);\n try\n {\n // Copy original output to the beginning of padded output\n for ( var i = 0; i < outWav.Length; i++ )\n {\n paddedOutput[i] = outWav[i];\n }\n // Rest of array is already zeroed when rented from pool\n\n // Find min and max values for normalization\n var minOutValue = short.MaxValue;\n var maxOutValue = short.MinValue;\n for ( var i = 0; i < outWav.Length; i++ )\n {\n minOutValue = Math.Min(minOutValue, outWav[i]);\n maxOutValue = Math.Max(maxOutValue, outWav[i]);\n }\n\n // Copy the output to the buffer with normalization matching original\n var outputSpan = output.Span;\n if ( outputSpan.Length < paddedSize )\n {\n throw new InvalidOperationException($\"Output buffer too small. Needed {paddedSize}, but only had {outputSpan.Length}\");\n }\n\n var maxLen = Math.Min(paddedSize, outputSpan.Length);\n\n // Apply normalization that matches the original implementation\n float range = maxOutValue - minOutValue;\n if ( range > 0 )\n {\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = paddedOutput[i] * originalScale / range;\n }\n }\n else\n {\n // Handle edge case where all values are the same\n for ( var i = 0; i < maxLen; i++ )\n {\n outputSpan[i] = 0;\n }\n }\n\n return outWav.Length;\n }\n finally\n {\n _shortArrayPool.Return(paddedOutput);\n }\n }\n finally\n {\n _arrayPool.Return(pitchBuffer);\n }\n }\n finally\n {\n _arrayPool.Return(f0Buffer);\n }\n }\n\n private short[] Forward(DenseTensor hubert, DenseTensor hubertLength,\n DenseTensor pitch, DenseTensor pitchf,\n DenseTensor speakerId, DenseTensor noise)\n {\n var inputs = new List {\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(0), hubert),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(1), hubertLength),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(2), pitch),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(3), pitchf),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(4), speakerId),\n NamedOnnxValue.CreateFromTensor(_model.InputMetadata.Keys.ElementAt(5), noise)\n };\n\n var results = _model.Run(inputs);\n var output = results.First().AsTensor();\n\n return output.Select(x => (short)(x * 32767)).ToArray();\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/VAD/SileroVadDetector.cs", "using System.Buffers;\nusing System.Runtime.CompilerServices;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Utils;\n\nnamespace PersonaEngine.Lib.ASR.VAD;\n\ninternal class SileroVadDetector : IVadDetector\n{\n private readonly int _minSilenceSamples;\n\n private readonly int _minSpeechSamples;\n\n private readonly SileroVadOnnxModel _model;\n\n private readonly float _negThreshold;\n\n private readonly float _threshold;\n\n public SileroVadDetector(VadDetectorOptions vadDetectorOptions, SileroVadOptions sileroVadOptions)\n {\n _model = new SileroVadOnnxModel(sileroVadOptions.ModelPath);\n _threshold = sileroVadOptions.Threshold;\n _negThreshold = _threshold - sileroVadOptions.ThresholdGap;\n _minSpeechSamples = (int)(16d * vadDetectorOptions.MinSpeechDuration.TotalMilliseconds);\n _minSilenceSamples = (int)(16d * vadDetectorOptions.MinSilenceDuration.TotalMilliseconds);\n }\n\n public async IAsyncEnumerable DetectSegmentsAsync(IAudioSource source, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n ValidateSource(source);\n\n foreach ( var segment in DetectSegments(await source.GetSamplesAsync(0, cancellationToken: cancellationToken)) )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n yield return segment;\n }\n }\n\n private IEnumerable DetectSegments(Memory samples)\n {\n var state = _model.CreateInferenceState();\n int? startingIndex = null;\n int? startingSilenceIndex = null;\n\n for ( var i = 0; i < samples.Length - SileroConstants.BatchSize; i += SileroConstants.BatchSize )\n {\n Memory slice;\n float[]? rentedMemory = null;\n try\n {\n if ( i == 0 )\n {\n // the first batch will have the empty context (which we need to copy at the beggining of the slice)\n rentedMemory = ArrayPool.Shared.Rent(SileroConstants.ContextSize + SileroConstants.BatchSize);\n Array.Clear(rentedMemory, 0, SileroConstants.ContextSize);\n samples.Span.Slice(0, SileroConstants.BatchSize).CopyTo(rentedMemory.AsSpan(SileroConstants.ContextSize));\n slice = rentedMemory.AsMemory(0, SileroConstants.BatchSize + SileroConstants.ContextSize);\n }\n else\n {\n slice = samples.Slice(i - SileroConstants.ContextSize, SileroConstants.BatchSize + SileroConstants.ContextSize);\n }\n\n var prob = _model.Call(slice, state);\n if ( !startingIndex.HasValue )\n {\n if ( prob > _threshold )\n {\n startingIndex = i;\n }\n\n continue;\n }\n\n // We are in speech\n if ( prob > _threshold )\n {\n startingSilenceIndex = null;\n\n continue;\n }\n\n if ( prob > _negThreshold )\n {\n // We are still in speech and the current batch is between the threshold and the negative threshold\n // We continue to the next batch\n continue;\n }\n\n if ( startingSilenceIndex == null )\n {\n startingSilenceIndex = i;\n\n continue;\n }\n\n var silenceLength = i - startingSilenceIndex.Value;\n\n if ( silenceLength > _minSilenceSamples )\n {\n // We have silence after speech exceeding the minimum silence duration\n var length = i - startingIndex.Value;\n if ( length >= _minSpeechSamples )\n {\n yield return new VadSegment { StartTime = TimeSpan.FromMilliseconds(startingIndex.Value * 1000d / SileroConstants.SampleRate), Duration = TimeSpan.FromMilliseconds(length * 1000d / SileroConstants.SampleRate) };\n }\n\n startingIndex = null;\n startingSilenceIndex = null;\n }\n }\n finally\n {\n if ( rentedMemory != null )\n {\n ArrayPool.Shared.Return(rentedMemory, ArrayPoolConfig.ClearOnReturn);\n }\n }\n }\n\n // The last segment if it was already started (might be incomplete for sources that are not yet finished)\n if ( startingIndex.HasValue )\n {\n var length = samples.Length - startingIndex.Value;\n if ( length >= _minSpeechSamples )\n {\n yield return new VadSegment { StartTime = TimeSpan.FromMilliseconds(startingIndex.Value * 1000d / SileroConstants.SampleRate), Duration = TimeSpan.FromMilliseconds(length * 1000d / SileroConstants.SampleRate), IsIncomplete = true };\n }\n }\n }\n\n private static void ValidateSource(IAudioSource source)\n {\n if ( source.ChannelCount != 1 )\n {\n throw new NotSupportedException(\"Only mono-channel audio is supported. Consider one channel aggregation on the audio source.\");\n }\n\n if ( source.SampleRate != 16000 )\n {\n throw new NotSupportedException(\"Only 16 kHz audio is supported. Consider resampling before calling this transcriptor.\");\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/SampleSerializer.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// Serializer for converting float samples to and from PCM byte buffers.\n/// \n/// \n/// For now, this class only supports 8, 16, 24, 32 and 64 bits per sample.\n/// \npublic static class SampleSerializer\n{\n /// \n /// Deserialize the PCM byte buffer into a new float samples.\n /// \n /// \n public static Memory Deserialize(ReadOnlyMemory buffer, ushort bitsPerSample)\n {\n var floatBuffer = new float[buffer.Length / (bitsPerSample / 8)];\n Deserialize(buffer, floatBuffer, bitsPerSample);\n\n return floatBuffer.AsMemory();\n }\n\n /// \n /// Serializes the float samples into a PCM byte buffer.\n /// \n /// \n public static Memory Serialize(ReadOnlyMemory samples, ushort bitsPerSample)\n {\n // Transform to long as we might overflow the int because of the multiplications (even if we cast to int later)\n var memoryBufferLength = (long)samples.Length * bitsPerSample / 8;\n\n var buffer = new byte[(int)memoryBufferLength];\n Serialize(samples, buffer, bitsPerSample);\n\n return buffer.AsMemory();\n }\n\n /// \n /// Serializes the float samples into a PCM byte buffer.\n /// \n public static void Serialize(ReadOnlyMemory samples, Memory buffer, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n var totalSamples = samples.Length;\n var totalBytes = totalSamples * bytesPerSample;\n\n if ( buffer.Length < totalBytes )\n {\n throw new ArgumentException(\"Buffer too small to hold the serialized data.\");\n }\n\n var samplesSpan = samples.Span;\n var bufferSpan = buffer.Span;\n\n var sampleIndex = 0;\n var bufferIndex = 0;\n\n while ( sampleIndex < totalSamples )\n {\n var sampleValue = samplesSpan[sampleIndex];\n WriteSample(bufferSpan, bufferIndex, sampleValue, bitsPerSample);\n bufferIndex += bytesPerSample;\n sampleIndex++;\n }\n }\n\n /// \n /// Deserializes the PCM byte buffer into float samples.\n /// \n public static void Deserialize(ReadOnlyMemory buffer, Memory samples, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n var totalSamples = buffer.Length / bytesPerSample;\n\n if ( samples.Length < totalSamples )\n {\n throw new ArgumentException(\"Samples buffer is too small to hold the deserialized data.\");\n }\n\n var bufferSpan = buffer.Span;\n var samplesSpan = samples.Span;\n\n var sampleIndex = 0;\n var bufferIndex = 0;\n\n while ( bufferIndex < bufferSpan.Length )\n {\n var sampleValue = ReadSample(bufferSpan, ref bufferIndex, bitsPerSample);\n samplesSpan[sampleIndex++] = sampleValue;\n // bufferIndex is already incremented inside ReadSample\n }\n }\n\n /// \n /// Reads a single sample from the byte span, considering the bit index and sample bit depth.\n /// \n internal static float ReadSample(ReadOnlySpan span, ref int index, ushort bitsPerSample)\n {\n var bytesPerSample = bitsPerSample / 8;\n\n float sampleValue;\n\n switch ( bitsPerSample )\n {\n case 8:\n var sampleByte = span[index];\n sampleValue = sampleByte / 127.5f - 1.0f;\n\n break;\n\n case 16:\n var sampleShort = BinaryPrimitives.ReadInt16LittleEndian(span.Slice(index, 2));\n sampleValue = sampleShort / 32768f;\n\n break;\n\n case 24:\n var sample24Bit = ReadInt24LittleEndian(span.Slice(index, 3));\n sampleValue = sample24Bit / 8388608f;\n\n break;\n\n case 32:\n var sampleInt = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(index, 4));\n sampleValue = sampleInt / 2147483648f;\n\n break;\n\n case 64:\n var sampleLong = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(index, 8));\n sampleValue = sampleLong / 9223372036854775808f;\n\n break;\n\n default:\n throw new NotSupportedException($\"Bits per sample {bitsPerSample} is not supported.\");\n }\n\n index += bytesPerSample;\n\n return sampleValue;\n }\n\n /// \n /// Writes a single sample into the byte span at the specified index.\n /// \n internal static void WriteSample(Span span, int index, float sampleValue, ushort bitsPerSample)\n {\n switch ( bitsPerSample )\n {\n case 8:\n var sampleByte = (byte)((sampleValue + 1.0f) * 127.5f);\n span[index] = sampleByte;\n\n break;\n\n case 16:\n var sampleShort = (short)(sampleValue * 32767f);\n BinaryPrimitives.WriteInt16LittleEndian(span.Slice(index, 2), sampleShort);\n\n break;\n\n case 24:\n var sample24Bit = (int)(sampleValue * 8388607f);\n WriteInt24LittleEndian(span.Slice(index, 3), sample24Bit);\n\n break;\n\n case 32:\n var sampleInt = (int)(sampleValue * 2147483647f);\n BinaryPrimitives.WriteInt32LittleEndian(span.Slice(index, 4), sampleInt);\n\n break;\n\n case 64:\n var sampleLong = (long)(sampleValue * 9223372036854775807f);\n BinaryPrimitives.WriteInt64LittleEndian(span.Slice(index, 8), sampleLong);\n\n break;\n\n default:\n throw new NotSupportedException($\"Bits per sample {bitsPerSample} is not supported.\");\n }\n }\n\n /// \n /// Reads a 24-bit integer from a byte span in little-endian order.\n /// \n private static int ReadInt24LittleEndian(ReadOnlySpan span)\n {\n int b0 = span[0];\n int b1 = span[1];\n int b2 = span[2];\n var sample = (b2 << 16) | (b1 << 8) | b0;\n\n // Sign-extend to 32 bits if necessary\n if ( (sample & 0x800000) != 0 )\n {\n sample |= unchecked((int)0xFF000000);\n }\n\n return sample;\n }\n\n /// \n /// Writes a 24-bit integer to a byte span in little-endian order.\n /// \n private static void WriteInt24LittleEndian(Span span, int value)\n {\n span[0] = (byte)(value & 0xFF);\n span[1] = (byte)((value >> 8) & 0xFF);\n span[2] = (byte)((value >> 16) & 0xFF);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/MergedMemoryChunks.cs", "using System.Buffers.Binary;\n\nnamespace PersonaEngine.Lib.Audio;\n\n/// \n/// This is a little helper for using multiple chunks of memory without writing it to auxiliary buffers\n/// \n/// \n/// It is used to consume the data that was appended in multiple calls and couldn't be used previously.\n/// Note: If the requested chunks are not contiguous, the data will be copied to a new buffer.\n/// \npublic class MergedMemoryChunks\n{\n private readonly List> chunks = [];\n\n private int currentChunkIndex;\n\n public MergedMemoryChunks(ReadOnlyMemory initialChunk)\n {\n chunks.Add(initialChunk);\n Length = initialChunk.Length;\n }\n\n public MergedMemoryChunks() { }\n\n /// \n /// The total length of the chunks\n /// \n public long Length { get; private set; }\n\n /// \n /// The current position in the chunks\n /// \n public long Position { get; private set; }\n\n /// \n /// The absolute position of the current chunk\n /// \n public long AbsolutePositionOfCurrentChunk { get; private set; }\n\n public void AddChunk(ReadOnlyMemory newChunk)\n {\n chunks.Add(newChunk);\n Length += newChunk.Length;\n }\n\n /// \n /// Tries to skip the given number of bytes in the chunks, advancing the position.\n /// \n public bool TrySkip(uint count)\n {\n var bytesToSkip = count;\n while ( bytesToSkip > 0 )\n {\n var positionInCurrentChunk = Position - AbsolutePositionOfCurrentChunk;\n var currentChunk = chunks[currentChunkIndex];\n if ( positionInCurrentChunk + bytesToSkip <= currentChunk.Length )\n {\n Position += bytesToSkip;\n\n return true;\n }\n\n if ( currentChunkIndex + 1 == chunks.Count )\n {\n return false;\n }\n\n var remainingInCurrentChunk = (int)(currentChunk.Length - positionInCurrentChunk);\n\n currentChunkIndex++;\n\n Position += remainingInCurrentChunk;\n AbsolutePositionOfCurrentChunk = Position;\n bytesToSkip -= (uint)remainingInCurrentChunk;\n }\n\n return true;\n }\n\n /// \n /// Restarts the reading from the beginning of the chunks\n /// \n public void RestartRead()\n {\n currentChunkIndex = 0;\n AbsolutePositionOfCurrentChunk = 0;\n Position = 0;\n }\n\n /// \n /// Gets a slice of the given size from the chunks\n /// \n /// \n /// If the data will span multiple chunks, it will be copied to a new buffer.\n /// \n public ReadOnlyMemory GetChunk(int size)\n {\n var positionInCurrentChunk = (int)(Position - AbsolutePositionOfCurrentChunk);\n var currentChunk = chunks[currentChunkIndex];\n // First, we try to just slice the current chunk if possible\n if ( currentChunk.Length >= positionInCurrentChunk + size )\n {\n Position += size;\n if ( currentChunk.Length == positionInCurrentChunk + size )\n {\n currentChunkIndex++;\n AbsolutePositionOfCurrentChunk = Position;\n }\n\n return currentChunk.Slice(positionInCurrentChunk, size);\n }\n\n // We cannot slice it, so we need to compose it\n var buffer = new byte[size];\n var bufferIndex = 0;\n var remainingSize = size;\n while ( remainingSize > 0 )\n {\n var currentChunkAddressable = currentChunk.Slice(positionInCurrentChunk, Math.Min(remainingSize, currentChunk.Length - positionInCurrentChunk));\n\n remainingSize -= currentChunkAddressable.Length;\n Position += currentChunkAddressable.Length;\n currentChunkAddressable.CopyTo(buffer.AsMemory(bufferIndex));\n bufferIndex += currentChunkAddressable.Length;\n if ( remainingSize > 0 && currentChunkIndex >= chunks.Count )\n {\n throw new InvalidOperationException($\"Not enough data was available in the chunks to read {size} bytes.\");\n }\n\n if ( remainingSize > 0 )\n {\n positionInCurrentChunk = 0;\n currentChunkIndex++;\n AbsolutePositionOfCurrentChunk = Position;\n currentChunk = chunks[currentChunkIndex];\n }\n }\n\n return buffer.AsMemory();\n }\n\n /// \n /// Reads a 32-bit unsigned integer from the chunks\n /// \n public uint ReadUInt32LittleEndian()\n {\n var chunk = GetChunk(4);\n\n return BinaryPrimitives.ReadUInt32LittleEndian(chunk.Span);\n }\n\n /// \n /// Reads a 16-bit unsigned integer from the chunks\n /// \n public ushort ReadUInt16LittleEndian()\n {\n var chunk = GetChunk(2);\n\n return BinaryPrimitives.ReadUInt16LittleEndian(chunk.Span);\n }\n\n /// \n /// Reads a 8-bit unsigned integer from the chunks\n /// \n /// \n /// \n public byte ReadByte()\n {\n var chunk = GetChunk(1);\n\n return chunk.Span[0];\n }\n\n public short ReadInt16LittleEndian()\n {\n var chunk = GetChunk(2);\n\n return BinaryPrimitives.ReadInt16LittleEndian(chunk.Span);\n }\n\n public int ReadInt24LittleEndian()\n {\n var chunk = GetChunk(3);\n\n return chunk.Span[0] | (chunk.Span[1] << 8) | (chunk.Span[2] << 16);\n }\n\n public int ReadInt32LittleEndian()\n {\n var chunk = GetChunk(4);\n\n return BinaryPrimitives.ReadInt32LittleEndian(chunk.Span);\n }\n\n public long ReadInt64LittleEndian()\n {\n var chunk = GetChunk(8);\n\n return BinaryPrimitives.ReadInt64LittleEndian(chunk.Span);\n }\n\n /// \n /// Copies the content of the current chunks to a single buffer\n /// \n /// \n public byte[] ToArray()\n {\n var buffer = new byte[Length];\n var bufferIndex = 0;\n foreach ( var chunk in chunks )\n {\n chunk.Span.CopyTo(buffer.AsSpan(bufferIndex));\n bufferIndex += chunk.Length;\n }\n\n return buffer;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Profanity/ProfanityDetector.cs", "using Microsoft.Extensions.Logging;\n\nnamespace PersonaEngine.Lib.TTS.Profanity;\n\n/// \n/// A profanity detector that uses an ONNX model under the hood.\n/// It supports DI for logging, configurable filter threshold, and a benchmarking utility.\n/// \npublic class ProfanityDetector : IDisposable\n{\n private readonly ILogger _logger;\n\n private readonly ProfanityDetectorOnnx _onnxDetector;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logger injected via dependency injection.\n /// Optional path to the ONNX model file.\n /// Optional path to the vocabulary file for tokenization.\n public ProfanityDetector(ILogger logger)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _logger.LogInformation(\"Initializing ProfanityDetector\");\n _onnxDetector = new ProfanityDetectorOnnx();\n }\n\n /// \n /// Gets or sets the threshold for detecting any profanity.\n /// If the model's score is below this threshold, the sentence is considered clean.\n /// \n public float FilterThreshold { get; set; } = 0.5f;\n\n /// \n /// Gets or sets the threshold for moderate profanity.\n /// \n public float ModerateThreshold { get; set; } = 0.75f;\n\n /// \n /// Gets or sets the threshold for severe profanity.\n /// \n public float SevereThreshold { get; set; } = 0.9f;\n\n public void Dispose() { _onnxDetector.Dispose(); }\n\n /// \n /// Evaluates the given sentence and determines the severity of profanity.\n /// \n /// The sentence to evaluate.\n /// \n /// A enum value indicating the level of profanity:\n /// Clean, Mild, Moderate, or Severe.\n /// \n public ProfanitySeverity EvaluateProfanity(string sentence)\n {\n if ( string.IsNullOrWhiteSpace(sentence) )\n {\n _logger.LogWarning(\"Empty or whitespace sentence provided.\");\n\n return ProfanitySeverity.Clean;\n }\n\n var score = _onnxDetector.Run(sentence);\n _logger.LogDebug(\"Sentence: \\\"{sentence}\\\" scored {score}.\", sentence, score);\n\n if ( score < FilterThreshold )\n {\n return ProfanitySeverity.Clean;\n }\n\n if ( score < ModerateThreshold )\n {\n return ProfanitySeverity.Mild;\n }\n\n if ( score < SevereThreshold )\n {\n return ProfanitySeverity.Moderate;\n }\n\n return ProfanitySeverity.Severe;\n }\n\n /// \n /// Benchmarks the profanity filter using provided test data.\n /// Each test item consists of a sentence and the expected outcome (true if profane, false otherwise).\n /// For benchmarking purposes, any result other than is considered profane.\n /// Returns useful statistics to help calibrate the filter thresholds.\n /// \n /// A collection of test sentences with their expected results.\n /// A instance containing detailed metrics.\n public BenchmarkResult Benchmark(IEnumerable<(string Sentence, bool ExpectedIsProfane)> testData)\n {\n if ( testData == null )\n {\n throw new ArgumentNullException(nameof(testData));\n }\n\n int total = 0,\n truePositives = 0,\n falsePositives = 0,\n trueNegatives = 0,\n falseNegatives = 0;\n\n foreach ( var (sentence, expected) in testData )\n {\n total++;\n var severity = EvaluateProfanity(sentence);\n // For benchmarking, any severity other than Clean is considered profane.\n var actual = severity != ProfanitySeverity.Clean;\n\n if ( expected && actual )\n {\n truePositives++;\n }\n else if ( !expected && actual )\n {\n falsePositives++;\n }\n else if ( !expected && !actual )\n {\n trueNegatives++;\n }\n else if ( expected && !actual )\n {\n falseNegatives++;\n }\n\n _logger.LogDebug(\"Benchmarking sentence: \\\"{sentence}\\\" | Severity: {severity} | Expected: {expected} | Actual: {actual}\",\n sentence, severity, expected, actual);\n }\n\n var accuracy = total > 0 ? (double)(truePositives + trueNegatives) / total : 0;\n var precision = truePositives + falsePositives > 0 ? (double)truePositives / (truePositives + falsePositives) : 0;\n var recall = truePositives + falseNegatives > 0 ? (double)truePositives / (truePositives + falseNegatives) : 0;\n\n var result = new BenchmarkResult {\n Total = total,\n TruePositives = truePositives,\n FalsePositives = falsePositives,\n TrueNegatives = trueNegatives,\n FalseNegatives = falseNegatives,\n Accuracy = accuracy,\n Precision = precision,\n Recall = recall\n };\n\n _logger.LogInformation(\"Benchmark results: {result} [Thresholds: FilterThreshold={FilterThreshold}, ModerateThreshold={ModerateThreshold}, SevereThreshold={SevereThreshold}]\",\n result, FilterThreshold, ModerateThreshold, SevereThreshold);\n\n return result;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Behaviour/Emotion/EmotionProcessor.cs", "using System.Text;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.LLM;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.Live2D.Behaviour.Emotion;\n\n/// \n/// Processor for extracting emotion tags from text before TTS synthesis\n/// \npublic class EmotionProcessor(IEmotionService emotionService, ILoggerFactory loggerFactory) : ITextFilter\n{\n private const string MetadataKey = \"EmotionMarkers\";\n\n private const string MarkerPrefix = \"__EM\";\n\n private const string MarkerSuffix = \"__\";\n\n private static readonly Regex EmotionTagRegex = new(@\"\\[EMOTION:(.*?)\\]\",\n RegexOptions.Compiled | RegexOptions.CultureInvariant);\n\n private readonly ILogger _logger = loggerFactory.CreateLogger();\n\n public int Priority => 100;\n\n public ValueTask ProcessAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n\n var markers = new List();\n var processedTextBuilder = new StringBuilder();\n var lastIndex = 0;\n var markerIndex = 0;\n\n var matches = EmotionTagRegex.Matches(text);\n if ( matches.Count == 0 )\n {\n _logger.LogTrace(\"No emotion tags found in the input text.\");\n\n return ValueTask.FromResult(new TextFilterResult { ProcessedText = text });\n }\n\n _logger.LogDebug(\"Found {Count} potential emotion tags.\", matches.Count);\n\n foreach ( Match match in matches )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n processedTextBuilder.Append(text, lastIndex, match.Index - lastIndex);\n var emotionValue = match.Groups[1].Value;\n if ( string.IsNullOrWhiteSpace(emotionValue) )\n {\n _logger.LogWarning(\"Found emotion tag with empty value at index {Index}. Skipping.\", match.Index);\n processedTextBuilder.Append(match.Value);\n lastIndex = match.Index + match.Length;\n\n continue;\n }\n\n // e.g., [__EM0__](//), [__EM1__](//) This causes the phonemizer to see it as a feature and ignore it\n var markerId = $\"{MarkerPrefix}{markerIndex++}{MarkerSuffix}\";\n var markerToken = $\"[{markerId}](//)\";\n processedTextBuilder.Append(markerToken);\n\n var markerInfo = new EmotionMarkerInfo { MarkerId = markerId, Emotion = emotionValue };\n markers.Add(markerInfo);\n\n _logger.LogTrace(\"Replaced tag '{Tag}' with marker '{Marker}' for emotion '{Emotion}'.\",\n match.Value, markerId, emotionValue);\n\n lastIndex = match.Index + match.Length;\n }\n\n processedTextBuilder.Append(text, lastIndex, text.Length - lastIndex);\n var processedText = processedTextBuilder.ToString();\n _logger.LogDebug(\"Processed text length: {Length}. Original length: {OriginalLength}.\",\n processedText.Length, text.Length);\n\n var metadata = new Dictionary();\n if ( markers.Count != 0 )\n {\n metadata[MetadataKey] = markers;\n }\n\n var result = new TextFilterResult { ProcessedText = processedText, Metadata = metadata };\n\n return ValueTask.FromResult(result);\n }\n\n public ValueTask PostProcessAsync(TextFilterResult textFilterResult, AudioSegment segment, CancellationToken cancellationToken = default)\n {\n if ( !segment.Tokens.Any() ||\n !textFilterResult.Metadata.TryGetValue(MetadataKey, out var markersObj) ||\n markersObj is not List markers || markers.Count == 0 )\n {\n _logger.LogTrace(\"No emotion markers found in metadata or segment/tokens are missing/empty for segment Id {SegmentId}. Skipping post-processing.\", segment?.Id);\n\n return ValueTask.CompletedTask;\n }\n\n _logger.LogDebug(\"Starting emotion post-processing for segment Id {SegmentId} with {MarkerCount} markers.\", segment.Id, markers.Count);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n var emotionTimings = new List();\n var processedMarkers = new HashSet();\n var allMarkersFound = false;\n\n var markerDict = markers.ToDictionary(m => m.MarkerId, m => m.Emotion);\n\n foreach ( var token in segment.Tokens )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n foreach ( var (markerId, emotion) in markerDict )\n {\n if ( processedMarkers.Contains(markerId) || !token.Text.Contains(markerId) )\n {\n continue;\n }\n\n // Usually okay, the only case wher StartTS is 0 is if it's the first token.\n var timestamp = token.StartTs ?? 0;\n\n emotionTimings.Add(new EmotionTiming { Timestamp = timestamp, Emotion = emotion });\n processedMarkers.Add(markerId);\n token.Text = string.Empty;\n\n _logger.LogDebug(\"Mapped emotion '{Emotion}' (from marker '{Marker}') to timestamp {Timestamp:F2}s based on token '{TokenText}'.\",\n emotion, markerId, timestamp, token.Text);\n\n if ( processedMarkers.Count == markers.Count )\n {\n _logger.LogDebug(\"All {Count} markers have been processed. Exiting token scan early.\", markers.Count);\n allMarkersFound = true;\n\n break;\n }\n }\n\n if ( allMarkersFound )\n {\n break;\n }\n }\n\n if ( emotionTimings.Count != 0 )\n {\n _logger.LogInformation(\"Registering {Count} timed emotions for segment Id {SegmentId}.\", emotionTimings.Count, segment.Id);\n try\n {\n emotionService.RegisterEmotions(segment.Id, emotionTimings);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error registering emotions for segment Id {SegmentId}.\", segment.Id);\n }\n }\n else\n {\n _logger.LogWarning(\"Could not map any emotion markers to timestamps for segment Id {SegmentId}. This might happen if markers were removed by later filters or TTS engine issues.\", segment.Id);\n }\n\n if ( processedMarkers.Count >= markers.Count )\n {\n return ValueTask.CompletedTask;\n }\n\n {\n var unprocessed = markers.Where(m => !processedMarkers.Contains(m.MarkerId)).Select(m => m.MarkerId);\n _logger.LogWarning(\"The following emotion markers were found in ProcessAsync but not located in the final tokens for segment Id {SegmentId}: {UnprocessedMarkers}\",\n segment.Id, string.Join(\", \", unprocessed));\n }\n\n return ValueTask.CompletedTask;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/ChannelAggregationStrategy.cs", "namespace PersonaEngine.Lib.Audio;\n\n/// \n/// A strategy for aggregating multiple audio channels into a single channel.\n/// \npublic interface IChannelAggregationStrategy\n{\n /// \n /// Aggregates the specified frame of audio samples.\n /// \n void Aggregate(ReadOnlyMemory frame, Memory destination);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n\n void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample);\n}\n\n/// \n/// Provides predefined strategies for aggregating float audio channels.\n/// \npublic static class DefaultChannelAggregationStrategies\n{\n /// \n /// Gets the average aggregation strategy for float audio channels.\n /// \n public static IChannelAggregationStrategy Average { get; } = new AverageChannelAggregationStrategy();\n\n /// \n /// Gets the max aggregation strategy for float audio channels.\n /// \n public static IChannelAggregationStrategy Sum { get; } = new SumChannelAggregationStrategy();\n\n /// \n /// Gets the channel selection strategy for float audio channels.\n /// \n /// The index of the channel to use for aggregation.\n /// The channel selection strategy.\n public static IChannelAggregationStrategy SelectChannel(int channelIndex) { return new SelectChannelAggregationStrategy(channelIndex); }\n}\n\n/// \n/// Aggregates audio channels by computing the average of the samples.\n/// \ninternal class AverageChannelAggregationStrategy : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetAverageFloat(frame); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetAverageFloat(frame, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetAverageFloat(frame, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetAverageFloat(frame);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetAverageFloat(ReadOnlyMemory frame)\n {\n var span = frame.Span;\n var sum = 0.0f;\n for ( var i = 0; i < span.Length; i++ )\n {\n sum += span[i];\n }\n\n return sum / span.Length;\n }\n\n private static float GetAverageFloat(ReadOnlyMemory frame, ushort bitsPerSample)\n {\n var index = 0;\n var sum = 0f;\n var span = frame.Span;\n while ( index < frame.Length )\n {\n sum += SampleSerializer.ReadSample(span, ref index, bitsPerSample);\n }\n\n // We multiply by 8 first to avoid integer division\n return sum / (frame.Length * 8 / bitsPerSample);\n }\n}\n\n/// \n/// Aggregates float audio channels by selecting the maximum sample.\n/// \ninternal class SumChannelAggregationStrategy : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetSumFloat(frame); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetSumFloat(frame, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetSumFloat(frame, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetSumFloat(frame);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetSumFloat(ReadOnlyMemory frame)\n {\n var span = frame.Span;\n var sum = 0.0f;\n for ( var i = 0; i < span.Length; i++ )\n {\n sum += span[i];\n }\n\n // Ensure the float value is within the range (-1, 1)\n if ( sum > 1 )\n {\n sum = 1;\n }\n else if ( sum < -1 )\n {\n sum = -1;\n }\n\n return sum;\n }\n\n private static float GetSumFloat(ReadOnlyMemory frame, ushort bitsPerSample)\n {\n var index = 0;\n var sum = 0f;\n var span = frame.Span;\n while ( index < frame.Length )\n {\n sum += SampleSerializer.ReadSample(span, ref index, bitsPerSample);\n }\n\n // Ensure the float value is within the range (-1, 1)\n if ( sum > 1 )\n {\n sum = 1;\n }\n else if ( sum < -1 )\n {\n sum = -1;\n }\n\n return sum;\n }\n}\n\n/// \n/// Aggregates float audio channels by selecting a specific channel.\n/// \n/// The index of the channel to use for aggregation.\ninternal class SelectChannelAggregationStrategy(int channelIndex) : IChannelAggregationStrategy\n{\n public void Aggregate(ReadOnlyMemory frame, Memory destination) { destination.Span[0] = GetChannelFloat(frame, channelIndex); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetChannelFloat(frame, channelIndex, bitsPerSample);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample) { destination.Span[0] = GetChannelFloat(frame, channelIndex, bitsPerSample); }\n\n public void Aggregate(ReadOnlyMemory frame, Memory destination, ushort bitsPerSample)\n {\n var sampleValue = GetChannelFloat(frame, channelIndex);\n SampleSerializer.WriteSample(destination.Span, 0, sampleValue, bitsPerSample);\n }\n\n private static float GetChannelFloat(ReadOnlyMemory frame, int channelIndex) { return frame.Span[channelIndex]; }\n\n private static float GetChannelFloat(ReadOnlyMemory frame, int channelIndex, ushort bitsPerSample)\n {\n var byteIndex = channelIndex * bitsPerSample / 8;\n\n return SampleSerializer.ReadSample(frame.Span, ref byteIndex, bitsPerSample);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/TtsConfigEditor.cs", "using System.Diagnostics;\nusing System.Numerics;\nusing System.Threading.Channels;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets.Dialogs;\n\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.RVC;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Editor for TTS section configuration\n/// \npublic class TtsConfigEditor : ConfigSectionEditorBase\n{\n private readonly IAudioOutputAdapter _audioPlayer;\n\n private readonly IRVCVoiceProvider _rvcProvider;\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly ITtsEngine _ttsEngine;\n\n private readonly IKokoroVoiceProvider _voiceProvider;\n\n private List _availableRVCs = new();\n\n private List _availableVoices = new();\n\n private TtsConfiguration _currentConfig;\n\n private RVCFilterOptions _currentRvcFilterOptions;\n\n private KokoroVoiceOptions _currentVoiceOptions;\n\n private string _defaultRVC;\n\n private string _defaultVoice;\n\n private string _espeakPath;\n\n private bool _isPlaying = false;\n\n private bool _loadingRvcs = false;\n\n private bool _loadingVoices = false;\n\n private int _maxPhonemeLength;\n\n private string _modelDir;\n\n private ActiveOperation? _playbackOperation = null;\n\n private bool _rvcEnabled;\n\n private int _rvcF0UpKey;\n\n private int _rvcHopSize;\n\n private int _sampleRate;\n\n private float _speechRate;\n\n private string _testText = \"This is a test of the text-to-speech system.\";\n\n private bool _trimSilence;\n\n private bool _useBritishEnglish;\n\n public TtsConfigEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n ITtsEngine ttsEngine,\n IOutputAdapter audioPlayer,\n IKokoroVoiceProvider voiceProvider,\n IUiThemeManager themeManager, IRVCVoiceProvider rvcProvider)\n : base(configManager, stateManager)\n {\n _ttsEngine = ttsEngine;\n _audioPlayer = (IAudioOutputAdapter)audioPlayer;\n _voiceProvider = voiceProvider;\n _themeManager = themeManager;\n _rvcProvider = rvcProvider;\n\n LoadConfiguration();\n\n // _audioPlayerHost.OnPlaybackStarted += OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted += OnPlaybackCompleted;\n }\n\n public override string SectionKey => \"TTS\";\n\n public override string DisplayName => \"TTS Configuration\";\n\n public override void Initialize()\n {\n // Load available voices\n LoadAvailableVoicesAsync();\n LoadAvailableRVCAsync();\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Main layout with tabs for different sections\n if ( ImGui.BeginTabBar(\"TtsConfigTabs\") )\n {\n // Basic settings tab\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettings();\n\n ImGui.EndTabItem();\n }\n\n // Advanced settings tab\n if ( ImGui.BeginTabItem(\"Advanced Settings\") )\n {\n RenderAdvancedSettings();\n ImGui.EndTabItem();\n }\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n // Reset button at bottom\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all TTS settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n public override void Update(float deltaTime)\n {\n // Simplified update just for playback operation\n if ( _playbackOperation != null && _isPlaying )\n {\n _playbackOperation.Progress += deltaTime * 0.1f;\n if ( _playbackOperation.Progress > 0.99f )\n {\n _playbackOperation.Progress = 0.99f;\n }\n }\n }\n\n public override void OnConfigurationChanged(ConfigurationChangedEventArgs args)\n {\n base.OnConfigurationChanged(args);\n\n if ( args.Type == ConfigurationChangedEventArgs.ChangeType.Reloaded )\n {\n LoadConfiguration();\n }\n }\n\n public override void Dispose()\n {\n // Unsubscribe from audio player events\n // _audioPlayerHost.OnPlaybackStarted -= OnPlaybackStarted;\n // _audioPlayerHost.OnPlaybackCompleted -= OnPlaybackCompleted;\n\n // Cancel any active playback\n StopPlayback();\n\n base.Dispose();\n }\n\n #region Configuration Management\n\n private void LoadConfiguration()\n {\n _currentConfig = ConfigManager.GetConfiguration(\"TTS\");\n _currentVoiceOptions = _currentConfig.Voice;\n _currentRvcFilterOptions = _currentConfig.Rvc;\n\n // Update local fields from configuration\n _modelDir = _currentConfig.ModelDirectory;\n _espeakPath = _currentConfig.EspeakPath;\n _speechRate = _currentVoiceOptions.DefaultSpeed;\n _sampleRate = _currentVoiceOptions.SampleRate;\n _trimSilence = _currentVoiceOptions.TrimSilence;\n _useBritishEnglish = _currentVoiceOptions.UseBritishEnglish;\n _defaultVoice = _currentVoiceOptions.DefaultVoice;\n _maxPhonemeLength = _currentVoiceOptions.MaxPhonemeLength;\n\n // RVC\n _defaultRVC = _currentRvcFilterOptions.DefaultVoice;\n _rvcEnabled = _currentRvcFilterOptions.Enabled;\n _rvcHopSize = _currentRvcFilterOptions.HopSize;\n _rvcF0UpKey = _currentRvcFilterOptions.F0UpKey;\n }\n\n private async void LoadAvailableVoicesAsync()\n {\n try\n {\n _loadingVoices = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-voices\", \"Loading Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _voiceProvider.GetAvailableVoicesAsync();\n _availableVoices = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableVoices = [];\n }\n finally\n {\n _loadingVoices = false;\n }\n }\n\n private async void LoadAvailableRVCAsync()\n {\n try\n {\n _loadingRvcs = true;\n\n // Register an active operation\n var operation = new ActiveOperation(\"load-rvc\", \"Loading RVC Voices\");\n StateManager.RegisterActiveOperation(operation);\n\n // Load voices asynchronously\n var voices = await _rvcProvider.GetAvailableVoicesAsync();\n _availableRVCs = voices.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading voices: {ex.Message}\");\n _availableRVCs = [];\n }\n finally\n {\n _loadingRvcs = false;\n }\n }\n\n private void UpdateConfiguration()\n {\n var updatedVoiceOptions = new KokoroVoiceOptions {\n DefaultVoice = _defaultVoice,\n DefaultSpeed = _speechRate,\n SampleRate = _sampleRate,\n TrimSilence = _trimSilence,\n UseBritishEnglish = _useBritishEnglish,\n MaxPhonemeLength = _maxPhonemeLength\n };\n\n var updatedRVCOptions = new RVCFilterOptions { DefaultVoice = _defaultRVC, Enabled = _rvcEnabled, HopSize = _rvcHopSize, F0UpKey = _rvcF0UpKey };\n\n var updatedConfig = new TtsConfiguration { ModelDirectory = _modelDir, EspeakPath = _espeakPath, Voice = updatedVoiceOptions, Rvc = updatedRVCOptions };\n\n _currentRvcFilterOptions = updatedRVCOptions;\n _currentVoiceOptions = updatedVoiceOptions;\n _currentConfig = updatedConfig;\n ConfigManager.UpdateConfiguration(updatedConfig, SectionKey);\n\n MarkAsChanged();\n }\n\n private void SaveConfiguration()\n {\n ConfigManager.SaveConfiguration();\n MarkAsSaved();\n }\n\n private void ResetToDefaults()\n {\n // Create default configuration\n var defaultVoiceOptions = new KokoroVoiceOptions();\n var defaultConfig = new TtsConfiguration();\n\n // Update local state\n _currentVoiceOptions = defaultVoiceOptions;\n _currentConfig = defaultConfig;\n\n // Update UI fields\n _modelDir = defaultConfig.ModelDirectory;\n _espeakPath = defaultConfig.EspeakPath;\n _speechRate = defaultVoiceOptions.DefaultSpeed;\n _sampleRate = defaultVoiceOptions.SampleRate;\n _trimSilence = defaultVoiceOptions.TrimSilence;\n _useBritishEnglish = defaultVoiceOptions.UseBritishEnglish;\n _defaultVoice = defaultVoiceOptions.DefaultVoice;\n _maxPhonemeLength = defaultVoiceOptions.MaxPhonemeLength;\n\n // Update configuration\n ConfigManager.UpdateConfiguration(defaultConfig, \"TTS\");\n MarkAsChanged();\n }\n\n #endregion\n\n #region Playback Controls\n\n private async void StartPlayback()\n {\n if ( _isPlaying || string.IsNullOrWhiteSpace(_testText) )\n {\n return;\n }\n\n try\n {\n // Create a new playback operation\n _playbackOperation = new ActiveOperation(\"tts-playback\", \"Playing TTS\");\n StateManager.RegisterActiveOperation(_playbackOperation);\n\n _isPlaying = true;\n\n var options = _currentVoiceOptions;\n\n var llmInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var ttsOutput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioInput = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });\n var audioEvents = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); // Tts Started/Tts Ended - Audio Started/Audio Ended\n\n await llmInput.Writer.WriteAsync(new LlmChunkEvent(Guid.Empty, Guid.Empty, DateTimeOffset.UtcNow, _testText), _playbackOperation.CancellationSource.Token);\n llmInput.Writer.Complete();\n\n _ = Task.Run(async () =>\n {\n await foreach(var ttsOut in ttsOutput.Reader.ReadAllAsync(_playbackOperation.CancellationSource.Token))\n {\n if ( ttsOut is TtsChunkEvent ttsChunk )\n {\n await audioInput.Writer.WriteAsync(ttsChunk, _playbackOperation.CancellationSource.Token);\n }\n }\n });\n\n _ = _ttsEngine.SynthesizeStreamingAsync(\n llmInput,\n ttsOutput,\n Guid.Empty,\n Guid.Empty,\n options,\n _playbackOperation.CancellationSource.Token\n );\n\n await _audioPlayer.SendAsync(audioInput, audioEvents, Guid.Empty, _playbackOperation.CancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"TTS playback cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during TTS playback: {ex.Message}\");\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n }\n\n private void StopPlayback()\n {\n if ( _playbackOperation != null )\n {\n _playbackOperation.CancellationSource.Cancel();\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n\n _isPlaying = false;\n }\n\n private void OnPlaybackStarted(object sender, EventArgs args)\n {\n _isPlaying = true;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 0.0f;\n }\n }\n\n private void OnPlaybackCompleted(object sender, EventArgs args)\n {\n _isPlaying = false;\n\n if ( _playbackOperation != null )\n {\n _playbackOperation.Progress = 1.0f;\n StateManager.ClearActiveOperation(_playbackOperation.Id);\n _playbackOperation = null;\n }\n }\n\n #endregion\n\n #region UI Rendering Methods\n\n private void RenderTestingSection()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Playground\");\n ImGui.Spacing();\n\n // Text input frame with light background\n ImGui.Text(\"Test Text:\");\n ImGui.SetNextItemWidth(availWidth);\n ImGui.InputTextMultiline(\"##TestText\", ref _testText, 1000, new Vector2(0, 80));\n\n ImGui.Spacing();\n ImGui.Spacing();\n\n // Controls section with better layout\n ImGui.BeginGroup();\n {\n // Left side: Example selector\n var controlWidth = Math.Min(180, availWidth * 0.4f);\n ImGui.SetNextItemWidth(controlWidth);\n\n if ( ImGui.BeginCombo(\"##exampleLbl\", \"Select Example\") )\n {\n string[] examples = { \"Hello, world!\", \"The quick brown fox jumps over the lazy dog.\", \"Welcome to the text-to-speech system.\", \"How are you doing today?\", \"Today's date is March 3rd, 2025.\" };\n\n foreach ( var example in examples )\n {\n var isSelected = _testText == example;\n if ( ImGui.Selectable(example, ref isSelected) )\n {\n _testText = example;\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.SameLine(0, 15);\n\n var clearDisabled = string.IsNullOrEmpty(_testText);\n if ( clearDisabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( ImGui.Button(\"Clear\", new Vector2(80, 0)) && !string.IsNullOrEmpty(_testText) )\n {\n _testText = \"\";\n }\n\n if ( clearDisabled )\n {\n ImGui.EndDisabled();\n }\n }\n\n ImGui.EndGroup();\n\n ImGui.SameLine(0, 10);\n\n // Playback controls in a styled frame\n {\n // Play/Stop button with color styling\n if ( _isPlaying )\n {\n if ( UiStyler.AnimatedButton(\"Stop\", new Vector2(80, 0), _isPlaying) )\n {\n StopPlayback();\n }\n\n ImGui.SameLine(0, 15);\n ImGui.ProgressBar(_playbackOperation?.Progress ?? 0, new Vector2(-1, 0), \"Playing\");\n }\n else\n {\n var disabled = string.IsNullOrWhiteSpace(_testText);\n if ( disabled )\n {\n ImGui.BeginDisabled();\n }\n\n if ( UiStyler.AnimatedButton(\"Play\", new Vector2(80, 0), _isPlaying) )\n {\n StartPlayback();\n }\n\n if ( disabled )\n {\n ImGui.EndDisabled();\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Enter some text to play\");\n }\n }\n }\n }\n }\n\n private void RenderBasicSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // === Voice Selection Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Voice Settings\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingVoices )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading voices...\";\n ImGui.InputText(\"##VoiceLoading\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n if ( ImGui.BeginCombo(\"##VoiceSelector\", string.IsNullOrEmpty(_defaultVoice) ? \"\" : _defaultRVC) )\n {\n if ( _availableRVCs.Count == 0 )\n {\n ImGui.TextColored(new Vector4(0.7f, 0.7f, 0.7f, 1.0f), \"No voices available\");\n }\n else\n {\n foreach ( var voice in _availableRVCs )\n {\n var isSelected = voice == _defaultRVC;\n if ( ImGui.Selectable(voice, isSelected) )\n {\n _defaultRVC = voice;\n UpdateConfiguration();\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n }\n\n ImGui.EndCombo();\n }\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Refresh##RefreshRVC\", new Vector2(-1, 0)) )\n {\n LoadAvailableRVCAsync();\n }\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Refresh available voices list\");\n }\n\n if ( ImGui.BeginTable(\"RVCProps\", 4, ImGuiTableFlags.SizingFixedFit) )\n {\n ImGui.TableSetupColumn(\"1\", 100f);\n ImGui.TableSetupColumn(\"2\", 200f);\n ImGui.TableSetupColumn(\"3\", 100f);\n ImGui.TableSetupColumn(\"4\", 200f);\n\n // Hop Size\n ImGui.TableNextRow();\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Hop Size\");\n ImGui.TableNextColumn();\n var fontSizeChanged = ImGui.InputInt(\"##HopSize\", ref _rvcHopSize, 8);\n if ( fontSizeChanged )\n {\n _rvcHopSize = Math.Clamp(_rvcHopSize, 8, 256);\n rvcConfigChanged = true;\n }\n\n // F0 Key\n ImGui.TableNextColumn();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Pitch\");\n ImGui.TableNextColumn();\n var pitchChanged = ImGui.InputInt(\"##Pitch\", ref _rvcF0UpKey, 1);\n if ( pitchChanged )\n {\n _rvcF0UpKey = Math.Clamp(_rvcF0UpKey, -20, 20);\n rvcConfigChanged = true;\n }\n\n ImGui.EndTable();\n }\n\n if ( !_rvcEnabled )\n {\n ImGui.EndDisabled();\n }\n\n if ( rvcConfigChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n private void RenderAdvancedSettings()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n // Section header\n ImGui.Spacing();\n ImGui.SeparatorText(\"Advanced TTS Settings\");\n ImGui.Spacing();\n\n var sampleRateChanged = false;\n var phonemeChanged = false;\n\n // ImGui.BeginDisabled();\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Sample Rate:\");\n ImGui.SameLine(200);\n\n string[] sampleRates = [\"16000 Hz (Low quality)\", \"24000 Hz (Standard quality)\", \"32000 Hz (Good quality)\", \"44100 Hz (High quality)\", \"48000 Hz (Studio quality)\"];\n int[] rateValues = [16000, 24000, 32000, 44100, 48000];\n\n var currentIdx = Array.IndexOf(rateValues, _sampleRate);\n if ( currentIdx < 0 )\n {\n currentIdx = 1; // Default to 24000 Hz\n }\n\n ImGui.SetNextItemWidth(availWidth - 200);\n\n if ( ImGui.BeginCombo(\"##SampleRate\", sampleRates[currentIdx]) )\n {\n for ( var i = 0; i < sampleRates.Length; i++ )\n {\n var isSelected = i == currentIdx;\n if ( ImGui.Selectable(sampleRates[i], isSelected) )\n {\n _sampleRate = rateValues[i];\n sampleRateChanged = true;\n }\n\n // Show additional info on hover\n if ( ImGui.IsItemHovered() )\n {\n var tooltipText = i switch {\n 0 => \"Low quality, minimal resource usage\",\n 1 => \"Standard quality, recommended for most uses\",\n 2 => \"Good quality, balanced resource usage\",\n 3 => \"High quality, CD audio standard\",\n 4 => \"Studio quality, higher resource usage\",\n _ => \"\"\n };\n\n ImGui.SetTooltip(tooltipText);\n }\n\n if ( isSelected )\n {\n ImGui.SetItemDefaultFocus();\n }\n }\n\n ImGui.EndCombo();\n }\n\n ImGui.EndDisabled();\n }\n\n ImGui.EndGroup();\n\n ImGui.BeginGroup();\n {\n ImGui.BeginDisabled();\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Max Phoneme Length:\");\n ImGui.SameLine(200);\n\n ImGui.SetNextItemWidth(120);\n phonemeChanged = ImGui.InputInt(\"##MaxPhonemeLength\", ref _maxPhonemeLength);\n ImGui.EndDisabled();\n\n // Clamp value to valid range\n if ( phonemeChanged )\n {\n var oldValue = _maxPhonemeLength;\n _maxPhonemeLength = Math.Clamp(_maxPhonemeLength, 1, 2048);\n\n if ( oldValue != _maxPhonemeLength )\n {\n ImGui.TextColored(new Vector4(1.0f, 0.7f, 0.3f, 1.0f),\n \"Value clamped to valid range (1-2048)\");\n }\n }\n\n // Helper text\n ImGui.Spacing();\n ImGui.TextWrapped(\"This is already setup correctly to work with Kokoro. Shouldn't have to change!\");\n\n // === Paths & Resources Section ===\n ImGui.Spacing();\n ImGui.SeparatorText(\"Paths & Resources\");\n ImGui.Spacing();\n\n ImGui.BeginGroup();\n {\n // Model directory\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Model Directory:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var modelDirChanged = ImGui.InputText(\"##ModelDir\", ref _modelDir, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##ModelDir\", new Vector2(-1, 0)) )\n {\n var fileDialog = new OpenFolderDialog(_modelDir);\n fileDialog.Show();\n if ( fileDialog.SelectedFolder != null )\n {\n _modelDir = fileDialog.SelectedFolder;\n modelDirChanged = true;\n }\n }\n\n // Espeak path\n ImGui.AlignTextToFramePadding();\n ImGui.Text(\"Espeak Path:\");\n ImGui.SameLine(150);\n\n ImGui.SetNextItemWidth(availWidth - 240);\n var espeakPathChanged = ImGui.InputText(\"##EspeakPath\", ref _espeakPath, 512, ImGuiInputTextFlags.ElideLeft);\n\n ImGui.SameLine(0, 10);\n if ( ImGui.Button(\"Browse##EspeakPath\", new Vector2(-1, 0)) )\n {\n // In a real app, this would open a file browser dialog\n Console.WriteLine(\"Open file browser for Espeak Path\");\n }\n\n // Apply changes if needed\n if ( modelDirChanged || espeakPathChanged )\n {\n UpdateConfiguration();\n }\n }\n\n ImGui.EndGroup();\n }\n\n ImGui.EndGroup();\n\n if ( sampleRateChanged || phonemeChanged )\n {\n UpdateConfiguration();\n }\n }\n\n #endregion\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/CubismClippingContext.cs", "using PersonaEngine.Lib.Live2D.Framework.Math;\nusing PersonaEngine.Lib.Live2D.Framework.Type;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Rendering;\n\npublic unsafe class CubismClippingContext(CubismClippingManager manager, int* clippingDrawableIndices, int clipCount)\n{\n /// \n /// このクリッピングで、クリッピングされる全ての描画オブジェクトの囲み矩形(毎回更新)\n /// \n public RectF AllClippedDrawRect = new();\n\n /// \n /// このマスクが割り当てられるレンダーテクスチャ(フレームバッファ)やカラーバッファのインデックス\n /// \n public int BufferIndex;\n\n /// \n /// このマスクにクリップされる描画オブジェクトのリスト\n /// \n public List ClippedDrawableIndexList = [];\n\n /// \n /// クリッピングマスクの数\n /// \n public int ClippingIdCount = clipCount;\n\n /// \n /// クリッピングマスクのIDリスト\n /// \n public int* ClippingIdList = clippingDrawableIndices;\n\n /// \n /// 現在の描画状態でマスクの準備が必要ならtrue\n /// \n public bool IsUsing;\n\n /// \n /// マスク用チャンネルのどの領域にマスクを入れるか(View座標-1..1, UVは0..1に直す)\n /// \n public RectF LayoutBounds = new();\n\n /// \n /// RGBAのいずれのチャンネルにこのクリップを配置するか(0:R , 1:G , 2:B , 3:A)\n /// \n public int LayoutChannelIndex = 0;\n\n /// \n /// 描画オブジェクトの位置計算結果を保持する行列\n /// \n public CubismMatrix44 MatrixForDraw = new();\n\n /// \n /// マスクの位置計算結果を保持する行列\n /// \n public CubismMatrix44 MatrixForMask = new();\n\n public CubismClippingManager Manager { get; } = manager;\n\n /// \n /// このマスクにクリップされる描画オブジェクトを追加する\n /// \n /// クリッピング対象に追加する描画オブジェクトのインデックス\n public void AddClippedDrawable(int drawableIndex) { ClippedDrawableIndexList.Add(drawableIndex); }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Lexicon.cs", "using System.Collections.Frozen;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic partial class Lexicon : ILexicon, IDisposable\n{\n private static readonly Regex _suffixRegex = SuffixRegex();\n\n private static readonly Regex _doubleConsonantIngRegex = DoubleConsonantIngRegex();\n\n private static readonly Regex _vsRegex = VersusRegex();\n\n private readonly (double Min, double Max) _capStresses = (0.5, 2.0);\n\n private readonly Lock _dictionaryLock = new();\n\n private readonly LruCache _stemCache;\n\n private readonly IOptionsMonitor _ttsConfig;\n\n private readonly IOptionsMonitor _voiceOptions;\n\n private readonly IDisposable? _voiceOptionsChangeToken;\n\n private readonly LruCache _wordCache;\n\n private volatile bool _british;\n\n private volatile IReadOnlyDictionary? _golds;\n\n private volatile IReadOnlyDictionary? _silvers;\n\n private volatile HashSet _vocab;\n\n public Lexicon(\n IOptionsMonitor ttsConfig,\n IOptionsMonitor voiceOptions)\n {\n _ttsConfig = ttsConfig;\n _voiceOptions = voiceOptions;\n\n // Initialize caches - size based on typical working set\n _wordCache = new LruCache(2048, StringComparer.Ordinal);\n _stemCache = new LruCache(512, StringComparer.Ordinal);\n\n // Initial load of dictionaries\n LoadDictionaries();\n\n // Register for configuration changes\n _voiceOptionsChangeToken = _voiceOptions.OnChange(options =>\n {\n var currentBritish = options.UseBritishEnglish;\n if ( _british != currentBritish )\n {\n LoadDictionaries();\n }\n });\n }\n\n public void Dispose() { _voiceOptionsChangeToken?.Dispose(); }\n\n public (string? Phonemes, int? Rating) ProcessToken(Token token, TokenContext ctx)\n {\n // Ensure dictionaries are loaded\n if ( _golds == null || _silvers == null )\n {\n LoadDictionaries();\n }\n\n // Normalize text: replace special quotes with straight quotes and normalize Unicode\n var word = (token.Text ?? token.Alias ?? \"\").Replace('\\u2018', '\\'').Replace('\\u2019', '\\'');\n word = word.Normalize(NormalizationForm.FormKC);\n\n // Calculate stress based on capitalization\n var stress = token.Stress;\n if ( stress == null && word != word.ToLower() )\n {\n stress = word == word.ToUpper() ? _capStresses.Max : _capStresses.Min;\n }\n\n // Call GetWord directly - it already handles all the necessary phoneme lookups, \n // stemming, and special cases\n return GetWord(\n word,\n token.Tag,\n stress,\n ctx,\n token.IsHead,\n token.Currency,\n token.NumFlags);\n }\n\n private void LoadDictionaries()\n {\n lock (_dictionaryLock)\n {\n var voiceOptions = _voiceOptions.CurrentValue;\n var ttsConfig = _ttsConfig.CurrentValue;\n var british = voiceOptions.UseBritishEnglish;\n\n // Double-check after acquiring lock to avoid unnecessary reloads\n if ( _golds != null && _british == british )\n {\n return;\n }\n\n // Update settings\n _british = british;\n _vocab = british ? PhonemizerConstants.GbVocab : PhonemizerConstants.UsVocab;\n\n // Construct paths\n var lexiconPrefix = british ? \"gb\" : \"us\";\n var primaryPath = Path.Combine(ttsConfig.ModelDirectory, $\"{lexiconPrefix}_gold.json\");\n var secondaryPath = Path.Combine(ttsConfig.ModelDirectory, $\"{lexiconPrefix}_silver.json\");\n\n // Use JsonSerializer with custom options\n var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, Converters = { new PhonemeEntryConverter() } };\n\n // Load dictionaries\n _golds = LoadAndGrowDictionary(primaryPath, options);\n _silvers = LoadAndGrowDictionary(secondaryPath, options);\n\n // Clear caches when dictionaries change\n _wordCache.Clear();\n _stemCache.Clear();\n }\n }\n\n private IReadOnlyDictionary LoadAndGrowDictionary(string path, JsonSerializerOptions options)\n {\n using var fileStream = File.OpenRead(path);\n\n // Deserialize with custom converter\n var rawDict = JsonSerializer.Deserialize>(fileStream);\n if ( rawDict == null )\n {\n throw new InvalidOperationException($\"Failed to deserialize lexicon from {path}\");\n }\n\n // Convert to strongly typed entries\n var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);\n foreach ( var (key, element) in rawDict )\n {\n if ( key.Length >= 2 )\n {\n dict[key] = PhonemeEntry.FromJsonElement(element);\n }\n }\n\n // Grow the dictionary with additional forms\n var extended = new Dictionary(StringComparer.OrdinalIgnoreCase);\n foreach ( var (key, value) in dict )\n {\n if ( key.Length < 2 )\n {\n continue;\n }\n\n if ( key == key.ToLower() )\n {\n var capitalized = LexiconUtils.Capitalize(key);\n if ( key != capitalized && !dict.ContainsKey(capitalized) )\n {\n extended[capitalized] = value;\n }\n }\n else if ( key == LexiconUtils.Capitalize(key.ToLower()) )\n {\n var lower = key.ToLower();\n if ( !dict.ContainsKey(lower) )\n {\n extended[lower] = value;\n }\n }\n }\n\n // Combine original and extended entries\n foreach ( var (key, value) in extended )\n {\n dict[key] = value;\n }\n\n // Return as frozen dictionary for performance\n return dict.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string? Phonemes, int? Rating) GetWord(\n string word,\n string tag,\n double? stress,\n TokenContext ctx,\n bool isHead,\n string? currency,\n string numFlags)\n {\n // Cache lookup - create a composite key for context-dependent lookups\n var cacheKey = $\"{word}|{tag}|{stress}|{ctx.FutureVowel}|{ctx.FutureTo}|{currency}|{numFlags}\";\n if ( _wordCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n // 1. Check special cases first\n var specialCase = GetSpecialCase(word, tag, stress, ctx);\n if ( specialCase.Phonemes != null )\n {\n var finalResult = (AppendCurrency(specialCase.Phonemes, currency), specialCase.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 2. Check if word is in dictionaries\n if ( IsKnown(word, tag) )\n {\n var result = Lookup(word, tag, stress, ctx);\n if ( result.Phonemes != null )\n {\n var finalResult = (ApplyStress(AppendCurrency(result.Phonemes, currency), stress), result.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 3. Check for apostrophe s at the end (possessives)\n if ( EndsWith(word, \"s'\") && IsKnown(word[..^2] + \"'s\", tag) )\n {\n var result = Lookup(word[..^2] + \"'s\", tag, stress, ctx);\n if ( result.Phonemes != null )\n {\n var finalResult = (AppendCurrency(result.Phonemes, currency), result.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 4. Check for words ending with apostrophe\n if ( EndsWith(word, \"'\") && IsKnown(word[..^1], tag) )\n {\n var result = Lookup(word[..^1], tag, stress, ctx);\n if ( result.Phonemes != null )\n {\n var finalResult = (AppendCurrency(result.Phonemes, currency), result.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 5. Try stemming for -s suffix\n var stemS = StemS(word, tag, stress, ctx);\n if ( stemS.Item1 != null )\n {\n var finalResult = (AppendCurrency(stemS.Item1, currency), stemS.Item2);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 6. Try stemming for -ed suffix\n var stemEd = StemEd(word, tag, stress, ctx);\n if ( stemEd.Item1 != null )\n {\n var finalResult = (AppendCurrency(stemEd.Item1, currency), stemEd.Item2);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 7. Try stemming for -ing suffix\n var stemIng = StemIng(word, tag, stress ?? 0.5, ctx);\n if ( stemIng.Item1 != null )\n {\n var finalResult = (AppendCurrency(stemIng.Item1, currency), stemIng.Item2);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n\n // 8. Handle numbers\n if ( IsNumber(word, isHead) )\n {\n var result = GetNumber(word, currency, isHead, numFlags);\n _wordCache[cacheKey] = result;\n\n return result;\n }\n\n // 9. Handle acronyms and capitalized words\n var isAllUpper = word.Length > 1 && word == word.ToUpper() && word.ToUpper() != word.ToLower();\n if ( isAllUpper )\n {\n var (nnpPhonemes, nnpRating) = GetNNP(word);\n if ( nnpPhonemes != null )\n {\n var finalResult = (AppendCurrency(nnpPhonemes, currency), nnpRating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // 10. Try lowercase version if word has some uppercase letters\n if ( word != word.ToLower() && (word == word.ToUpper() || word[1..] == word[1..].ToLower()) )\n {\n var lowercaseResult = Lookup(word.ToLower(), tag, stress, ctx);\n if ( lowercaseResult.Phonemes != null )\n {\n var finalResult = (AppendCurrency(lowercaseResult.Phonemes, currency), lowercaseResult.Rating);\n _wordCache[cacheKey] = finalResult;\n\n return finalResult;\n }\n }\n\n // No match found\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string? Phonemes, int? Rating) GetSpecialCase(string word, string tag, double? stress, TokenContext ctx)\n {\n // Handle special cases with optimized lookups\n var wordSpan = word.AsSpan();\n\n // Special symbols\n if ( tag == \"ADD\" && PhonemizerConstants.AddSymbols.TryGetValue(word, out var addSymbol) )\n {\n return Lookup(addSymbol, null, -0.5, ctx);\n }\n\n if ( PhonemizerConstants.Symbols.TryGetValue(word, out var symbol) )\n {\n return Lookup(symbol, null, null, ctx);\n }\n\n if ( wordSpan.Contains('.') && IsAllLettersOrDots(wordSpan) && MaxSubstringLength(wordSpan, '.') < 3 )\n {\n return GetNNP(word);\n }\n\n switch ( word )\n {\n case \"a\":\n case \"A\" when tag == \"DT\":\n return (\"ɐ\", 4);\n case \"I\" when tag == \"PRP\":\n return ($\"{PhonemizerConstants.SecondaryStress}I\", 4);\n case \"am\" or \"Am\" or \"AM\" when tag.StartsWith(\"NN\"):\n return GetNNP(word);\n case \"am\" or \"Am\" or \"AM\" when ctx.FutureVowel != null && word == \"am\" && stress is not > 0:\n return (\"ɐm\", 4);\n case \"am\" or \"Am\" or \"AM\" when _golds.TryGetValue(\"am\", out var amEntry) && amEntry is SimplePhonemeEntry simpleAm:\n return (simpleAm.Phoneme, 4);\n case \"am\" or \"Am\" or \"AM\":\n return (\"ɐm\", 4);\n case (\"an\" or \"An\" or \"AN\") and \"AN\" when tag.StartsWith(\"NN\"):\n return GetNNP(word);\n case \"an\" or \"An\" or \"AN\":\n return (\"ɐn\", 4);\n case \"by\" or \"By\" or \"BY\" when LexiconUtils.GetParentTag(tag) == \"ADV\":\n return (\"bˈI\", 4);\n case \"to\":\n case \"To\":\n case \"TO\" when tag is \"TO\" or \"IN\":\n switch ( ctx.FutureVowel )\n {\n case null:\n {\n if ( _golds.TryGetValue(\"to\", out var toEntry) && toEntry is SimplePhonemeEntry simpleTo )\n {\n return (simpleTo.Phoneme, 4);\n }\n\n break;\n }\n case false:\n return (\"tə\", 4);\n default:\n return (\"tʊ\", 4);\n }\n\n break;\n case \"the\":\n case \"The\":\n case \"THE\" when tag == \"DT\":\n return (ctx.FutureVowel == true ? \"ði\" : \"ðə\", 4);\n }\n\n if ( tag == \"IN\" && _vsRegex.IsMatch(word) )\n {\n return Lookup(\"versus\", null, null, ctx);\n }\n\n if ( word is \"used\" or \"Used\" or \"USED\" )\n {\n if ( tag is \"VBD\" or \"JJ\" && ctx.FutureTo )\n {\n if ( _golds.TryGetValue(\"used\", out var usedEntry) && usedEntry is ContextualPhonemeEntry contextualUsed )\n {\n return (contextualUsed.GetForm(\"VBD\", null), 4);\n }\n }\n\n if ( _golds.TryGetValue(\"used\", out var usedDefaultEntry) && usedDefaultEntry is ContextualPhonemeEntry contextualDefault )\n {\n return (contextualDefault.GetForm(\"DEFAULT\", null), 4);\n }\n }\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsAllLettersOrDots(ReadOnlySpan word)\n {\n foreach ( var c in word )\n {\n if ( c != '.' && !char.IsLetter(c) )\n {\n return false;\n }\n }\n\n return true;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private int MaxSubstringLength(ReadOnlySpan text, char separator)\n {\n var maxLength = 0;\n var start = 0;\n\n for ( var i = 0; i < text.Length; i++ )\n {\n if ( text[i] == separator )\n {\n maxLength = Math.Max(maxLength, i - start);\n start = i + 1;\n }\n }\n\n // Check the last segment\n maxLength = Math.Max(maxLength, text.Length - start);\n\n return maxLength;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string? Phonemes, int? Rating) Lookup(string word, string? tag, double? stress, TokenContext ctx)\n {\n var isNNP = false;\n if ( word == word.ToUpper() && !_golds.ContainsKey(word) )\n {\n word = word.ToLower();\n isNNP = tag == \"NNP\";\n }\n\n PhonemeEntry? entry = null;\n var rating = 4;\n\n if ( _golds.TryGetValue(word, out entry) )\n {\n // Found in gold dictionary\n }\n else if ( !isNNP && _silvers.TryGetValue(word, out entry) )\n {\n rating = 3;\n }\n\n if ( entry == null )\n {\n if ( isNNP )\n {\n return GetNNP(word);\n }\n\n return (null, null);\n }\n\n string? phonemes = null;\n\n switch ( entry )\n {\n case SimplePhonemeEntry simple:\n phonemes = simple.Phoneme;\n\n break;\n\n case ContextualPhonemeEntry contextual:\n phonemes = contextual.GetForm(tag, ctx);\n\n break;\n }\n\n if ( phonemes == null || (isNNP && !phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return GetNNP(word);\n }\n\n return (ApplyStress(phonemes, stress), rating);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsKnown(string word, string tag)\n {\n if ( _golds.ContainsKey(word) || PhonemizerConstants.Symbols.ContainsKey(word) || _silvers.ContainsKey(word) )\n {\n return true;\n }\n\n if ( !word.All(c => char.IsLetter(c)) || !word.All(IsValidCharacter) )\n {\n return false;\n }\n\n if ( word.Length == 1 )\n {\n return true;\n }\n\n if ( word == word.ToUpper() && _golds.ContainsKey(word.ToLower()) )\n {\n return true;\n }\n\n return word.Length > 1 && word[1..] == word[1..].ToUpper();\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsValidCharacter(char c)\n {\n // Check if character is valid for lexicon\n return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '\\'' || c == '-' || c == '_';\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string ApplyStress(string phonemes, double? stress)\n {\n if ( phonemes == null )\n {\n return \"\";\n }\n\n if ( stress == null )\n {\n return phonemes;\n }\n\n // Early return conditions\n if ( (stress == 0 || stress == 1) && !ContainsStressMarkers(phonemes) )\n {\n return phonemes;\n }\n\n // Remove all stress for very negative stress\n if ( stress < -1 )\n {\n return phonemes\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty);\n }\n\n // Lower stress level for -1 or 0\n if ( stress == -1 || (stress is 0 or -0.5 && phonemes.Contains(PhonemizerConstants.PrimaryStress)) )\n {\n return phonemes\n .Replace(PhonemizerConstants.SecondaryStress.ToString(), string.Empty)\n .Replace(PhonemizerConstants.PrimaryStress.ToString(), PhonemizerConstants.SecondaryStress.ToString());\n }\n\n // Add secondary stress for unstressed phonemes\n if ( stress is 0 or 0.5 or 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !ContainsVowel(phonemes) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.SecondaryStress + phonemes);\n }\n\n // Upgrade secondary stress to primary\n if ( stress >= 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n return phonemes.Replace(\n PhonemizerConstants.SecondaryStress.ToString(),\n PhonemizerConstants.PrimaryStress.ToString());\n }\n\n // Add primary stress for high stress values\n if ( stress > 1 &&\n !phonemes.Contains(PhonemizerConstants.PrimaryStress) &&\n !phonemes.Contains(PhonemizerConstants.SecondaryStress) )\n {\n if ( !ContainsVowel(phonemes) )\n {\n return phonemes;\n }\n\n return RestressPhonemes(PhonemizerConstants.PrimaryStress + phonemes);\n }\n\n return phonemes;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool ContainsStressMarkers(string phonemes)\n {\n return phonemes.Contains(PhonemizerConstants.PrimaryStress) ||\n phonemes.Contains(PhonemizerConstants.SecondaryStress);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool ContainsVowel(string phonemes) { return phonemes.Any(c => PhonemizerConstants.Vowels.Contains(c)); }\n\n private string RestressPhonemes(string phonemes)\n {\n // Optimization: Avoid allocations if there are no stress markers\n if ( !ContainsStressMarkers(phonemes) )\n {\n return phonemes;\n }\n\n var chars = phonemes.ToCharArray();\n var charPositions = new List<(int Position, char Char)>(chars.Length);\n\n for ( var i = 0; i < chars.Length; i++ )\n {\n charPositions.Add((i, chars[i]));\n }\n\n var stressPositions = new Dictionary();\n for ( var i = 0; i < charPositions.Count; i++ )\n {\n if ( PhonemizerConstants.Stresses.Contains(charPositions[i].Char) )\n {\n // Find the next vowel\n var vowelPos = -1;\n for ( var j = i + 1; j < charPositions.Count; j++ )\n {\n if ( PhonemizerConstants.Vowels.Contains(charPositions[j].Char) )\n {\n vowelPos = j;\n\n break;\n }\n }\n\n if ( vowelPos != -1 )\n {\n stressPositions[charPositions[i].Position] = charPositions[vowelPos].Position;\n charPositions[i] = ((int)(vowelPos - 0.5), charPositions[i].Char);\n }\n }\n }\n\n charPositions.Sort((a, b) => a.Position.CompareTo(b.Position));\n\n return new string(charPositions.Select(cp => cp.Char).ToArray());\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool EndsWith(string word, string suffix) { return word.Length > suffix.Length && word.EndsWith(suffix, StringComparison.Ordinal); }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) GetNNP(string word)\n {\n // Early exit for extremely short or long words\n if ( word.Length < 1 || word.Length > 20 )\n {\n return (null, null);\n }\n\n // Cache lookups for acronyms\n var cacheKey = $\"NNP_{word}\";\n if ( _wordCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n // Collect phonemes for each letter\n var phoneticLetters = new List();\n\n foreach ( var c in word )\n {\n if ( !char.IsLetter(c) )\n {\n continue;\n }\n\n if ( _golds.TryGetValue(c.ToString().ToUpper(), out var letterEntry) )\n {\n if ( letterEntry is SimplePhonemeEntry simpleEntry )\n {\n phoneticLetters.Add(simpleEntry.Phoneme);\n }\n else\n {\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n }\n else\n {\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n }\n\n if ( phoneticLetters.Count == 0 )\n {\n _wordCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n // Join and apply stress\n var phonemes = string.Join(\"\", phoneticLetters);\n var result = ApplyStress(phonemes, 0);\n\n // Split by secondary stress and join with primary stress\n // This matches the Python implementation more closely\n var parts = result.Split(PhonemizerConstants.SecondaryStress);\n if ( parts.Length > 1 )\n {\n // Taking only the last split, as in Python's rsplit(SECONDARY_STRESS, 1)\n var lastIdx = result.LastIndexOf(PhonemizerConstants.SecondaryStress);\n var beginning = result.Substring(0, lastIdx);\n var end = result.Substring(lastIdx + 1);\n result = beginning + PhonemizerConstants.PrimaryStress + end;\n }\n\n _wordCache[cacheKey] = (result, 3);\n\n return (result, 3);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string? S(string? stem)\n {\n // https://en.wiktionary.org/wiki/-s\n if ( string.IsNullOrEmpty(stem) )\n {\n return null;\n }\n\n // Cache result for frequently used stems\n var cacheKey = $\"S_{stem}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) && cached.Phonemes != null )\n {\n return cached.Phonemes;\n }\n\n string? result;\n if ( \"ptkfθ\".Contains(stem[^1]) )\n {\n result = stem + \"s\";\n }\n else if ( \"szʃʒʧʤ\".Contains(stem[^1]) )\n {\n result = stem + (_british ? \"ɪ\" : \"ᵻ\") + \"z\";\n }\n else\n {\n result = stem + \"z\";\n }\n\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) StemS(string word, string tag, double? stress, TokenContext ctx)\n {\n // Cache lookup\n var cacheKey = $\"StemS_{word}_{tag}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n string stem;\n\n if ( word.Length > 2 && EndsWith(word, \"s\") && !EndsWith(word, \"ss\") && IsKnown(word[..^1], tag) )\n {\n stem = word[..^1];\n }\n else if ( (EndsWith(word, \"'s\") ||\n (word.Length > 4 && EndsWith(word, \"es\") && !EndsWith(word, \"ies\"))) &&\n IsKnown(word[..^2], tag) )\n {\n stem = word[..^2];\n }\n else if ( word.Length > 4 && EndsWith(word, \"ies\") && IsKnown(word[..^3] + \"y\", tag) )\n {\n stem = word[..^3] + \"y\";\n }\n else\n {\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n var (stemPhonemes, rating) = Lookup(stem, tag, stress, ctx);\n if ( stemPhonemes != null )\n {\n var result = (S(stemPhonemes), rating);\n _stemCache[cacheKey] = result;\n\n return result;\n }\n\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string? Ed(string? stem)\n {\n // https://en.wiktionary.org/wiki/-ed\n if ( string.IsNullOrEmpty(stem) )\n {\n return null;\n }\n\n // Cache result for frequently used stems\n var cacheKey = $\"Ed_{stem}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) && cached.Phonemes != null )\n {\n return cached.Phonemes;\n }\n\n string? result;\n if ( \"pkfθʃsʧ\".Contains(stem[^1]) )\n {\n result = stem + \"t\";\n }\n else if ( stem[^1] == 'd' )\n {\n result = stem + (_british ? \"ɪ\" : \"ᵻ\") + \"d\";\n }\n else if ( stem[^1] != 't' )\n {\n result = stem + \"d\";\n }\n else if ( _british || stem.Length < 2 )\n {\n result = stem + \"ɪd\";\n }\n else if ( PhonemizerConstants.UsTaus.Contains(stem[^2]) )\n {\n result = stem[..^1] + \"ɾᵻd\";\n }\n else\n {\n result = stem + \"ᵻd\";\n }\n\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) StemEd(string word, string tag, double? stress, TokenContext ctx)\n {\n // Cache lookup\n var cacheKey = $\"StemEd_{word}_{tag}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n string stem;\n\n if ( EndsWith(word, \"d\") && !EndsWith(word, \"dd\") && IsKnown(word[..^1], tag) )\n {\n stem = word[..^1];\n }\n else if ( EndsWith(word, \"ed\") && !EndsWith(word, \"eed\") && IsKnown(word[..^2], tag) )\n {\n stem = word[..^2];\n }\n else\n {\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n var (stemPhonemes, rating) = Lookup(stem, tag, stress, ctx);\n if ( stemPhonemes != null )\n {\n var result = (Ed(stemPhonemes), rating);\n _stemCache[cacheKey] = result;\n\n return result;\n }\n\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string? Ing(string? stem)\n {\n if ( string.IsNullOrEmpty(stem) )\n {\n return null;\n }\n\n // Cache result for frequently used stems\n var cacheKey = $\"Ing_{stem}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) && cached.Phonemes != null )\n {\n return cached.Phonemes;\n }\n\n string? result;\n if ( _british )\n {\n if ( stem[^1] == 'ə' || stem[^1] == 'ː' )\n {\n _stemCache[cacheKey] = (null, null);\n\n return null;\n }\n }\n else if ( stem.Length > 1 && stem[^1] == 't' && PhonemizerConstants.UsTaus.Contains(stem[^2]) )\n {\n result = stem[..^1] + \"ɾɪŋ\";\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n result = stem + \"ɪŋ\";\n _stemCache[cacheKey] = (result, null);\n\n return result;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private (string?, int?) StemIng(string word, string tag, double stress, TokenContext ctx)\n {\n // Cache lookup\n var cacheKey = $\"StemIng_{word}_{tag}\";\n if ( _stemCache.TryGetValue(cacheKey, out var cached) )\n {\n return cached;\n }\n\n string stem;\n\n if ( EndsWith(word, \"ing\") && IsKnown(word[..^3], tag) )\n {\n stem = word[..^3];\n }\n else if ( EndsWith(word, \"ing\") && IsKnown(word[..^3] + \"e\", tag) )\n {\n stem = word[..^3] + \"e\";\n }\n else if ( _doubleConsonantIngRegex.IsMatch(word) && IsKnown(word[..^4], tag) )\n {\n stem = word[..^4];\n }\n else\n {\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n var (stemPhonemes, rating) = Lookup(stem, tag, stress, ctx);\n if ( stemPhonemes != null )\n {\n var result = (Ing(stemPhonemes), rating);\n _stemCache[cacheKey] = result;\n\n return result;\n }\n\n _stemCache[cacheKey] = (null, null);\n\n return (null, null);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private bool IsNumber(string word, bool isHead)\n {\n // Quick check for any digit\n if ( !word.Any(char.IsDigit) )\n {\n return false;\n }\n\n // Check for valid number format with possible suffixes\n var end = word.Length;\n\n // Check for common suffixes\n foreach ( var suffix in PhonemizerConstants.Ordinals )\n {\n if ( EndsWith(word, suffix) )\n {\n end -= suffix.Length;\n\n break;\n }\n }\n\n if ( EndsWith(word, \"'s\") )\n {\n end -= 2;\n }\n else if ( EndsWith(word, \"s\") )\n {\n end -= 1;\n }\n else if ( EndsWith(word, \"ing\") )\n {\n end -= 3;\n }\n else if ( EndsWith(word, \"'d\") || EndsWith(word, \"ed\") )\n {\n end -= 2;\n }\n\n // Validate characters in the number portion\n for ( var i = 0; i < end; i++ )\n {\n var c = word[i];\n if ( !(char.IsDigit(c) || c == ',' || c == '.' || (isHead && i == 0 && c == '-')) )\n {\n return false;\n }\n }\n\n return true;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static bool IsCurrency(string word)\n {\n if ( !word.Contains('.') )\n {\n return true;\n }\n\n if ( word.Count(c => c == '.') > 1 )\n {\n return false;\n }\n\n var cents = word.Split('.')[1];\n\n return cents.Length < 3 || cents.All(c => c == '0');\n }\n\n private (string?, int?) GetNumber(string word, string? currency, bool isHead, string numFlags)\n {\n // Process suffix (like 'st', 'nd', 'rd', 'th')\n var suffixMatch = _suffixRegex.Match(word);\n var suffix = suffixMatch.Success ? suffixMatch.Value : null;\n\n if ( suffix != null )\n {\n word = word[..^suffix.Length];\n }\n\n var result = new List<(string Phoneme, int Rating)>();\n\n // Handle negative numbers\n if ( word.StartsWith('-') )\n {\n ExtendResult(\"minus\");\n word = word[1..];\n }\n\n // Main number processing logic\n if ( !isHead && !word.Contains('.') )\n {\n var num = word.Replace(\",\", \"\");\n\n // Handle leading zeros or longer numbers digit by digit\n if ( num[0] == '0' || num.Length > 3 )\n {\n foreach ( var digit in num )\n {\n if ( !ExtendResult(digit.ToString(), false) )\n {\n return (null, null);\n }\n }\n }\n // Handle 3-digit numbers that don't end with \"00\"\n else if ( num.Length == 3 && !num.EndsWith(\"00\") )\n {\n // Handle first digit + \"hundred\"\n if ( !ExtendResult(num[0].ToString()) )\n {\n return (null, null);\n }\n\n if ( !ExtendResult(\"hundred\") )\n {\n return (null, null);\n }\n\n // Handle remaining digits\n if ( num[1] == '0' )\n {\n // Special case: x0y\n if ( !ExtendResult(\"O\", specialRating: -2) )\n {\n return (null, null);\n }\n\n if ( !ExtendResult(num[2].ToString(), false) )\n {\n return (null, null);\n }\n }\n else\n {\n // Handle last two digits as a number\n if ( !ExtendNum(int.Parse(num.Substring(1, 2)), false) )\n {\n return (null, null);\n }\n }\n }\n else\n {\n // Standard number conversion\n if ( !ExtendNum(int.Parse(num)) )\n {\n return (null, null);\n }\n }\n }\n else if ( word.Count(c => c == '.') > 1 || !isHead )\n {\n // Handle multiple decimal points or non-head position\n var parts = word.Replace(\",\", \"\").Split('.');\n var isFirst = true;\n\n foreach ( var part in parts )\n {\n if ( string.IsNullOrEmpty(part) )\n {\n continue;\n }\n\n if ( part[0] == '0' || (part.Length != 2 && part.Any(n => n != '0')) )\n {\n // Handle digit by digit\n foreach ( var digit in part )\n {\n if ( !ExtendResult(digit.ToString(), false) )\n {\n return (null, null);\n }\n }\n }\n else\n {\n // Standard number conversion\n if ( !ExtendNum(int.Parse(part), isFirst) )\n {\n return (null, null);\n }\n }\n\n isFirst = false;\n }\n }\n else if ( currency != null && PhonemizerConstants.Currencies.TryGetValue(currency, out var currencyPair) && IsCurrency(word) )\n {\n // Parse the parts\n var parts = word.Replace(\",\", \"\")\n .Split('.')\n .Select(p => string.IsNullOrEmpty(p) ? 0 : int.Parse(p))\n .ToList();\n\n while ( parts.Count < 2 )\n {\n parts.Add(0);\n }\n\n // Filter out zero parts\n var nonZeroParts = parts.Take(2)\n .Select((value, index) => (Value: value, Unit: index == 0 ? currencyPair.Dollar : currencyPair.Cent))\n .Where(p => p.Value != 0)\n .ToList();\n\n for ( var i = 0; i < nonZeroParts.Count; i++ )\n {\n var (value, unit) = nonZeroParts[i];\n\n if ( i > 0 && !ExtendResult(\"and\") )\n {\n return (null, null);\n }\n\n // Convert number to words\n if ( !ExtendNum(value, i == 0) )\n {\n return (null, null);\n }\n\n // Add currency unit\n if ( Math.Abs(value) != 1 && unit != \"pence\" )\n {\n var (unitPhonemes, unitRating) = StemS(unit + \"s\", null, null, null);\n if ( unitPhonemes != null )\n {\n result.Add((unitPhonemes, unitRating.Value));\n }\n else\n {\n return (null, null);\n }\n }\n else\n {\n if ( !ExtendResult(unit) )\n {\n return (null, null);\n }\n }\n }\n }\n else\n {\n // Standard number handling for most cases\n string wordsForm;\n\n if ( int.TryParse(word.Replace(\",\", \"\"), out var number) )\n {\n // Choose conversion type\n var to = \"cardinal\";\n if ( suffix != null && PhonemizerConstants.Ordinals.Contains(suffix) )\n {\n to = \"ordinal\";\n }\n else if ( result.Count == 0 && word.Length == 4 )\n {\n to = \"year\";\n }\n\n wordsForm = Num2Words.Convert(number, to);\n }\n else if ( double.TryParse(word.Replace(\",\", \"\"), out var numberDouble) )\n {\n if ( word.StartsWith(\".\") )\n {\n // Handle \".xx\" format\n wordsForm = \"point \" + string.Join(\" \", word[1..].Select(c => Num2Words.Convert(int.Parse(c.ToString()))));\n }\n else\n {\n wordsForm = Num2Words.Convert(numberDouble);\n }\n }\n else\n {\n return (null, null);\n }\n\n // Process the words form\n if ( !ExtendNum(wordsForm, escape: true) )\n {\n return (null, null);\n }\n }\n\n if ( result.Count == 0 )\n {\n return (null, null);\n }\n\n // Join the phonemes and handle suffix\n var combinedPhoneme = string.Join(\" \", result.Select(r => r.Phoneme));\n var minRating = result.Min(r => r.Rating);\n\n // Apply suffix transformations\n return suffix switch {\n \"s\" or \"'s\" => (S(combinedPhoneme), minRating),\n \"ed\" or \"'d\" => (Ed(combinedPhoneme), minRating),\n \"ing\" => (Ing(combinedPhoneme), minRating),\n _ => (combinedPhoneme, minRating)\n };\n\n // Helper method to extend number words\n bool ExtendNum(object num, bool first = true, bool escape = false)\n {\n var wordsForm = escape ? num.ToString()! : Num2Words.Convert(Convert.ToInt32(num));\n var splits = wordsForm.Split(new[] { ' ', '-' }, StringSplitOptions.RemoveEmptyEntries);\n\n for ( var i = 0; i < splits.Length; i++ )\n {\n var w = splits[i];\n\n if ( w != \"and\" || numFlags.Contains('&') )\n {\n if ( first && i == 0 && splits.Length > 1 && w == \"one\" && numFlags.Contains('a') )\n {\n result.Add((\"ə\", 4));\n }\n else\n {\n double? specialRating = w == \"point\" ? -2.0 : null;\n var (wordPhoneme, wordRating) = Lookup(w, null, specialRating, null);\n if ( wordPhoneme != null )\n {\n result.Add((wordPhoneme, wordRating.Value));\n }\n else\n {\n return false;\n }\n }\n }\n else if ( w == \"and\" && numFlags.Contains('n') && result.Count > 0 )\n {\n // Append \"ən\" to the previous word\n var last = result[^1];\n result[^1] = (last.Phoneme + \"ən\", last.Rating);\n }\n }\n\n return true;\n }\n\n // Helper method to add a single word result\n bool ExtendResult(string word, bool first = true, double? specialRating = null)\n {\n var (phoneme, rating) = Lookup(word, null, specialRating, null);\n if ( phoneme != null )\n {\n result.Add((phoneme, rating.Value));\n\n return true;\n }\n\n return false;\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private string AppendCurrency(string phonemes, string? currency)\n {\n if ( string.IsNullOrEmpty(currency) )\n {\n return phonemes;\n }\n\n if ( !PhonemizerConstants.Currencies.TryGetValue(currency, out var currencyPair) )\n {\n return phonemes;\n }\n\n var (stemPhonemes, _) = StemS(currencyPair.Dollar + \"s\", null, null, null);\n if ( stemPhonemes != null )\n {\n return $\"{phonemes} {stemPhonemes}\";\n }\n\n return phonemes;\n }\n\n [GeneratedRegex(@\"(?i)vs\\.?$\", RegexOptions.Compiled, \"en-BE\")]\n private static partial Regex VersusRegex();\n\n [GeneratedRegex(@\"([bcdgklmnprstvxz])\\1ing$|cking$\", RegexOptions.Compiled)]\n private static partial Regex DoubleConsonantIngRegex();\n\n [GeneratedRegex(@\"[a-z']+$\", RegexOptions.Compiled)]\n private static partial Regex SuffixRegex();\n}\n\npublic class LruCache(int capacity, IEqualityComparer comparer)\n where TKey : notnull\n{\n private readonly Dictionary> _cacheMap = new(capacity, comparer);\n\n private readonly LinkedList _lruList = new();\n\n public TValue this[TKey key]\n {\n get\n {\n if ( _cacheMap.TryGetValue(key, out var node) )\n {\n _lruList.Remove(node);\n _lruList.AddFirst(node);\n\n return node.Value.Value;\n }\n\n throw new KeyNotFoundException($\"Key {key} not found in cache\");\n }\n\n set\n {\n if ( _cacheMap.TryGetValue(key, out var existingNode) )\n {\n _lruList.Remove(existingNode);\n _lruList.AddFirst(existingNode);\n existingNode.Value.Value = value;\n\n return;\n }\n\n if ( _cacheMap.Count >= capacity )\n {\n var last = _lruList.Last;\n if ( last != null )\n {\n _cacheMap.Remove(last.Value.Key);\n _lruList.RemoveLast();\n }\n }\n\n var cacheItem = new LruCacheItem(key, value);\n var newNode = new LinkedListNode(cacheItem);\n _lruList.AddFirst(newNode);\n _cacheMap.Add(key, newNode);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public bool TryGetValue(TKey key, out TValue value)\n {\n if ( _cacheMap.TryGetValue(key, out var node) )\n {\n _lruList.Remove(node);\n _lruList.AddFirst(node);\n\n value = node.Value.Value;\n\n return true;\n }\n\n value = default!;\n\n return false;\n }\n\n public void Clear()\n {\n _cacheMap.Clear();\n _lruList.Clear();\n }\n\n private record LruCacheItem(TKey Key, TValue Value)\n {\n public TValue Value { get; set; } = Value;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Audio/Player/TimedPlaybackController.cs", "using System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\n\nnamespace PersonaEngine.Lib.Audio.Player;\n\n/// \n/// Implementation of IPlaybackController that works with large audio segments.\n/// \npublic class TimedPlaybackController : IPlaybackController\n{\n private readonly int _initialBufferMs;\n\n private readonly double _latencyThresholdMs;\n\n private readonly ILogger _logger;\n\n private readonly Stopwatch _playbackTimer = new();\n\n // For time updates\n private readonly object _timeLock = new();\n\n private readonly int _timeUpdateIntervalMs;\n\n private readonly Timer _timeUpdateTimer;\n\n // Latency tracking\n\n private int _currentSampleRate;\n\n private double _lastReportedLatencyMs;\n\n private long _startTimeMs; // When playback actually started (system time)\n\n /// \n /// Initializes a new instance of the TimedPlaybackController class.\n /// \n /// Initial buffer size in milliseconds.\n /// Threshold for significant latency changes in milliseconds.\n /// Interval in milliseconds for time updates.\n /// Logger instance.\n public TimedPlaybackController(\n int initialBufferMs = 20,\n double latencyThresholdMs = 20.0,\n int timeUpdateIntervalMs = 20,\n ILogger? logger = null)\n {\n _initialBufferMs = initialBufferMs;\n _latencyThresholdMs = latencyThresholdMs;\n _timeUpdateIntervalMs = timeUpdateIntervalMs;\n _logger = logger ?? NullLogger.Instance;\n\n // Start a timer to update the playback time periodically\n _timeUpdateTimer = new Timer(UpdateTime, null, Timeout.Infinite, Timeout.Infinite);\n }\n\n /// \n public float CurrentTime { get; private set; }\n\n /// \n public long TotalSamplesPlayed { get; private set; }\n\n /// \n public double CurrentLatencyMs { get; private set; }\n\n /// \n public bool HasLatencyInformation { get; private set; }\n\n /// \n /// Event that fires when the playback time changes substantially.\n /// \n public event EventHandler TimeChanged\n {\n add\n {\n lock (_timeLock)\n {\n TimeChangedInternal += value;\n }\n }\n remove\n {\n lock (_timeLock)\n {\n TimeChangedInternal -= value;\n }\n }\n }\n\n /// \n public event EventHandler? LatencyChanged;\n\n /// \n public void Reset()\n {\n _playbackTimer.Reset();\n TotalSamplesPlayed = 0;\n CurrentTime = 0;\n _startTimeMs = 0;\n\n // Stop the time update timer\n _timeUpdateTimer.Change(Timeout.Infinite, Timeout.Infinite);\n }\n\n /// \n public void UpdateLatency(double latencyMs)\n {\n var oldLatency = CurrentLatencyMs;\n CurrentLatencyMs = latencyMs;\n HasLatencyInformation = true;\n\n // Only notify if the change is significant\n if ( Math.Abs(latencyMs - _lastReportedLatencyMs) >= _latencyThresholdMs )\n {\n _logger.LogInformation(\"Playback latency updated: {OldLatency:F1}ms -> {NewLatency:F1}ms\",\n oldLatency, latencyMs);\n\n _lastReportedLatencyMs = latencyMs;\n LatencyChanged?.Invoke(this, latencyMs);\n }\n }\n\n /// \n public Task SchedulePlaybackAsync(int samplesPerChannel, int sampleRate, CancellationToken cancellationToken)\n {\n // Store the sample rate for time calculations\n _currentSampleRate = sampleRate;\n\n // Update total samples\n TotalSamplesPlayed += samplesPerChannel;\n\n // Start the playback timer if this is the first call\n if ( !_playbackTimer.IsRunning )\n {\n _logger.LogDebug(\"Starting playback timer\");\n\n // Account for initial buffering\n var initialBufferMs = HasLatencyInformation\n ? Math.Max(50, _initialBufferMs + CurrentLatencyMs)\n : _initialBufferMs;\n\n // Record when playback will actually start (now + buffer)\n _startTimeMs = Environment.TickCount64 + (long)initialBufferMs;\n\n // Start the stopwatch for measuring elapsed time\n _playbackTimer.Start();\n\n // Start the timer to update current time periodically\n _timeUpdateTimer.Change(_timeUpdateIntervalMs, _timeUpdateIntervalMs);\n }\n\n // Always send the data - the transport will handle chunking\n return Task.FromResult(true);\n }\n\n /// \n /// Disposes resources used by the controller.\n /// \n public void Dispose() { _timeUpdateTimer.Dispose(); }\n\n private event EventHandler? TimeChangedInternal;\n\n // Private methods\n\n private void UpdateTime(object? state)\n {\n if ( !_playbackTimer.IsRunning || _currentSampleRate <= 0 )\n {\n return;\n }\n\n // Calculate current system time\n var currentTimeMs = Environment.TickCount64;\n\n // Calculate how much time has passed since playback started\n var elapsedSinceStartMs = currentTimeMs > _startTimeMs\n ? currentTimeMs - _startTimeMs\n : 0;\n\n // Apply latency adjustment if available\n var adjustedElapsedMs = HasLatencyInformation\n ? elapsedSinceStartMs - CurrentLatencyMs\n : elapsedSinceStartMs;\n\n // Don't allow negative time\n adjustedElapsedMs = Math.Max(0, adjustedElapsedMs);\n\n // Convert to seconds\n var newPlaybackTime = (float)(adjustedElapsedMs / 1000.0);\n\n // Only update and notify if the time changed significantly\n if ( Math.Abs(newPlaybackTime - CurrentTime) >= 0.01f ) // 10ms threshold\n {\n CurrentTime = newPlaybackTime;\n\n EventHandler? handler;\n lock (_timeLock)\n {\n handler = TimeChangedInternal;\n }\n\n handler?.Invoke(this, newPlaybackTime);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/TtsMemoryCache.cs", "using System.Collections.Concurrent;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Enhanced memory-efficient TTS cache implementation with expiration and metrics\n/// \npublic class TtsMemoryCache : ITtsCache, IAsyncDisposable\n{\n private readonly ConcurrentDictionary _cache = new();\n\n private readonly Timer _cleanupTimer;\n\n private readonly ILogger _logger;\n\n private readonly TtsCacheOptions _options;\n\n private readonly ConcurrentDictionary _pendingOperations = new();\n\n private bool _disposed;\n\n private long _evictions;\n\n // Metrics\n private long _hits;\n\n private long _misses;\n\n public TtsMemoryCache(\n ILogger logger,\n IOptions options = null)\n {\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _options = options?.Value ?? new TtsCacheOptions();\n\n // Set up periodic cleanup if expiration is enabled\n if ( _options.ItemExpiration.HasValue )\n {\n // Run cleanup at half the expiration interval or at least every minute\n var cleanupInterval = TimeSpan.FromMilliseconds(\n Math.Max(_options.ItemExpiration.Value.TotalMilliseconds / 2, 60000));\n\n _cleanupTimer = new Timer(CleanupExpiredItems, null, cleanupInterval, cleanupInterval);\n }\n }\n\n /// \n /// Gets or adds an item to the cache with metrics and expiration support\n /// \n public async Task GetOrAddAsync(\n string key,\n Func> valueFactory,\n CancellationToken cancellationToken = default) where T : class\n {\n // Argument validation\n if ( string.IsNullOrEmpty(key) )\n {\n throw new ArgumentException(\"Cache key cannot be null or empty\", nameof(key));\n }\n\n if ( valueFactory == null )\n {\n throw new ArgumentNullException(nameof(valueFactory));\n }\n\n // Check for cancellation\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check if the item exists in cache and is valid\n if ( _cache.TryGetValue(key, out var cacheItem) )\n {\n if ( cacheItem.Value is T typedValue && !IsExpired(cacheItem) )\n {\n Interlocked.Increment(ref _hits);\n _logger.LogDebug(\"Cache hit for key {Key}\", key);\n\n return typedValue;\n }\n\n // Item exists but is either wrong type or expired - remove it\n _cache.TryRemove(key, out _);\n }\n\n // Item not in cache or was invalid, create it\n Interlocked.Increment(ref _misses);\n _logger.LogDebug(\"Cache miss for key {Key}, creating new value\", key);\n\n var stopwatch = new Stopwatch();\n if ( _options.CollectMetrics )\n {\n _pendingOperations[key] = stopwatch;\n stopwatch.Start();\n }\n\n try\n {\n // Create the value\n var value = await valueFactory(cancellationToken);\n\n if ( value == null )\n {\n _logger.LogWarning(\"Value factory for key {Key} returned null\", key);\n\n return null;\n }\n\n // Enforce maximum cache size if configured\n EnforceSizeLimit();\n\n // Add to cache using GetOrAdd to handle the case where another thread might have\n // added the same key while we were creating the value\n var newItem = new CacheItem { Value = value };\n var actualItem = _cache.GetOrAdd(key, newItem);\n\n // If another thread beat us to it and that value is of the correct type, use it\n if ( actualItem != newItem && actualItem.Value is T existingValue && !IsExpired(actualItem) )\n {\n _logger.LogDebug(\"Another thread already added key {Key}\", key);\n\n return existingValue;\n }\n\n return value;\n }\n catch (Exception ex) when (ex is not OperationCanceledException)\n {\n _logger.LogError(ex, \"Error creating value for key {Key}\", key);\n\n throw;\n }\n finally\n {\n if ( _options.CollectMetrics && _pendingOperations.TryRemove(key, out var sw) )\n {\n sw.Stop();\n _logger.LogDebug(\"Value creation for key {Key} took {ElapsedMs}ms\", key, sw.ElapsedMilliseconds);\n }\n }\n }\n\n /// \n /// Removes an item from the cache\n /// \n public void Remove(string key)\n {\n if ( string.IsNullOrEmpty(key) )\n {\n throw new ArgumentException(\"Cache key cannot be null or empty\", nameof(key));\n }\n\n if ( _cache.TryRemove(key, out _) )\n {\n _logger.LogDebug(\"Removed item with key {Key} from cache\", key);\n }\n }\n\n /// \n /// Clears the cache\n /// \n public void Clear()\n {\n _cache.Clear();\n _logger.LogInformation(\"Cache cleared\");\n }\n\n /// \n /// Disposes the cache resources\n /// \n public async ValueTask DisposeAsync()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n\n _cleanupTimer?.Dispose();\n _cache.Clear();\n\n var stats = GetStatistics();\n _logger.LogInformation(\n \"Cache disposed. Final stats: Size={Size}, Hits={Hits}, Misses={Misses}, Evictions={Evictions}\",\n stats.Size, stats.Hits, stats.Misses, stats.Evictions);\n\n await Task.CompletedTask;\n }\n\n /// \n /// Gets the current cache statistics\n /// \n public (int Size, long Hits, long Misses, long Evictions) GetStatistics() { return (_cache.Count, _hits, _misses, _evictions); }\n\n /// \n /// Determines if a cache item has expired\n /// \n private bool IsExpired(CacheItem item)\n {\n if ( _options.ItemExpiration == null )\n {\n return false;\n }\n\n return DateTime.UtcNow - item.CreatedAt > _options.ItemExpiration.Value;\n }\n\n /// \n /// Enforces the maximum cache size by removing oldest items if necessary\n /// \n private void EnforceSizeLimit()\n {\n if ( _options.MaxItems <= 0 || _cache.Count < _options.MaxItems )\n {\n return;\n }\n\n // Get all items with their ages\n var items = _cache.ToArray();\n\n // Sort by creation time (oldest first)\n Array.Sort(items, (a, b) => a.Value.CreatedAt.CompareTo(b.Value.CreatedAt));\n\n // Remove oldest items to get back under the limit\n // We'll remove 10% of max capacity to avoid doing this too frequently\n var toRemove = Math.Max(1, _options.MaxItems / 10);\n\n for ( var i = 0; i < toRemove && i < items.Length; i++ )\n {\n if ( _cache.TryRemove(items[i].Key, out _) )\n {\n Interlocked.Increment(ref _evictions);\n }\n }\n\n _logger.LogInformation(\"Removed {Count} items from cache due to size limit\", toRemove);\n }\n\n /// \n /// Periodically removes expired items from the cache\n /// \n private void CleanupExpiredItems(object state)\n {\n if ( _disposed )\n {\n return;\n }\n\n try\n {\n var removed = 0;\n foreach ( var key in _cache.Keys )\n {\n if ( _cache.TryGetValue(key, out var item) && IsExpired(item) )\n {\n if ( _cache.TryRemove(key, out _) )\n {\n removed++;\n Interlocked.Increment(ref _evictions);\n }\n }\n }\n\n if ( removed > 0 )\n {\n _logger.LogInformation(\"Removed {Count} expired items from cache\", removed);\n }\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during cache cleanup\");\n }\n }\n\n private class CacheItem\n {\n public object Value { get; set; }\n\n public DateTime CreatedAt { get; } = DateTime.UtcNow;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/FontProvider.cs", "using System.Drawing;\n\nusing FontStashSharp;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.UI.Common;\nusing PersonaEngine.Lib.UI.Text.Rendering;\n\nusing Silk.NET.OpenGL;\n\nusing StbImageSharp;\n\nusing Texture = PersonaEngine.Lib.UI.Common.Texture;\n\nnamespace PersonaEngine.Lib.UI;\n\n/// \n/// Manages caching and loading of fonts and textures.\n/// \npublic class FontProvider : IStartupTask\n{\n private const string FONTS_DIR = @\"Resources\\Fonts\";\n\n private const string IMAGES_PATH = @\"Resources\\Imgs\";\n\n private readonly Dictionary _fontCache = new();\n\n private readonly ILogger _logger;\n\n private readonly Dictionary _textureCache = new();\n\n private Texture2DManager _texture2DManager = null!;\n\n // static FontProvider()\n // {\n // FontSystemDefaults.FontLoader = new SixLaborsFontLoader();\n // }\n\n public FontProvider(ILogger logger) { _logger = logger; }\n\n public void Execute(GL gl) { _texture2DManager = new Texture2DManager(gl); }\n\n public Task> GetAvailableFontsAsync(CancellationToken cancellationToken = default)\n {\n try\n {\n if ( !Directory.Exists(FONTS_DIR) )\n {\n _logger.LogWarning(\"Fonts directory not found: {Path}\", FONTS_DIR);\n\n return Task.FromResult>(Array.Empty());\n }\n\n var fontFiles = Directory.GetFiles(FONTS_DIR, \"*.ttf\");\n var fontNames = new List(fontFiles.Length);\n foreach ( var file in fontFiles )\n {\n var voiceId = Path.GetFileName(file);\n fontNames.Add(voiceId);\n }\n\n _logger.LogInformation(\"Found {Count} available fonts\", fontNames.Count);\n\n return Task.FromResult>(fontNames);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error getting available fonts\");\n\n throw;\n }\n }\n\n public FontSystem GetFontSystem(string fontName)\n {\n if ( !_fontCache.TryGetValue(fontName, out var fontSystem) )\n {\n fontSystem = new FontSystem();\n var fontData = File.ReadAllBytes(Path.Combine(FONTS_DIR, fontName));\n fontSystem.AddFont(fontData);\n _fontCache[fontName] = fontSystem;\n }\n\n return fontSystem;\n }\n\n public Texture GetTexture(string imageName)\n {\n if ( !_textureCache.TryGetValue(imageName, out var texture) )\n {\n using var stream = File.OpenRead(Path.Combine(IMAGES_PATH, imageName));\n var imageResult = ImageResult.FromStream(stream, ColorComponents.RedGreenBlueAlpha);\n\n // Premultiply alpha\n unsafe\n {\n fixed (byte* b = imageResult.Data)\n {\n var ptr = b;\n for ( var i = 0; i < imageResult.Data.Length; i += 4, ptr += 4 )\n {\n var falpha = ptr[3] / 255.0f;\n ptr[0] = (byte)(ptr[0] * falpha);\n ptr[1] = (byte)(ptr[1] * falpha);\n ptr[2] = (byte)(ptr[2] * falpha);\n }\n }\n }\n\n texture = (Texture)_texture2DManager.CreateTexture(imageResult.Width, imageResult.Height);\n _texture2DManager.SetTextureData(texture, new Rectangle(0, 0, (int)texture.Width, (int)texture.Height), imageResult.Data);\n _textureCache[imageName] = texture;\n }\n\n return texture;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Core/CubismCore.cs", "using System.Numerics;\nusing System.Runtime.InteropServices;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Core;\n\npublic static class CsmEnum\n{\n //Alignment constraints.\n\n /// \n /// Necessary alignment for mocs (in bytes).\n /// \n public const int csmAlignofMoc = 64;\n\n /// \n /// Necessary alignment for models (in bytes).\n /// \n public const int CsmAlignofModel = 16;\n\n //Bit masks for non-dynamic drawable flags.\n\n /// \n /// Additive blend mode mask.\n /// \n public const byte CsmBlendAdditive = 1 << 0;\n\n /// \n /// Multiplicative blend mode mask.\n /// \n public const byte CsmBlendMultiplicative = 1 << 1;\n\n /// \n /// Double-sidedness mask.\n /// \n public const byte CsmIsDoubleSided = 1 << 2;\n\n /// \n /// Clipping mask inversion mode mask.\n /// \n public const byte CsmIsInvertedMask = 1 << 3;\n\n //Bit masks for dynamic drawable flags.\n\n /// \n /// Flag set when visible.\n /// \n public const byte CsmIsVisible = 1 << 0;\n\n /// \n /// Flag set when visibility did change.\n /// \n public const byte CsmVisibilityDidChange = 1 << 1;\n\n /// \n /// Flag set when opacity did change.\n /// \n public const byte CsmOpacityDidChange = 1 << 2;\n\n /// \n /// Flag set when draw order did change.\n /// \n public const byte CsmDrawOrderDidChange = 1 << 3;\n\n /// \n /// Flag set when render order did change.\n /// \n public const byte CsmRenderOrderDidChange = 1 << 4;\n\n /// \n /// Flag set when vertex positions did change.\n /// \n public const byte CsmVertexPositionsDidChange = 1 << 5;\n\n /// \n /// Flag set when blend color did change.\n /// \n public const byte CsmBlendColorDidChange = 1 << 6;\n\n //moc3 file format version.\n\n /// \n /// unknown\n /// \n public const int CsmMocVersion_Unknown = 0;\n\n /// \n /// moc3 file version 3.0.00 - 3.2.07\n /// \n public const int CsmMocVersion_30 = 1;\n\n /// \n /// moc3 file version 3.3.00 - 3.3.03\n /// \n public const int CsmMocVersion_33 = 2;\n\n /// \n /// moc3 file version 4.0.00 - 4.1.05\n /// \n public const int CsmMocVersion_40 = 3;\n\n /// \n /// moc3 file version 4.2.00 -\n /// \n public const int CsmMocVersion_42 = 4;\n\n //Parameter types.\n\n /// \n /// Normal parameter.\n /// \n public const int CsmParameterType_Normal = 0;\n\n /// \n /// Parameter for blend shape.\n /// \n public const int CsmParameterType_BlendShape = 1;\n}\n\n/// \n/// Log handler.\n/// \n/// Null-terminated string message to log.\npublic delegate void LogFunction(string message);\n\npublic static partial class CubismCore\n{\n //VERSION\n\n public static uint Version() { return GetVersion(); }\n\n /// \n /// Queries Core version.\n /// \n /// Core version.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetVersion\")]\n internal static partial uint GetVersion();\n\n /// \n /// Gets Moc file supported latest version.\n /// \n /// csmMocVersion (Moc file latest format version).\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetLatestMocVersion\")]\n internal static partial uint GetLatestMocVersion();\n\n /// \n /// Gets Moc file format version.\n /// \n /// Address of moc.\n /// Size of moc (in bytes).\n /// csmMocVersion\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetMocVersion\")]\n internal static partial uint GetMocVersion(IntPtr address, int size);\n\n //CONSISTENCY\n\n /// \n /// Checks consistency of a moc.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// '1' if Moc is valid; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmHasMocConsistency\")]\n [return: MarshalAs(UnmanagedType.I4)]\n internal static partial bool HasMocConsistency(IntPtr address, int size);\n\n //LOGGING\n\n /// \n /// Queries log handler.\n /// \n /// Log handler.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetLogFunction\")]\n internal static partial LogFunction GetLogFunction();\n\n /// \n /// Sets log handler.\n /// \n /// Handler to use.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmSetLogFunction\")]\n internal static partial void SetLogFunction(LogFunction handler);\n\n //MOC\n\n /// \n /// Tries to revive a moc from bytes in place.\n /// \n /// Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.\n /// Size of moc (in bytes).\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmReviveMocInPlace\")]\n internal static partial IntPtr ReviveMocInPlace(IntPtr address, int size);\n\n //MODEL\n\n /// \n /// Queries size of a model in bytes.\n /// \n /// Moc to query.\n /// Valid size on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetSizeofModel\")]\n internal static partial int GetSizeofModel(IntPtr moc);\n\n /// \n /// Tries to instantiate a model in place.\n /// \n /// Source moc.\n /// Address to place instance at. Address must be aligned to 'csmAlignofModel'.\n /// Size of memory block for instance (in bytes).\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmInitializeModelInPlace\")]\n internal static partial IntPtr InitializeModelInPlace(IntPtr moc, IntPtr address, int size);\n\n /// \n /// Updates a model.\n /// \n /// Model to update.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmUpdateModel\")]\n internal static partial void UpdateModel(IntPtr model);\n\n //CANVAS\n\n /// \n /// Reads info on a model canvas.\n /// \n /// Model query.\n /// Canvas dimensions.\n /// Origin of model on canvas.\n /// Aspect used for scaling pixels to units.\n [DllImport(\"Live2DCubismCore\", EntryPoint = \"csmReadCanvasInfo\")]\n#pragma warning disable SYSLIB1054 // 使用 “LibraryImportAttribute” 而不是 “DllImportAttribute” 在编译时生成 P/Invoke 封送代码\n internal static extern void ReadCanvasInfo(IntPtr model, out Vector2 outSizeInPixels,\n#pragma warning restore SYSLIB1054 // 使用 “LibraryImportAttribute” 而不是 “DllImportAttribute” 在编译时生成 P/Invoke 封送代码\n out Vector2 outOriginInPixels, out float outPixelsPerUnit);\n\n //PARAMETERS\n\n /// \n /// Gets number of parameters.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterCount\")]\n internal static partial int GetParameterCount(IntPtr model);\n\n /// \n /// Gets parameter IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterIds\")]\n internal static unsafe partial sbyte** GetParameterIds(IntPtr model);\n\n /// \n /// Gets parameter types.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterTypes\")]\n internal static unsafe partial int* GetParameterTypes(IntPtr model);\n\n /// \n /// Gets minimum parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterMinimumValues\")]\n internal static unsafe partial float* GetParameterMinimumValues(IntPtr model);\n\n /// \n /// Gets maximum parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterMaximumValues\")]\n internal static unsafe partial float* GetParameterMaximumValues(IntPtr model);\n\n /// \n /// Gets default parameter values.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterDefaultValues\")]\n internal static unsafe partial float* GetParameterDefaultValues(IntPtr model);\n\n /// \n /// Gets read/write parameter values buffer.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterValues\")]\n internal static unsafe partial float* GetParameterValues(IntPtr model);\n\n /// \n /// Gets number of key values of each parameter.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterKeyCounts\")]\n internal static unsafe partial int* GetParameterKeyCounts(IntPtr model);\n\n /// \n /// Gets key values of each parameter.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetParameterKeyValues\")]\n internal static unsafe partial float** GetParameterKeyValues(IntPtr model);\n\n //PARTS\n\n /// \n /// Gets number of parts.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartCount\")]\n internal static partial int GetPartCount(IntPtr model);\n\n /// \n /// Gets parts IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartIds\")]\n internal static unsafe partial sbyte** GetPartIds(IntPtr model);\n\n /// \n /// Gets read/write part opacities buffer.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartOpacities\")]\n internal static unsafe partial float* GetPartOpacities(IntPtr model);\n\n /// \n /// Gets part's parent part indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetPartParentPartIndices\")]\n internal static unsafe partial int* GetPartParentPartIndices(IntPtr model);\n\n //DRAWABLES\n\n /// \n /// Gets number of drawables.\n /// \n /// Model to query.\n /// Valid count on success; '-1' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableCount\")]\n internal static partial int GetDrawableCount(IntPtr model);\n\n /// \n /// Gets drawable IDs.\n /// All IDs are null-terminated ANSI strings.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIds\")]\n internal static unsafe partial sbyte** GetDrawableIds(IntPtr model);\n\n /// \n /// Gets constant drawable flags.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableConstantFlags\")]\n internal static unsafe partial byte* GetDrawableConstantFlags(IntPtr model);\n\n /// \n /// Gets dynamic drawable flags.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableDynamicFlags\")]\n internal static unsafe partial byte* GetDrawableDynamicFlags(IntPtr model);\n\n /// \n /// Gets drawable texture indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableTextureIndices\")]\n internal static unsafe partial int* GetDrawableTextureIndices(IntPtr model);\n\n /// \n /// Gets drawable draw orders.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableDrawOrders\")]\n internal static unsafe partial int* GetDrawableDrawOrders(IntPtr model);\n\n /// \n /// Gets drawable render orders.\n /// The higher the order, the more up front a drawable is.\n /// \n /// Model to query.\n /// Valid pointer on success; '0'otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableRenderOrders\")]\n internal static unsafe partial int* GetDrawableRenderOrders(IntPtr model);\n\n /// \n /// Gets drawable opacities.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableOpacities\")]\n internal static unsafe partial float* GetDrawableOpacities(IntPtr model);\n\n /// \n /// Gets numbers of masks of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMaskCounts\")]\n internal static unsafe partial int* GetDrawableMaskCounts(IntPtr model);\n\n /// \n /// Gets number of vertices of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMasks\")]\n internal static unsafe partial int** GetDrawableMasks(IntPtr model);\n\n /// \n /// Gets number of vertices of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexCounts\")]\n internal static unsafe partial int* GetDrawableVertexCounts(IntPtr model);\n\n /// \n /// Gets vertex position data of each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; a null pointer otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexPositions\")]\n internal static unsafe partial Vector2** GetDrawableVertexPositions(IntPtr model);\n\n /// \n /// Gets texture coordinate data of each drawables.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableVertexUvs\")]\n internal static unsafe partial Vector2** GetDrawableVertexUvs(IntPtr model);\n\n /// \n /// Gets number of triangle indices for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIndexCounts\")]\n internal static unsafe partial int* GetDrawableIndexCounts(IntPtr model);\n\n /// \n /// Gets triangle index data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableIndices\")]\n internal static unsafe partial ushort** GetDrawableIndices(IntPtr model);\n\n /// \n /// Gets multiply color data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableMultiplyColors\")]\n internal static unsafe partial Vector4* GetDrawableMultiplyColors(IntPtr model);\n\n /// \n /// Gets screen color data for each drawable.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableScreenColors\")]\n internal static unsafe partial Vector4* GetDrawableScreenColors(IntPtr model);\n\n /// \n /// Gets drawable's parent part indices.\n /// \n /// Model to query.\n /// Valid pointer on success; '0' otherwise.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmGetDrawableParentPartIndices\")]\n internal static unsafe partial int* GetDrawableParentPartIndices(IntPtr model);\n\n /// \n /// Resets all dynamic drawable flags.\n /// \n /// Model containing flags.\n [LibraryImport(\"Live2DCubismCore\", EntryPoint = \"csmResetDrawableDynamicFlags\")]\n internal static unsafe partial void ResetDrawableDynamicFlags(IntPtr model);\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Rendering/OpenGL/CubismRendererProfile_OpenGLES2.cs", "namespace PersonaEngine.Lib.Live2D.Framework.Rendering.OpenGL;\n\ninternal class CubismRendererProfile_OpenGLES2(OpenGLApi gl)\n{\n /// \n /// モデル描画直前のアクティブなテクスチャ\n /// \n internal int LastActiveTexture;\n\n /// \n /// モデル描画直前の頂点バッファ\n /// \n internal int LastArrayBufferBinding;\n\n /// \n /// モデル描画直前のGL_SCISSOR_TESTパラメータ\n /// \n internal bool LastBlend;\n\n /// \n /// モデル描画直前のカラーブレンディングパラメータ\n /// \n internal int[] LastBlending = new int[4];\n\n /// \n /// モデル描画直前のGL_COLOR_WRITEMASKパラメータ\n /// \n internal bool[] LastColorMask = new bool[4];\n\n /// \n /// モデル描画直前のGL_CULL_FACEパラメータ\n /// \n internal bool LastCullFace;\n\n /// \n /// モデル描画直前のGL_DEPTH_TESTパラメータ\n /// \n internal bool LastDepthTest;\n\n /// \n /// モデル描画直前のElementバッファ\n /// \n internal int LastElementArrayBufferBinding;\n\n /// \n /// モデル描画直前のフレームバッファ\n /// \n internal int LastFBO;\n\n /// \n /// モデル描画直前のGL_CULL_FACEパラメータ\n /// \n internal int LastFrontFace;\n\n /// \n /// モデル描画直前のシェーダプログラムバッファ\n /// \n internal int LastProgram;\n\n /// \n /// モデル描画直前のGL_VERTEX_ATTRIB_ARRAY_ENABLEDパラメータ\n /// \n internal bool LastScissorTest;\n\n /// \n /// モデル描画直前のGL_STENCIL_TESTパラメータ\n /// \n internal bool LastStencilTest;\n\n /// \n /// モデル描画直前のテクスチャユニット0\n /// \n internal int LastTexture0Binding2D;\n\n /// \n /// モデル描画直前のテクスチャユニット1\n /// \n internal int LastTexture1Binding2D;\n\n /// \n /// モデル描画直前のテクスチャユニット1\n /// \n internal int[] LastVertexAttribArrayEnabled = new int[4];\n\n /// \n /// モデル描画直前のビューポート\n /// \n internal int[] LastViewport = new int[4];\n\n /// \n /// OpenGLES2のステートを保持する\n /// \n internal void Save()\n {\n //-- push state --\n gl.GetIntegerv(gl.GL_ARRAY_BUFFER_BINDING, out LastArrayBufferBinding);\n gl.GetIntegerv(gl.GL_ELEMENT_ARRAY_BUFFER_BINDING, out LastElementArrayBufferBinding);\n gl.GetIntegerv(gl.GL_CURRENT_PROGRAM, out LastProgram);\n\n gl.GetIntegerv(gl.GL_ACTIVE_TEXTURE, out LastActiveTexture);\n gl.ActiveTexture(gl.GL_TEXTURE1); //テクスチャユニット1をアクティブに(以後の設定対象とする)\n gl.GetIntegerv(gl.GL_TEXTURE_BINDING_2D, out LastTexture1Binding2D);\n\n gl.ActiveTexture(gl.GL_TEXTURE0); //テクスチャユニット0をアクティブに(以後の設定対象とする)\n gl.GetIntegerv(gl.GL_TEXTURE_BINDING_2D, out LastTexture0Binding2D);\n\n gl.GetVertexAttribiv(0, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[0]);\n gl.GetVertexAttribiv(1, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[1]);\n gl.GetVertexAttribiv(2, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[2]);\n gl.GetVertexAttribiv(3, gl.GL_VERTEX_ATTRIB_ARRAY_ENABLED, out LastVertexAttribArrayEnabled[3]);\n\n LastScissorTest = gl.IsEnabled(gl.GL_SCISSOR_TEST);\n LastStencilTest = gl.IsEnabled(gl.GL_STENCIL_TEST);\n LastDepthTest = gl.IsEnabled(gl.GL_DEPTH_TEST);\n LastCullFace = gl.IsEnabled(gl.GL_CULL_FACE);\n LastBlend = gl.IsEnabled(gl.GL_BLEND);\n\n gl.GetIntegerv(gl.GL_FRONT_FACE, out LastFrontFace);\n\n gl.GetBooleanv(gl.GL_COLOR_WRITEMASK, LastColorMask);\n\n // backup blending\n gl.GetIntegerv(gl.GL_BLEND_SRC_RGB, out LastBlending[0]);\n gl.GetIntegerv(gl.GL_BLEND_DST_RGB, out LastBlending[1]);\n gl.GetIntegerv(gl.GL_BLEND_SRC_ALPHA, out LastBlending[2]);\n gl.GetIntegerv(gl.GL_BLEND_DST_ALPHA, out LastBlending[3]);\n\n // モデル描画直前のFBOとビューポートを保存\n gl.GetIntegerv(gl.GL_FRAMEBUFFER_BINDING, out LastFBO);\n gl.GetIntegerv(gl.GL_VIEWPORT, LastViewport);\n }\n\n /// \n /// 保持したOpenGLES2のステートを復帰させる\n /// \n internal void Restore()\n {\n gl.UseProgram(LastProgram);\n\n SetGlEnableVertexAttribArray(0, LastVertexAttribArrayEnabled[0] > 0);\n SetGlEnableVertexAttribArray(1, LastVertexAttribArrayEnabled[1] > 0);\n SetGlEnableVertexAttribArray(2, LastVertexAttribArrayEnabled[2] > 0);\n SetGlEnableVertexAttribArray(3, LastVertexAttribArrayEnabled[3] > 0);\n\n SetGlEnable(gl.GL_SCISSOR_TEST, LastScissorTest);\n SetGlEnable(gl.GL_STENCIL_TEST, LastStencilTest);\n SetGlEnable(gl.GL_DEPTH_TEST, LastDepthTest);\n SetGlEnable(gl.GL_CULL_FACE, LastCullFace);\n SetGlEnable(gl.GL_BLEND, LastBlend);\n\n gl.FrontFace(LastFrontFace);\n\n gl.ColorMask(LastColorMask[0], LastColorMask[1], LastColorMask[2], LastColorMask[3]);\n\n gl.BindBuffer(gl.GL_ARRAY_BUFFER, LastArrayBufferBinding); //前にバッファがバインドされていたら破棄する必要がある\n gl.BindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, LastElementArrayBufferBinding);\n\n gl.ActiveTexture(gl.GL_TEXTURE1); //テクスチャユニット1を復元\n gl.BindTexture(gl.GL_TEXTURE_2D, LastTexture1Binding2D);\n\n gl.ActiveTexture(gl.GL_TEXTURE0); //テクスチャユニット0を復元\n gl.BindTexture(gl.GL_TEXTURE_2D, LastTexture0Binding2D);\n\n gl.ActiveTexture(LastActiveTexture);\n\n // restore blending\n gl.BlendFuncSeparate(LastBlending[0], LastBlending[1], LastBlending[2], LastBlending[3]);\n }\n\n /// \n /// OpenGLES2の機能の有効・無効をセットする\n /// \n /// 有効・無効にする機能\n /// trueなら有効にする\n internal void SetGlEnable(int index, bool enabled)\n {\n if ( enabled )\n {\n gl.Enable(index);\n }\n else\n {\n gl.Disable(index);\n }\n }\n\n /// \n /// OpenGLES2のVertex Attribute Array機能の有効・無効をセットする\n /// \n /// 有効・無効にする機能\n /// trueなら有効にする\n internal void SetGlEnableVertexAttribArray(int index, bool enabled)\n {\n if ( enabled )\n {\n gl.EnableVertexAttribArray(index);\n }\n else\n {\n gl.DisableVertexAttribArray(index);\n }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/Num2Words.cs", "using System.Globalization;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\npublic static class Num2Words\n{\n private static readonly string[] _units = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" };\n\n private static readonly string[] _tens = { \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" };\n\n private static readonly string[] _ordinalUnits = { \"zeroth\", \"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\", \"seventh\", \"eighth\", \"ninth\", \"tenth\", \"eleventh\", \"twelfth\", \"thirteenth\", \"fourteenth\", \"fifteenth\", \"sixteenth\", \"seventeenth\", \"eighteenth\", \"nineteenth\" };\n\n private static readonly string[] _ordinalTens = { \"\", \"\", \"twentieth\", \"thirtieth\", \"fortieth\", \"fiftieth\", \"sixtieth\", \"seventieth\", \"eightieth\", \"ninetieth\" };\n\n public static string Convert(int number, string to = \"cardinal\")\n {\n if ( number == 0 )\n {\n return _units[0];\n }\n\n if ( number < 0 )\n {\n return \"negative \" + Convert(-number, to);\n }\n\n return to.ToLower() switch {\n \"ordinal\" => ConvertToOrdinal(number),\n \"year\" => ConvertToYear(number),\n _ => ConvertToCardinal(number)\n };\n }\n\n public static string Convert(double number)\n {\n // Handle integer part\n var intPart = (int)Math.Floor(number);\n var result = ConvertToCardinal(intPart);\n\n // Handle decimal part\n var decimalPart = number - intPart;\n if ( decimalPart > 0 )\n {\n // Get decimal digits as string and remove trailing zeros\n var decimalString = decimalPart.ToString(\"F20\", CultureInfo.InvariantCulture)\n .TrimStart('0', '.')\n .TrimEnd('0');\n\n if ( !string.IsNullOrEmpty(decimalString) )\n {\n result += \" point\";\n foreach ( var digit in decimalString )\n {\n result += \" \" + _units[int.Parse(digit.ToString())];\n }\n }\n }\n\n return result;\n }\n\n private static string ConvertToCardinal(int number)\n {\n if ( number < 20 )\n {\n return _units[number];\n }\n\n if ( number < 100 )\n {\n return _tens[number / 10] + (number % 10 > 0 ? \"-\" + _units[number % 10] : \"\");\n }\n\n if ( number < 1000 )\n {\n return _units[number / 100] + \" hundred\" + (number % 100 > 0 ? \" and \" + ConvertToCardinal(number % 100) : \"\");\n }\n\n if ( number < 1000000 )\n {\n var thousands = number / 1000;\n var remainder = number % 1000;\n\n var result = ConvertToCardinal(thousands) + \" thousand\";\n\n if ( remainder > 0 )\n {\n // If remainder is less than 100, or if it has a tens/units part\n if ( remainder < 100 )\n {\n result += \" and \" + ConvertToCardinal(remainder);\n }\n else\n {\n // For numbers like 1,234 -> \"one thousand two hundred and thirty-four\"\n var hundreds = remainder / 100;\n var tensAndUnits = remainder % 100;\n\n result += \" \" + _units[hundreds] + \" hundred\";\n if ( tensAndUnits > 0 )\n {\n result += \" and \" + ConvertToCardinal(tensAndUnits);\n }\n }\n }\n\n return result;\n }\n\n if ( number < 1000000000 )\n {\n return ConvertToCardinal(number / 1000000) + \" million\" + (number % 1000000 > 0 ? (number % 1000000 < 100 ? \" and \" : \" \") + ConvertToCardinal(number % 1000000) : \"\");\n }\n\n return ConvertToCardinal(number / 1000000000) + \" billion\" + (number % 1000000000 > 0 ? (number % 1000000000 < 100 ? \" and \" : \" \") + ConvertToCardinal(number % 1000000000) : \"\");\n }\n\n private static string ConvertToOrdinal(int number)\n {\n if ( number < 20 )\n {\n return _ordinalUnits[number];\n }\n\n if ( number < 100 )\n {\n if ( number % 10 == 0 )\n {\n return _ordinalTens[number / 10];\n }\n\n return _tens[number / 10] + \"-\" + _ordinalUnits[number % 10];\n }\n\n var cardinal = ConvertToCardinal(number);\n\n // Replace the last word with its ordinal form\n var lastSpace = cardinal.LastIndexOf(' ');\n if ( lastSpace == -1 )\n {\n // Single word\n var lastWord = cardinal;\n if ( lastWord.EndsWith(\"y\") )\n {\n return lastWord.Substring(0, lastWord.Length - 1) + \"ieth\";\n }\n\n if ( lastWord.EndsWith(\"eight\") )\n {\n return lastWord + \"h\";\n }\n\n if ( lastWord.EndsWith(\"nine\") )\n {\n return lastWord + \"th\";\n }\n\n return lastWord + \"th\";\n }\n else\n {\n // Multiple words\n var lastWord = cardinal.Substring(lastSpace + 1);\n var prefix = cardinal.Substring(0, lastSpace + 1);\n\n if ( lastWord.EndsWith(\"y\") )\n {\n return prefix + lastWord.Substring(0, lastWord.Length - 1) + \"ieth\";\n }\n\n if ( lastWord == \"one\" )\n {\n return prefix + \"first\";\n }\n\n if ( lastWord == \"two\" )\n {\n return prefix + \"second\";\n }\n\n if ( lastWord == \"three\" )\n {\n return prefix + \"third\";\n }\n\n if ( lastWord == \"five\" )\n {\n return prefix + \"fifth\";\n }\n\n if ( lastWord == \"eight\" )\n {\n return prefix + \"eighth\";\n }\n\n if ( lastWord == \"nine\" || lastWord == \"twelve\" )\n {\n return prefix + lastWord + \"th\";\n }\n\n return prefix + lastWord + \"th\";\n }\n }\n\n private static string ConvertToYear(int year)\n {\n // Handle years specially\n if ( year >= 2000 )\n {\n // 2xxx is \"two thousand [and] xxx\"\n var remainder = year - 2000;\n if ( remainder == 0 )\n {\n return \"two thousand\";\n }\n\n if ( remainder < 100 )\n {\n return \"two thousand and \" + ConvertToCardinal(remainder);\n }\n\n return \"two thousand \" + ConvertToCardinal(remainder);\n }\n\n if ( year >= 1000 )\n {\n // Years like 1984 are \"nineteen eighty-four\"\n var century = year / 100;\n var remainder = year % 100;\n\n if ( remainder == 0 )\n {\n return ConvertToCardinal(century) + \" hundred\";\n }\n\n return ConvertToCardinal(century) + \" \" + ConvertToCardinal(remainder);\n }\n\n // Years less than 1000\n return ConvertToCardinal(year);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/UiStyler.cs", "using System.Numerics;\n\nusing Hexa.NET.ImGui;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\n/// \n/// Static utility class for common UI styling operations\n/// \npublic static class UiStyler\n{\n /// \n /// Executes an action with a temporary style color change\n /// \n public static void WithStyleColor(ImGuiCol colorId, Vector4 color, Action action)\n {\n ImGui.PushStyleColor(colorId, color);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleColor();\n }\n }\n\n /// \n /// Executes an action with multiple temporary style color changes\n /// \n public static void WithStyleColors(IReadOnlyList<(ImGuiCol, Vector4)> colors, Action action)\n {\n foreach ( var (colorId, color) in colors )\n {\n ImGui.PushStyleColor(colorId, color);\n }\n\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleColor(colors.Count);\n }\n }\n\n /// \n /// Executes an action with a temporary style variable change\n /// \n public static void WithStyleVar(ImGuiStyleVar styleVar, Vector2 value, Action action)\n {\n ImGui.PushStyleVar(styleVar, value);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleVar();\n }\n }\n\n /// \n /// Executes an action with a temporary style variable change\n /// \n public static void WithStyleVar(ImGuiStyleVar styleVar, float value, Action action)\n {\n ImGui.PushStyleVar(styleVar, value);\n try\n {\n action();\n }\n finally\n {\n ImGui.PopStyleVar();\n }\n }\n\n /// \n /// Displays a help marker with a tooltip\n /// \n public static void HelpMarker(string desc)\n {\n ImGui.TextDisabled(\"(?)\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(desc);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n }\n\n /// \n /// Renders an input text field with optional validation\n /// \n public static bool ValidatedInputText(\n string label,\n ref string value,\n uint bufferSize,\n string? tooltip = null,\n Func? validator = null)\n {\n var changed = ImGui.InputText(label, ref value, bufferSize);\n\n // Show tooltip if provided\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n // Validate if changed and validator provided\n if ( changed && validator != null )\n {\n var isValid = validator(value);\n if ( !isValid )\n {\n ImGui.SameLine();\n ImGui.TextColored(new Vector4(1, 0, 0, 1), \"!\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.TextUnformatted(\"Invalid input\");\n ImGui.EndTooltip();\n }\n }\n }\n\n return changed;\n }\n\n /// \n /// Renders an input integer field with optional validation and constraints\n /// \n public static bool ValidatedInputInt(\n string label,\n ref int value,\n string? tooltip = null,\n Func? validator = null,\n int? min = null,\n int? max = null)\n {\n var changed = ImGui.InputInt(label, ref value);\n\n // Apply min/max constraints\n if ( changed )\n {\n if ( min.HasValue && value < min.Value )\n {\n value = min.Value;\n }\n\n if ( max.HasValue && value > max.Value )\n {\n value = max.Value;\n }\n }\n\n // Show tooltip if provided\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n // Validate if changed and validator provided\n if ( changed && validator != null )\n {\n var isValid = validator(value);\n if ( !isValid )\n {\n ImGui.SameLine();\n ImGui.TextColored(new Vector4(1, 0, 0, 1), \"!\");\n if ( ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.TextUnformatted(\"Invalid input\");\n ImGui.EndTooltip();\n }\n }\n }\n\n return changed;\n }\n\n /// \n /// Renders a float slider with tooltip and optional animation\n /// \n public static bool TooltipSliderFloat(\n string label,\n ref float value,\n float min,\n float max,\n string format = \"%.3f\",\n string? tooltip = null,\n bool animate = false)\n {\n if ( animate )\n {\n // For animated sliders, use a pulsing accent color\n var time = (float)Math.Sin(ImGui.GetTime() * 2.0f) * 0.5f + 0.5f;\n var color = new Vector4(0.1f, 0.4f + time * 0.2f, 0.8f + time * 0.2f, 1.0f);\n ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.3f, 0.3f, 0.3f, 1.0f));\n ImGui.PushStyleColor(ImGuiCol.SliderGrab, color);\n }\n\n var changed = ImGui.SliderFloat(label, ref value, min, max, format);\n\n if ( animate )\n {\n ImGui.PopStyleColor(2);\n }\n\n if ( tooltip != null && ImGui.IsItemHovered(ImGuiHoveredFlags.DelayShort) )\n {\n ImGui.BeginTooltip();\n ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0f);\n ImGui.TextUnformatted(tooltip);\n ImGui.PopTextWrapPos();\n ImGui.EndTooltip();\n }\n\n return changed;\n }\n\n /// \n /// Renders a collapsible section header\n /// \n /// \n /// Renders a collapsible section header\n /// \n public static bool SectionHeader(string label, bool defaultOpen = true)\n {\n // Define the style colors\n var styleColors = new List<(ImGuiCol, Vector4)> { (ImGuiCol.Header, new Vector4(0.15f, 0.45f, 0.8f, 0.8f)), (ImGuiCol.HeaderHovered, new Vector4(0.2f, 0.5f, 0.9f, 0.8f)), (ImGuiCol.HeaderActive, new Vector4(0.25f, 0.55f, 0.95f, 0.8f)) };\n\n var flags = defaultOpen ? ImGuiTreeNodeFlags.DefaultOpen : ImGuiTreeNodeFlags.None;\n flags |= ImGuiTreeNodeFlags.Framed;\n flags |= ImGuiTreeNodeFlags.SpanAvailWidth;\n flags |= ImGuiTreeNodeFlags.AllowOverlap;\n flags |= ImGuiTreeNodeFlags.FramePadding;\n\n // Use the WithStyleColors method properly - pass the actual rendering logic in the action\n var opened = false;\n WithStyleColors(styleColors, () => { WithStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 6), () => { opened = ImGui.CollapsingHeader(label, flags); }); });\n\n return opened;\n }\n\n /// \n /// Renders a button with animation effects\n /// \n public static bool AnimatedButton(string label, Vector2 size, bool isActive = false)\n {\n bool clicked;\n if ( isActive )\n {\n // Pulse animation for active button\n var time = (float)Math.Sin(ImGui.GetTime() * 2.0f) * 0.5f + 0.5f;\n var color = new Vector4(0.1f, 0.5f + time * 0.3f, 0.9f, 0.7f + time * 0.3f);\n ImGui.PushStyleColor(ImGuiCol.Button, color);\n ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(color.X, color.Y, color.Z, 1.0f));\n ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(color.X * 1.1f, color.Y * 1.1f, color.Z * 1.1f, 1.0f));\n clicked = ImGui.Button(label, size);\n ImGui.PopStyleColor(3);\n }\n else\n {\n // Default stylish button\n // ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.8f, 0.6f));\n // ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.2f, 0.5f, 0.9f, 0.7f));\n // ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.25f, 0.55f, 0.95f, 0.8f));\n clicked = ImGui.Button(label, size);\n }\n\n return clicked;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Core/Conversation/Implementations/Adapters/Audio/Output/PortaudioOutputAdapter.cs", "using System.Runtime.InteropServices;\nusing System.Threading.Channels;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.Audio.Player;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Adapters;\nusing PersonaEngine.Lib.Core.Conversation.Abstractions.Events;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Common;\nusing PersonaEngine.Lib.Core.Conversation.Implementations.Events.Output;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nusing PortAudioSharp;\n\nusing Stream = PortAudioSharp.Stream;\n\nnamespace PersonaEngine.Lib.Core.Conversation.Implementations.Adapters.Audio.Output;\n\npublic class PortaudioOutputAdapter(ILogger logger, IAudioProgressNotifier progressNotifier) : IAudioOutputAdapter\n{\n private const int DefaultSampleRate = 24000;\n\n private const int DefaultFrameBufferSize = 1024;\n\n private readonly float[] _frameBuffer = new float[DefaultFrameBufferSize];\n\n private Stream? _audioStream;\n\n private AudioBuffer? _currentBuffer;\n\n private ChannelReader? _currentReader;\n\n private Guid _currentTurnId;\n\n private long _framesOfChunkPlayed;\n\n private TaskCompletionSource? _playbackCompletion;\n\n private CancellationTokenSource? _playbackCts;\n\n private volatile bool _producerCompleted;\n\n private Channel? _progressChannel;\n\n private Guid _sessionId;\n\n public ValueTask DisposeAsync()\n {\n try\n {\n _audioStream = null;\n }\n catch\n {\n /* ignored */\n }\n\n return ValueTask.CompletedTask;\n }\n\n public Guid AdapterId { get; } = Guid.NewGuid();\n\n public ValueTask InitializeAsync(Guid sessionId, CancellationToken cancellationToken)\n {\n _sessionId = sessionId;\n\n try\n {\n PortAudio.Initialize();\n var deviceIndex = PortAudio.DefaultOutputDevice;\n if ( deviceIndex == PortAudio.NoDevice )\n {\n throw new AudioDeviceNotFoundException(\"No default PortAudio output device found.\");\n }\n\n var deviceInfo = PortAudio.GetDeviceInfo(deviceIndex);\n logger.LogDebug(\"Using PortAudio output device: {DeviceName} (Index: {DeviceIndex})\", deviceInfo.name, deviceIndex);\n\n var parameters = new StreamParameters {\n device = deviceIndex,\n channelCount = 1,\n sampleFormat = SampleFormat.Float32,\n suggestedLatency = deviceInfo.defaultLowOutputLatency,\n hostApiSpecificStreamInfo = IntPtr.Zero\n };\n\n _audioStream = new Stream(\n null,\n parameters,\n DefaultSampleRate,\n DefaultFrameBufferSize,\n StreamFlags.ClipOff,\n AudioCallback,\n IntPtr.Zero);\n }\n catch (Exception ex)\n {\n logger.LogError(ex, \"Failed to initialize PortAudio or create stream.\");\n\n try\n {\n PortAudio.Terminate();\n }\n catch\n {\n // ignored\n }\n\n throw new AudioPlayerInitializationException(\"Failed to initialize PortAudio audio system.\", ex);\n }\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StartAsync(CancellationToken cancellationToken)\n {\n // Don't start it here, SendAsync will handle it.\n\n return ValueTask.CompletedTask;\n }\n\n public ValueTask StopAsync(CancellationToken cancellationToken)\n {\n // Don't stop it here, SendAsync's cleanup or cancellation will handle it.\n // If a hard stop independent of SendAsync is needed, cancellation of SendAsync's token is the way.\n\n return ValueTask.CompletedTask;\n }\n\n public async Task SendAsync(ChannelReader inputReader, ChannelWriter outputWriter, Guid turnId, CancellationToken cancellationToken = default)\n {\n if ( _audioStream == null )\n {\n throw new InvalidOperationException(\"Audio stream is not initialized.\");\n }\n\n _currentTurnId = turnId;\n _currentReader = inputReader;\n\n _progressChannel = Channel.CreateBounded(new BoundedChannelOptions(10) { SingleReader = true, SingleWriter = true });\n\n _playbackCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _playbackCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);\n\n var completedReason = CompletionReason.Completed;\n var firstChunk = true;\n var localPlaybackCts = _playbackCts;\n var localCompletion = _playbackCompletion;\n using var eventLoopCts = new CancellationTokenSource();\n var progressPumpTask = ProgressEventsLoop(eventLoopCts.Token);\n\n try\n {\n _audioStream.Start();\n\n while ( await inputReader.WaitToReadAsync(localPlaybackCts.Token).ConfigureAwait(false) )\n {\n if ( !firstChunk )\n {\n continue;\n }\n\n var firstChunkEvent = new AudioPlaybackStartedEvent(_sessionId, turnId, DateTimeOffset.UtcNow);\n await outputWriter.WriteAsync(firstChunkEvent, localPlaybackCts.Token).ConfigureAwait(false);\n\n firstChunk = false;\n }\n\n _producerCompleted = true;\n\n await localCompletion.Task.ConfigureAwait(false);\n await progressPumpTask.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n completedReason = CompletionReason.Cancelled;\n\n eventLoopCts.CancelAfter(250);\n\n await localCompletion.Task.ConfigureAwait(false);\n await progressPumpTask.ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n completedReason = CompletionReason.Error;\n\n await outputWriter.WriteAsync(new ErrorOutputEvent(_sessionId, turnId, DateTimeOffset.UtcNow, ex), CancellationToken.None).ConfigureAwait(false);\n }\n finally\n {\n CleanupPlayback();\n\n if ( !firstChunk )\n {\n await outputWriter.WriteAsync(new AudioPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, completedReason), CancellationToken.None).ConfigureAwait(false);\n }\n }\n }\n\n private async ValueTask ProgressEventsLoop(CancellationToken ct = default)\n {\n var eventsReader = _progressChannel!.Reader;\n\n await foreach ( var progressEvent in eventsReader.ReadAllAsync(ct).ConfigureAwait(false) )\n {\n if ( ct.IsCancellationRequested )\n {\n break;\n }\n\n switch ( progressEvent )\n {\n case AudioChunkPlaybackStartedEvent startedArgs:\n progressNotifier.RaiseChunkStarted(this, startedArgs);\n\n break;\n case AudioChunkPlaybackEndedEvent endedArgs:\n progressNotifier.RaiseChunkEnded(this, endedArgs);\n\n break;\n case AudioPlaybackProgressEvent progressArgs:\n progressNotifier.RaiseProgress(this, progressArgs);\n\n break;\n }\n }\n }\n\n private void CleanupPlayback()\n {\n _audioStream?.Stop();\n\n _currentTurnId = Guid.Empty;\n _currentReader = null;\n\n _progressChannel?.Writer.TryComplete();\n _producerCompleted = false;\n _framesOfChunkPlayed = 0;\n _currentBuffer = null;\n\n _playbackCts?.Cancel();\n _playbackCts?.Dispose();\n _playbackCts = null;\n\n Array.Clear(_frameBuffer, 0, DefaultFrameBufferSize);\n }\n\n private StreamCallbackResult AudioCallback(IntPtr input, IntPtr output, uint framecount, ref StreamCallbackTimeInfo timeinfo, StreamCallbackFlags statusflags, IntPtr userdataptr)\n {\n var framesRequested = (int)framecount;\n var framesWritten = 0;\n\n var turnId = _currentTurnId;\n var reader = _currentReader;\n var completionSource = _playbackCompletion;\n var currentPlaybackCts = _playbackCts;\n var ct = currentPlaybackCts?.Token ?? CancellationToken.None;\n var progressWriter = _progressChannel!.Writer;\n\n if ( reader == null )\n {\n completionSource?.TrySetResult(false);\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n while ( framesWritten < framesRequested )\n {\n if ( ct.IsCancellationRequested )\n {\n FillSilence();\n completionSource?.TrySetResult(false);\n\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n if ( _currentBuffer == null )\n {\n if ( reader.TryRead(out var chunk) )\n {\n _currentBuffer = new AudioBuffer(chunk.Chunk.AudioData, chunk.Chunk);\n progressWriter.TryWrite(new AudioChunkPlaybackStartedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, chunk.Chunk));\n }\n else\n {\n if ( _producerCompleted )\n {\n FillSilence();\n completionSource?.TrySetResult(true);\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n FillSilence();\n }\n }\n\n if ( _currentBuffer == null )\n {\n return StreamCallbackResult.Continue;\n }\n\n var framesToCopy = Math.Min(framesRequested - framesWritten, _currentBuffer.Remaining);\n var sourceSpan = _currentBuffer.Data.Span.Slice(_currentBuffer.Position, framesToCopy);\n var destinationSpan = _frameBuffer.AsSpan(framesWritten, framesToCopy);\n sourceSpan.CopyTo(destinationSpan);\n _currentBuffer.Advance(framesToCopy);\n framesWritten += framesToCopy;\n\n if ( _currentBuffer.IsFinished )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n _framesOfChunkPlayed = 0;\n _currentBuffer = null;\n }\n }\n\n Marshal.Copy(_frameBuffer, 0, output, framesRequested);\n\n _framesOfChunkPlayed += framesRequested;\n var currentTime = TimeSpan.FromSeconds((double)_framesOfChunkPlayed / DefaultSampleRate);\n progressWriter.TryWrite(new AudioPlaybackProgressEvent(_sessionId, turnId, DateTimeOffset.UtcNow, currentTime));\n\n if ( _currentBuffer == null && _producerCompleted )\n {\n completionSource?.TrySetResult(true);\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n if ( ct.IsCancellationRequested )\n {\n completionSource?.TrySetResult(false);\n if ( _currentBuffer != null )\n {\n progressWriter.TryWrite(new AudioChunkPlaybackEndedEvent(_sessionId, turnId, DateTimeOffset.UtcNow, _currentBuffer.Segment));\n }\n\n progressWriter.TryComplete();\n\n return StreamCallbackResult.Complete;\n }\n\n return StreamCallbackResult.Continue;\n\n void FillSilence()\n {\n if ( framesWritten < framesRequested )\n {\n Array.Clear(_frameBuffer, framesWritten, framesRequested - framesWritten);\n }\n\n Marshal.Copy(_frameBuffer, 0, output, framesRequested);\n }\n }\n\n private sealed class AudioBuffer(Memory data, AudioSegment segment)\n {\n public Memory Data { get; } = data;\n\n public AudioSegment Segment { get; } = segment;\n\n public int Position { get; private set; } = 0;\n\n public int Remaining => Data.Length - Position;\n\n public bool IsFinished => Position >= Data.Length;\n\n public void Advance(int count) { Position += count; }\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/RVC/RVCFilter.cs", "using System.Buffers;\nusing System.Diagnostics;\n\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\n\nusing PersonaEngine.Lib.Audio;\nusing PersonaEngine.Lib.Configuration;\nusing PersonaEngine.Lib.TTS.Synthesis;\n\nnamespace PersonaEngine.Lib.TTS.RVC;\n\npublic class RVCFilter : IAudioFilter, IDisposable\n{\n private const int ProcessingSampleRate = 16000;\n\n private const int OutputSampleRate = 32000;\n\n private const int FinalSampleRate = 24000;\n\n private const int MaxInputDuration = 30; // seconds\n\n private readonly SemaphoreSlim _initLock = new(1, 1);\n\n private readonly ILogger _logger;\n\n private readonly IModelProvider _modelProvider;\n\n private readonly IDisposable? _optionsChangeRegistration;\n\n private readonly IOptionsMonitor _optionsMonitor;\n\n private readonly IRVCVoiceProvider _rvcVoiceProvider;\n\n private RVCFilterOptions _currentOptions;\n\n private bool _disposed;\n\n private IF0Predictor? _f0Predictor;\n\n private OnnxRVC? _rvcModel;\n\n public RVCFilter(\n IOptionsMonitor optionsMonitor,\n IModelProvider modelProvider,\n IRVCVoiceProvider rvcVoiceProvider,\n ILogger logger)\n {\n _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));\n _modelProvider = modelProvider;\n _rvcVoiceProvider = rvcVoiceProvider;\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n _currentOptions = optionsMonitor.CurrentValue;\n\n _ = InitializeAsync(_currentOptions);\n\n // Register for options changes\n _optionsChangeRegistration = _optionsMonitor.OnChange(OnOptionsChanged);\n }\n\n public void Process(AudioSegment audioSegment)\n {\n if ( _disposed )\n {\n throw new ObjectDisposedException(nameof(RVCFilter));\n }\n\n if ( _rvcModel == null || _f0Predictor == null ||\n audioSegment?.AudioData == null || audioSegment.AudioData.Length == 0 )\n {\n return;\n }\n\n // Get the latest options for processing\n var options = _currentOptions;\n var originalSampleRate = audioSegment.SampleRate;\n\n if ( !options.Enabled )\n {\n return;\n }\n\n // Start timing\n var stopwatch = Stopwatch.StartNew();\n\n // Step 1: Resample input to processing sample rate\n var resampleRatioToProcessing = (int)Math.Ceiling((double)ProcessingSampleRate / originalSampleRate);\n var resampledInputSize = audioSegment.AudioData.Length * resampleRatioToProcessing;\n\n var resampledInput = ArrayPool.Shared.Rent(resampledInputSize);\n try\n {\n var inputSampleCount = AudioConverter.ResampleFloat(\n audioSegment.AudioData,\n resampledInput,\n 1,\n (uint)originalSampleRate,\n ProcessingSampleRate);\n\n // Step 2: Process with RVC model\n var maxInputSamples = OutputSampleRate * MaxInputDuration;\n var outputBufferSize = maxInputSamples + 2 * options.HopSize;\n\n var processingBuffer = ArrayPool.Shared.Rent(outputBufferSize);\n try\n {\n var processedSampleCount = _rvcModel.ProcessAudio(\n resampledInput.AsMemory(0, inputSampleCount),\n processingBuffer,\n _f0Predictor,\n options.SpeakerId,\n options.F0UpKey);\n\n // Step 3: Resample to original sample rate\n var resampleRatioToOutput = (int)Math.Ceiling((double)originalSampleRate / OutputSampleRate);\n var finalOutputSize = processedSampleCount * resampleRatioToOutput;\n\n var resampledOutput = ArrayPool.Shared.Rent(finalOutputSize);\n try\n {\n var finalSampleCount = AudioConverter.ResampleFloat(\n processingBuffer.AsMemory(0, processedSampleCount),\n resampledOutput,\n 1,\n OutputSampleRate,\n (uint)originalSampleRate);\n\n // Need one allocation for the final output buffer since AudioSegment keeps this reference\n var finalBuffer = new float[finalSampleCount];\n Array.Copy(resampledOutput, finalBuffer, finalSampleCount);\n\n audioSegment.AudioData = finalBuffer.AsMemory();\n audioSegment.SampleRate = FinalSampleRate;\n }\n finally\n {\n ArrayPool.Shared.Return(resampledOutput);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(processingBuffer);\n }\n }\n finally\n {\n ArrayPool.Shared.Return(resampledInput);\n }\n\n // Stop timing after processing is complete\n stopwatch.Stop();\n var processingTime = stopwatch.Elapsed.TotalSeconds;\n\n // Calculate final audio duration (based on the processed audio)\n var finalAudioDuration = audioSegment.AudioData.Length / (double)FinalSampleRate;\n\n // Calculate real-time factor\n var realTimeFactor = finalAudioDuration / processingTime;\n\n // Log the results using ILogger\n _logger.LogInformation(\"Generated {AudioDuration:F2}s audio in {ProcessingTime:F2}s (x{RealTimeFactor:F2} real-time)\",\n finalAudioDuration, processingTime, realTimeFactor);\n }\n\n public int Priority => 100;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( disposing )\n {\n _optionsChangeRegistration?.Dispose();\n DisposeResources();\n }\n\n _disposed = true;\n }\n\n private async void OnOptionsChanged(RVCFilterOptions newOptions)\n {\n if ( _disposed )\n {\n return;\n }\n\n if ( ShouldReinitialize(newOptions) )\n {\n DisposeResources();\n await InitializeAsync(newOptions);\n }\n\n _currentOptions = newOptions;\n }\n\n private bool ShouldReinitialize(RVCFilterOptions newOptions)\n {\n return _currentOptions.DefaultVoice != newOptions.DefaultVoice ||\n _currentOptions.HopSize != newOptions.HopSize;\n }\n\n private async ValueTask InitializeAsync(RVCFilterOptions options)\n {\n await _initLock.WaitAsync();\n try\n {\n var crepeModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCCrepeTiny);\n var hubertModel = await _modelProvider.GetModelAsync(Synthesis.ModelType.RVCHubert);\n var rvcModel = await _rvcVoiceProvider.GetVoiceAsync(options.DefaultVoice);\n\n // _f0Predictor = new CrepeOnnx(crepeModel.Path);\n _f0Predictor = new CrepeOnnxSimd(crepeModel.Path);\n // _f0Predictor = new ACFMethod(512, 16000);\n\n _rvcModel = new OnnxRVC(\n rvcModel,\n options.HopSize,\n hubertModel.Path);\n }\n finally\n {\n _initLock.Release();\n }\n }\n\n private void DisposeResources()\n {\n _rvcModel?.Dispose();\n _rvcModel = null;\n\n _f0Predictor?.Dispose();\n _f0Predictor = null;\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/ASR/Transcriber/RealtimeTranscriptor.cs", "using System.Diagnostics;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\n\nusing Microsoft.Extensions.Logging;\n\nusing PersonaEngine.Lib.ASR.VAD;\nusing PersonaEngine.Lib.Audio;\n\nnamespace PersonaEngine.Lib.ASR.Transcriber;\n\ninternal class RealtimeTranscriptor : IRealtimeSpeechTranscriptor, IAsyncDisposable\n{\n private readonly object cacheLock = new();\n\n private readonly ILogger logger;\n\n private readonly RealtimeSpeechTranscriptorOptions options;\n\n private readonly RealtimeOptions realtimeOptions;\n\n private readonly ISpeechTranscriptorFactory? recognizingSpeechTranscriptorFactory;\n\n private readonly ISpeechTranscriptorFactory speechTranscriptorFactory;\n\n private readonly Dictionary transcriptorCache;\n\n private readonly IVadDetector vadDetector;\n\n private TimeSpan _lastDuration = TimeSpan.Zero;\n\n private TimeSpan _processedDuration = TimeSpan.Zero;\n\n private bool isDisposed;\n\n public RealtimeTranscriptor(\n ISpeechTranscriptorFactory speechTranscriptorFactory,\n IVadDetector vadDetector,\n ISpeechTranscriptorFactory? recognizingSpeechTranscriptorFactory,\n RealtimeSpeechTranscriptorOptions options,\n RealtimeOptions realtimeOptions,\n ILogger logger)\n {\n this.speechTranscriptorFactory = speechTranscriptorFactory;\n this.vadDetector = vadDetector;\n this.recognizingSpeechTranscriptorFactory = recognizingSpeechTranscriptorFactory;\n this.options = options;\n this.realtimeOptions = realtimeOptions;\n this.logger = logger;\n transcriptorCache = new Dictionary();\n\n logger.LogDebug(\"RealtimeTranscriptor initialized with options: {@Options}, realtime options: {@RealtimeOptions}\",\n options, realtimeOptions);\n }\n\n public async ValueTask DisposeAsync()\n {\n if ( isDisposed )\n {\n return;\n }\n\n // lock (cacheLock)\n // {\n logger.LogInformation(\"Disposing {Count} cached transcriptors\", transcriptorCache.Count);\n foreach ( var transcriptor in transcriptorCache.Values )\n {\n await transcriptor.DisposeAsync();\n }\n\n transcriptorCache.Clear();\n // }\n\n isDisposed = true;\n GC.SuppressFinalize(this);\n }\n\n public async IAsyncEnumerable TranscribeAsync(\n IAwaitableAudioSource source,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n if ( isDisposed )\n {\n throw new ObjectDisposedException(nameof(RealtimeTranscriptor));\n }\n\n var stopwatch = Stopwatch.StartNew();\n var promptBuilder = new StringBuilder(options.Prompt);\n CultureInfo? detectedLanguage = null;\n\n await source.WaitForInitializationAsync(cancellationToken);\n var sessionId = Guid.NewGuid().ToString();\n\n logger.LogInformation(\"Starting transcription session {SessionId}\", sessionId);\n\n yield return new RealtimeSessionStarted(sessionId);\n\n try\n {\n while ( !source.IsFlushed )\n {\n var currentDuration = source.Duration;\n\n if ( currentDuration == _lastDuration )\n {\n await source.WaitForNewSamplesAsync(_lastDuration + realtimeOptions.ProcessingInterval, cancellationToken);\n\n continue;\n }\n\n logger.LogTrace(\"Processing new audio segment: Current={Current}ms, Last={Last}ms, Delta={Delta}ms\",\n currentDuration.TotalMilliseconds,\n _lastDuration.TotalMilliseconds,\n (currentDuration - _lastDuration).TotalMilliseconds);\n\n _lastDuration = currentDuration;\n var segmentStopwatch = Stopwatch.StartNew();\n var slicedSource = new SliceAudioSource(source, _processedDuration, currentDuration - _processedDuration);\n\n VadSegment? lastNonFinalSegment = null;\n VadSegment? recognizingSegment = null;\n\n await foreach ( var segment in vadDetector.DetectSegmentsAsync(slicedSource, cancellationToken) )\n {\n if ( segment.IsIncomplete )\n {\n recognizingSegment = segment;\n\n continue;\n }\n\n var segmentEnd = segment.StartTime + segment.Duration;\n lastNonFinalSegment = segment;\n\n logger.LogDebug(\"Processing VAD segment: Start={Start}ms, Duration={Duration}ms\",\n segment.StartTime.TotalMilliseconds,\n segment.Duration.TotalMilliseconds);\n\n var transcribeStopwatch = Stopwatch.StartNew();\n var transcribingEvents = TranscribeSegments(\n speechTranscriptorFactory,\n source,\n _processedDuration,\n segment.StartTime,\n segment.Duration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segmentData in transcribingEvents )\n {\n if ( options.AutodetectLanguageOnce )\n {\n detectedLanguage = segmentData.Language;\n }\n\n if ( realtimeOptions.ConcatenateSegmentsToPrompt )\n {\n promptBuilder.Append(segmentData.Text);\n }\n\n logger.LogDebug(\n \"Segment recognized: SessionId={SessionId}, Duration={Duration}ms, ProcessingTime={ProcessingTime}ms\",\n sessionId,\n segmentData.Duration.TotalMilliseconds,\n transcribeStopwatch.ElapsedMilliseconds);\n\n yield return new RealtimeSegmentRecognized(segmentData, sessionId);\n }\n }\n\n if ( options.IncludeSpeechRecogizingEvents && recognizingSegment != null )\n {\n logger.LogDebug(\"Processing recognizing segment: Duration={Duration}ms\",\n recognizingSegment.Duration.TotalMilliseconds);\n\n var transcribingEvents = TranscribeSegments(\n recognizingSpeechTranscriptorFactory ?? speechTranscriptorFactory,\n source,\n _processedDuration,\n recognizingSegment.StartTime,\n recognizingSegment.Duration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segment in transcribingEvents )\n {\n yield return new RealtimeSegmentRecognizing(segment, sessionId);\n }\n }\n\n HandleSegmentProcessing(source, ref _processedDuration, lastNonFinalSegment, recognizingSegment, _lastDuration);\n\n logger.LogTrace(\"Segment processing completed in {ElapsedTime}ms\",\n segmentStopwatch.ElapsedMilliseconds);\n }\n\n var finalStopwatch = Stopwatch.StartNew();\n var lastEvents = TranscribeSegments(\n speechTranscriptorFactory,\n source,\n _processedDuration,\n TimeSpan.Zero,\n source.Duration - _processedDuration,\n promptBuilder,\n detectedLanguage,\n sessionId,\n cancellationToken);\n\n await foreach ( var segmentData in lastEvents )\n {\n if ( realtimeOptions.ConcatenateSegmentsToPrompt )\n {\n promptBuilder.Append(segmentData.Text);\n }\n\n yield return new RealtimeSegmentRecognized(segmentData, sessionId);\n }\n\n logger.LogInformation(\n \"Transcription session completed: SessionId={SessionId}, TotalDuration={TotalDuration}ms, TotalProcessingTime={TotalTime}ms\",\n sessionId,\n source.Duration.TotalMilliseconds,\n stopwatch.ElapsedMilliseconds);\n\n yield return new RealtimeSessionStopped(sessionId);\n }\n finally\n {\n await CleanupSessionAsync(sessionId);\n }\n }\n\n private void HandleSegmentProcessing(\n IAudioSource source,\n ref TimeSpan processedDuration,\n VadSegment? lastNonFinalSegment,\n VadSegment? recognizingSegment,\n TimeSpan lastDuration)\n {\n if ( lastNonFinalSegment != null )\n {\n var skippingDuration = lastNonFinalSegment.StartTime + lastNonFinalSegment.Duration;\n processedDuration += skippingDuration;\n\n if ( source is IDiscardableAudioSource discardableSource )\n {\n var lastSegmentEndFrameIndex = (int)(skippingDuration.TotalMilliseconds * source.SampleRate / 1000d) - 1;\n discardableSource.DiscardFrames(lastSegmentEndFrameIndex);\n logger.LogTrace(\"Discarded frames up to index {FrameIndex}\", lastSegmentEndFrameIndex);\n }\n }\n else if ( recognizingSegment == null )\n {\n if ( lastDuration - processedDuration > realtimeOptions.SilenceDiscardInterval )\n {\n var silenceDurationToDiscard = TimeSpan.FromTicks(realtimeOptions.SilenceDiscardInterval.Ticks / 2);\n processedDuration += silenceDurationToDiscard;\n\n if ( source is IDiscardableAudioSource discardableSource )\n {\n var halfSilenceIndex = (int)(silenceDurationToDiscard.TotalMilliseconds * source.SampleRate / 1000d) - 1;\n discardableSource.DiscardFrames(halfSilenceIndex);\n logger.LogTrace(\"Discarded silence frames up to index {FrameIndex}\", halfSilenceIndex);\n }\n }\n }\n }\n\n private async IAsyncEnumerable TranscribeSegments(\n ISpeechTranscriptorFactory transcriptorFactory,\n IAudioSource source,\n TimeSpan processedDuration,\n TimeSpan startTime,\n TimeSpan duration,\n StringBuilder promptBuilder,\n CultureInfo? detectedLanguage,\n string sessionId,\n [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n if ( duration < realtimeOptions.MinTranscriptDuration )\n {\n yield break;\n }\n\n startTime += processedDuration;\n var paddedStart = startTime - realtimeOptions.PaddingDuration;\n\n if ( paddedStart < processedDuration )\n {\n paddedStart = processedDuration;\n }\n\n var paddedDuration = duration + realtimeOptions.PaddingDuration;\n\n using IAudioSource paddedSource = paddedDuration < realtimeOptions.MinDurationWithPadding\n ? GetSilenceAddedSource(source, paddedStart, paddedDuration)\n : new SliceAudioSource(source, paddedStart, paddedDuration);\n\n var languageAutodetect = options.LanguageAutoDetect;\n var language = options.Language;\n\n if ( languageAutodetect && options.AutodetectLanguageOnce && detectedLanguage != null )\n {\n languageAutodetect = false;\n language = detectedLanguage;\n }\n\n var currentOptions = options with { Prompt = realtimeOptions.ConcatenateSegmentsToPrompt ? promptBuilder.ToString() : options.Prompt, LanguageAutoDetect = languageAutodetect, Language = language };\n\n var transcriptor = GetOrCreateTranscriptor(transcriptorFactory, currentOptions, sessionId);\n\n await foreach ( var segment in transcriptor.TranscribeAsync(paddedSource, cancellationToken) )\n {\n segment.StartTime += processedDuration;\n\n yield return segment;\n }\n }\n\n private ISpeechTranscriptor GetOrCreateTranscriptor(\n ISpeechTranscriptorFactory factory,\n RealtimeSpeechTranscriptorOptions currentOptions,\n string sessionId)\n {\n var cacheKey = $\"{sessionId}_{factory.GetHashCode()}\";\n\n lock (cacheLock)\n {\n if ( !transcriptorCache.TryGetValue(cacheKey, out var transcriptor) )\n {\n transcriptor = factory.Create(currentOptions);\n transcriptorCache.Add(cacheKey, transcriptor);\n }\n\n return transcriptor;\n }\n }\n\n private async ValueTask CleanupSessionAsync(string sessionId)\n {\n // lock (cacheLock)\n // {\n var keysToRemove = transcriptorCache.Keys\n .Where(k => k.StartsWith($\"{sessionId}_\"))\n .ToList();\n\n foreach ( var key in keysToRemove )\n {\n if ( !transcriptorCache.TryGetValue(key, out var transcriptor) )\n {\n continue;\n }\n\n await transcriptor.DisposeAsync();\n transcriptorCache.Remove(key);\n }\n // }\n }\n\n private ConcatAudioSource GetSilenceAddedSource(IAudioSource source, TimeSpan paddedStart, TimeSpan paddedDuration)\n {\n var silenceDuration = new TimeSpan((realtimeOptions.MinDurationWithPadding.Ticks - paddedDuration.Ticks) / 2);\n var preSilence = new SilenceAudioSource(silenceDuration, source.SampleRate, source.Metadata, source.ChannelCount, source.BitsPerSample);\n var postSilence = new SilenceAudioSource(silenceDuration, source.SampleRate, source.Metadata, source.ChannelCount, source.BitsPerSample);\n\n return new ConcatAudioSource([preSilence, new SliceAudioSource(source, paddedStart, paddedDuration), postSilence], source.Metadata);\n }\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/TTS/Synthesis/OpenNlpPosTagger.cs", "using System.Text.RegularExpressions;\n\nusing Microsoft.Extensions.Logging;\n\nusing OpenNLP.Tools.PosTagger;\nusing OpenNLP.Tools.Tokenize;\n\nnamespace PersonaEngine.Lib.TTS.Synthesis;\n\n/// \n/// Implementation of OpenNLP-based POS tagger with spaCy-like currency handling\n/// \npublic partial class OpenNlpPosTagger : IPosTagger\n{\n private readonly Regex _currencySymbolRegex = CurrencyRegex();\n\n private readonly ILogger _logger;\n\n private readonly EnglishMaximumEntropyPosTagger _posTagger;\n\n private readonly EnglishRuleBasedTokenizer _tokenizer;\n\n private bool _disposed;\n\n public OpenNlpPosTagger(string modelPath, ILogger logger)\n {\n if ( string.IsNullOrEmpty(modelPath) )\n {\n throw new ArgumentException(\"Model path cannot be null or empty\", nameof(modelPath));\n }\n\n _logger = logger ?? throw new ArgumentNullException(nameof(logger));\n\n try\n {\n _tokenizer = new EnglishRuleBasedTokenizer(false);\n _posTagger = new EnglishMaximumEntropyPosTagger(modelPath);\n _logger.LogInformation(\"Initialized OpenNLP POS tagger from {ModelPath}\", modelPath);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to initialize OpenNLP POS tagger\");\n\n throw;\n }\n }\n\n /// \n /// Tags parts of speech in text using OpenNLP with spaCy-like currency handling\n /// \n public Task> TagAsync(string text, CancellationToken cancellationToken = default)\n {\n if ( string.IsNullOrEmpty(text) )\n {\n return Task.FromResult>(Array.Empty());\n }\n\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Pre-process text to insert spaces between currency symbols and digits\n // This makes the tokenizer split currency symbols from amounts, similar to spaCy\n var currencyRegex = CurrencyWithNumRegex();\n var processedText = currencyRegex.Replace(text, \"$1 $2\");\n\n // Tokenize pre-processed text\n var tokens = _tokenizer.Tokenize(processedText);\n\n // Get POS tags\n var tags = _posTagger.Tag(tokens);\n\n // Post-process to assign \"$\" tag to currency symbols\n for ( var i = 0; i < tokens.Length; i++ )\n {\n if ( _currencySymbolRegex.IsMatch(tokens[i]) )\n {\n tags[i] = \"$\"; // Assign \"$\" tag to currency symbols (spaCy-like behavior)\n }\n }\n\n // Build result tokens with whitespace\n var result = new List();\n var currentPosition = 0;\n\n for ( var i = 0; i < tokens.Length; i++ )\n {\n var token = tokens[i];\n var tag = tags[i];\n\n // Find token position in processed text\n var tokenPosition = processedText.IndexOf(token, currentPosition, StringComparison.Ordinal);\n\n // Extract whitespace between tokens\n var whitespace = \"\";\n if ( i < tokens.Length - 1 )\n {\n var nextTokenStart = processedText.IndexOf(tokens[i + 1], tokenPosition + token.Length, StringComparison.Ordinal);\n if ( nextTokenStart >= 0 )\n {\n whitespace = processedText.Substring(\n tokenPosition + token.Length,\n nextTokenStart - (tokenPosition + token.Length));\n }\n }\n else\n {\n // Last token - get any remaining whitespace\n whitespace = tokenPosition + token.Length < processedText.Length\n ? processedText[(tokenPosition + token.Length)..]\n : \"\";\n }\n\n result.Add(new PosToken { Text = token, PartOfSpeech = tag, IsWhitespace = whitespace.Contains(\" \") });\n\n currentPosition = tokenPosition + token.Length;\n }\n\n return Task.FromResult>(result);\n }\n catch (OperationCanceledException)\n {\n _logger.LogInformation(\"POS tagging was canceled\");\n\n throw;\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Error during POS tagging\");\n\n throw;\n }\n }\n\n public void Dispose()\n {\n if ( _disposed )\n {\n return;\n }\n\n _disposed = true;\n }\n\n [GeneratedRegex(@\"([\\$\\€\\£\\¥\\₹])(\\d)\")]\n private static partial Regex CurrencyWithNumRegex();\n\n [GeneratedRegex(@\"^[\\$\\€\\£\\¥\\₹]$\")] private static partial Regex CurrencyRegex();\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/Live2D/Framework/Physics/CubismPhysicsInternal.cs", "using System.Numerics;\n\nnamespace PersonaEngine.Lib.Live2D.Framework.Physics;\n\n/// \n/// 物理演算の適用先の種類。\n/// \npublic enum CubismPhysicsTargetType\n{\n /// \n /// パラメータに対して適用\n /// \n CubismPhysicsTargetType_Parameter\n}\n\n/// \n/// 物理演算の入力の種類。\n/// \npublic enum CubismPhysicsSource\n{\n /// \n /// X軸の位置から\n /// \n CubismPhysicsSource_X,\n\n /// \n /// Y軸の位置から\n /// \n CubismPhysicsSource_Y,\n\n /// \n /// 角度から\n /// \n CubismPhysicsSource_Angle\n}\n\n/// \n/// 物理演算で使用する外部の力。\n/// \npublic record PhysicsJsonEffectiveForces\n{\n /// \n /// 重力\n /// \n public Vector2 Gravity;\n\n /// \n /// 風\n /// \n public Vector2 Wind;\n}\n\n/// \n/// 物理演算のパラメータ情報。\n/// \npublic record CubismPhysicsParameter\n{\n /// \n /// パラメータID\n /// \n public required string Id;\n\n /// \n /// 適用先の種類\n /// \n public CubismPhysicsTargetType TargetType;\n}\n\n/// \n/// 物理演算の正規化情報。\n/// \npublic record CubismPhysicsNormalization\n{\n /// \n /// デフォルト値\n /// \n public float Default;\n\n /// \n /// 最小値\n /// \n public float Maximum;\n\n /// \n /// 最大値\n /// \n public float Minimum;\n}\n\n/// \n/// 物理演算の演算に使用する物理点の情報。\n/// \npublic record CubismPhysicsParticle\n{\n /// \n /// 加速度\n /// \n public float Acceleration;\n\n /// \n /// 遅れ\n /// \n public float Delay;\n\n /// \n /// 現在かかっている力\n /// \n public Vector2 Force;\n\n /// \n /// 初期位置\n /// \n public Vector2 InitialPosition;\n\n /// \n /// 最後の重力\n /// \n public Vector2 LastGravity;\n\n /// \n /// 最後の位置\n /// \n public Vector2 LastPosition;\n\n /// \n /// 動きやすさ\n /// \n public float Mobility;\n\n /// \n /// 現在の位置\n /// \n public Vector2 Position;\n\n /// \n /// 距離\n /// \n public float Radius;\n\n /// \n /// 現在の速度\n /// \n public Vector2 Velocity;\n}\n\n/// \n/// 物理演算の物理点の管理。\n/// \npublic record CubismPhysicsSubRig\n{\n /// \n /// 入力の最初のインデックス\n /// \n public int BaseInputIndex;\n\n /// \n /// 出力の最初のインデックス\n /// \n public int BaseOutputIndex;\n\n /// \n /// /物理点の最初のインデックス\n /// \n public int BaseParticleIndex;\n\n /// \n /// 入力の個数\n /// \n public int InputCount;\n\n /// \n /// 正規化された角度\n /// \n public required CubismPhysicsNormalization NormalizationAngle;\n\n /// \n /// 正規化された位置\n /// \n public required CubismPhysicsNormalization NormalizationPosition;\n\n /// \n /// 出力の個数\n /// \n public int OutputCount;\n\n /// \n /// 物理点の個数\n /// \n public int ParticleCount;\n}\n\n/// \n/// 正規化されたパラメータの取得関数の宣言。\n/// \n/// 演算結果の移動値\n/// 演算結果の角度\n/// パラメータの値\n/// パラメータの最小値\n/// パラメータの最大値\n/// パラメータのデフォルト値\n/// 正規化された位置\n/// 正規化された角度\n/// 値が反転されているか?\n/// 重み\npublic delegate void NormalizedPhysicsParameterValueGetter(\n ref Vector2 targetTranslation,\n ref float targetAngle,\n float value,\n float parameterMinimumValue,\n float parameterMaximumValue,\n float parameterDefaultValue,\n CubismPhysicsNormalization normalizationPosition,\n CubismPhysicsNormalization normalizationAngle,\n bool isInverted,\n float weight\n);\n\n/// \n/// 物理演算の値の取得関数の宣言。\n/// \n/// 移動値\n/// 物理点のリスト\n/// \n/// 値が反転されているか?\n/// 重力\n/// \npublic delegate float PhysicsValueGetter(\n Vector2 translation,\n CubismPhysicsParticle[] particles,\n int currentParticleIndex,\n int particleIndex,\n bool isInverted,\n Vector2 parentGravity\n);\n\n/// \n/// 物理演算のスケールの取得関数の宣言。\n/// \n/// 移動値のスケール\n/// 角度のスケール\n/// スケール値\npublic delegate float PhysicsScaleGetter(Vector2 translationScale, float angleScale);\n\n/// \n/// 物理演算の入力情報。\n/// \npublic record CubismPhysicsInput\n{\n /// \n /// 正規化されたパラメータ値の取得関数\n /// \n public NormalizedPhysicsParameterValueGetter GetNormalizedParameterValue;\n\n /// \n /// 値が反転されているかどうか\n /// \n public bool Reflect;\n\n /// \n /// 入力元のパラメータ\n /// \n public required CubismPhysicsParameter Source;\n\n /// \n /// 入力元のパラメータのインデックス\n /// \n public int SourceParameterIndex;\n\n /// \n /// 入力の種類\n /// \n public CubismPhysicsSource Type;\n\n /// \n /// 重み\n /// \n public float Weight;\n}\n\n/// \n/// 物理演算の出力情報。\n/// \npublic record CubismPhysicsOutput\n{\n /// \n /// 角度のスケール\n /// \n public float AngleScale;\n\n /// \n /// 出力先のパラメータ\n /// \n public required CubismPhysicsParameter Destination;\n\n /// \n /// 出力先のパラメータのインデックス\n /// \n public int DestinationParameterIndex;\n\n /// \n /// 物理演算のスケール値の取得関数\n /// \n public PhysicsScaleGetter GetScale;\n\n /// \n /// 物理演算の値の取得関数\n /// \n public PhysicsValueGetter GetValue;\n\n /// \n /// 値が反転されているかどうか\n /// \n public bool Reflect;\n\n /// \n /// 移動値のスケール\n /// \n public Vector2 TranslationScale;\n\n /// \n /// 出力の種類\n /// \n public CubismPhysicsSource Type;\n\n /// \n /// 最小値を下回った時の値\n /// \n public float ValueBelowMinimum;\n\n /// \n /// 最大値をこえた時の値\n /// \n public float ValueExceededMaximum;\n\n /// \n /// 振り子のインデックス\n /// \n public int VertexIndex;\n\n /// \n /// 重み\n /// \n public float Weight;\n}\n\n/// \n/// 物理演算のデータ。\n/// \npublic record CubismPhysicsRig\n{\n /// \n /// 物理演算動作FPS\n /// \n public float Fps;\n\n /// \n /// 重力\n /// \n public Vector2 Gravity;\n\n /// \n /// 物理演算の入力のリスト\n /// \n public required CubismPhysicsInput[] Inputs;\n\n /// \n /// 物理演算の出力のリスト\n /// \n public required CubismPhysicsOutput[] Outputs;\n\n /// \n /// 物理演算の物理点のリスト\n /// \n public required CubismPhysicsParticle[] Particles;\n\n /// \n /// 物理演算の物理点の管理のリスト\n /// \n public required CubismPhysicsSubRig[] Settings;\n\n /// \n /// 物理演算の物理点の個数\n /// \n public int SubRigCount;\n\n /// \n /// 風\n /// \n public Vector2 Wind;\n}"], ["/handcrafted-persona-engine/src/PersonaEngine/PersonaEngine.Lib/UI/GUI/RouletteWheelEditor.cs", "using System.Diagnostics;\nusing System.Drawing;\nusing System.Numerics;\n\nusing Hexa.NET.ImGui;\nusing Hexa.NET.ImGui.Widgets;\n\nusing PersonaEngine.Lib.Configuration;\n\nnamespace PersonaEngine.Lib.UI.GUI;\n\npublic class RouletteWheelEditor : ConfigSectionEditorBase\n{\n private readonly string[] _anchorOptions = { \"TopLeft\", \"TopCenter\", \"TopRight\", \"MiddleLeft\", \"MiddleCenter\", \"MiddleRight\", \"BottomLeft\", \"BottomCenter\", \"BottomRight\" };\n\n private readonly FontProvider _fontProvider;\n\n private readonly string[] _positionOptions = { \"Center\", \"Custom Position\", \"Anchor Position\" };\n\n private readonly IUiThemeManager _themeManager;\n\n private readonly RouletteWheel.RouletteWheel _wheel;\n\n private bool _animateToggle;\n\n private float _animationDuration;\n\n private List _availableFonts = new();\n\n private RouletteWheelOptions _currentConfig;\n\n private bool _defaultEnabled;\n\n private string _fontName;\n\n private int _fontSize;\n\n private int _height;\n\n private bool _loadingFonts = false;\n\n private float _minRotations;\n\n private string _newSectionLabel = string.Empty;\n\n private bool _radialTextOrientation = true;\n\n private float _rotationDegrees;\n\n private string[] _sectionLabels;\n\n private int _selectedAnchor = 4;\n\n private int _selectedPositionOption = 0;\n\n private int _selectedSection = 0;\n\n private float _spinDuration;\n\n private ActiveOperation? _spinningOperation = null;\n\n private int _strokeWidth;\n\n private string _textColor;\n\n private float _textScale;\n\n private bool _useAdaptiveSize = true;\n\n private int _width;\n\n private float _xPosition = 0.5f;\n\n private float _yPosition = 0.5f;\n\n public RouletteWheelEditor(\n IUiConfigurationManager configManager,\n IEditorStateManager stateManager,\n IUiThemeManager themeManager,\n RouletteWheel.RouletteWheel wheel,\n FontProvider fontProvider)\n : base(configManager, stateManager)\n {\n _wheel = wheel;\n _themeManager = themeManager;\n _fontProvider = fontProvider;\n\n _currentConfig = ConfigManager.GetConfiguration(\"RouletteWheel\");\n LoadConfiguration(_currentConfig);\n }\n\n public override string SectionKey => \"Roulette\";\n\n public override string DisplayName => \"Roulette Configuration\";\n\n public override void Initialize() { LoadAvailableFontsAsync(); }\n\n private async void Spin(int? targetSection = null)\n {\n if ( _wheel.IsSpinning )\n {\n return;\n }\n\n try\n {\n _spinningOperation = new ActiveOperation(\"wheel-spinning\", \"Spinning Wheel\");\n StateManager.RegisterActiveOperation(_spinningOperation);\n await _wheel.SpinAsync(targetSection);\n }\n catch (OperationCanceledException)\n {\n Debug.WriteLine(\"Spinning cancelled\");\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error during spinning: {ex.Message}\");\n\n if ( _spinningOperation != null )\n {\n StateManager.ClearActiveOperation(_spinningOperation.Id);\n _spinningOperation = null;\n }\n }\n }\n\n private async void LoadAvailableFontsAsync()\n {\n try\n {\n _loadingFonts = true;\n\n var operation = new ActiveOperation(\"load-fonts\", \"Loading Fonts\");\n StateManager.RegisterActiveOperation(operation);\n\n var fonts = await _fontProvider.GetAvailableFontsAsync();\n _availableFonts = fonts.ToList();\n\n // Clear operation\n StateManager.ClearActiveOperation(operation.Id);\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error loading fonts: {ex.Message}\");\n _availableFonts = [];\n }\n finally\n {\n _loadingFonts = false;\n }\n }\n\n private void LoadConfiguration(RouletteWheelOptions config)\n {\n _width = config.Width;\n _height = config.Height;\n _fontName = config.Font;\n _fontSize = config.FontSize;\n _textScale = config.TextScale;\n _textColor = config.TextColor;\n _strokeWidth = config.TextStroke;\n _useAdaptiveSize = config.AdaptiveText;\n _radialTextOrientation = config.RadialTextOrientation;\n _sectionLabels = config.SectionLabels;\n _spinDuration = config.SpinDuration;\n _minRotations = config.MinRotations;\n _animateToggle = config.AnimateToggle;\n _animationDuration = config.AnimationDuration;\n _defaultEnabled = config.Enabled;\n }\n\n public override void Render()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n\n if ( ImGui.BeginTabBar(\"RouletteConfigTabs\") )\n {\n if ( ImGui.BeginTabItem(\"Basic Settings\") )\n {\n RenderTestingSection();\n RenderBasicSettingsTab();\n RenderSectionsTab();\n RenderBehaviorTab();\n RenderStyleTab();\n\n ImGui.EndTabItem();\n }\n\n RenderPositioningTab();\n\n ImGui.EndTabBar();\n }\n\n ImGui.Spacing();\n ImGui.Separator();\n ImGui.Spacing();\n\n ImGui.SetCursorPosX(availWidth * .5f * .5f);\n if ( ImGui.Button(\"Reset\", new Vector2(150, 0)) )\n {\n ResetToDefaults();\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.IsItemHovered() )\n {\n ImGui.SetTooltip(\"Reset all Wheel settings to default values\");\n }\n\n if ( !StateManager.HasUnsavedChanges )\n {\n ImGui.BeginDisabled();\n ImGui.Button(\"Save\", new Vector2(150, 0));\n ImGui.EndDisabled();\n }\n else if ( ImGui.Button(\"Save\", new Vector2(150, 0)) )\n {\n SaveConfiguration();\n }\n }\n\n private void RenderBasicSettingsTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n bool widthChanged,\n heightChanged;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Wheel Dimensions\");\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(125);\n widthChanged = ImGui.InputInt(\"Width##WheelWidth\", ref _width, 10);\n if ( widthChanged )\n {\n _width = Math.Max(50, _width); // Minimum width\n }\n\n ImGui.SameLine();\n\n ImGui.SetCursorPosX(availWidth - 175);\n if ( ImGui.Button(\"Equal Dimensions\", new Vector2(175, 0)) )\n {\n var size = Math.Max(_width, _height);\n _width = _height = size;\n _wheel.SetDiameter(size);\n widthChanged = true;\n heightChanged = true;\n }\n\n ImGui.SetNextItemWidth(125);\n heightChanged = ImGui.InputInt(\"Height##WheelHeight\", ref _height, 10);\n if ( heightChanged )\n {\n _height = Math.Max(50, _height); // Minimum height\n }\n\n if ( widthChanged || heightChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderSectionsTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n var sectionsChanged = false;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Wheel Sections\");\n ImGui.Spacing();\n\n if ( _sectionLabels.Length > 0 )\n {\n ImGui.BeginChild(\"SectionsList\", new Vector2(0, 0), ImGuiChildFlags.AutoResizeY);\n\n for ( var i = 0; i < _sectionLabels.Length; i++ )\n {\n ImGui.PushID(i);\n\n var tempLabel = _sectionLabels[i];\n ImGui.SetNextItemWidth(availWidth - 10 - 30);\n if ( ImGui.InputText(\"##SectionLabel\", ref tempLabel, 128) )\n {\n _sectionLabels[i] = tempLabel;\n sectionsChanged = true;\n }\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"X##RemoveSection\" + i, new Vector2(30, 0)) )\n {\n var newLabels = new string[_sectionLabels.Length - 1];\n Array.Copy(_sectionLabels, 0, newLabels, 0, i);\n Array.Copy(_sectionLabels, i + 1, newLabels, i, _sectionLabels.Length - i - 1);\n _sectionLabels = newLabels;\n sectionsChanged = true;\n }\n\n ImGui.PopID();\n }\n\n ImGui.EndChild();\n }\n else\n {\n TextHelper.TextCenteredH(\"No sections defined. Add your first section below.\");\n }\n\n // Add new section\n ImGui.Spacing();\n // ImGui.Separator();\n ImGui.Spacing();\n\n ImGui.SetNextItemWidth(availWidth - 80 - 10);\n ImGui.InputText(\"##NewSectionLabel\", ref _newSectionLabel, 128);\n\n ImGui.SameLine(0, 10);\n\n if ( ImGui.Button(\"Add\", new Vector2(80, 0)) && !string.IsNullOrWhiteSpace(_newSectionLabel) )\n {\n // Add the new section\n var newLabels = new string[(_sectionLabels?.Length ?? 0) + 1];\n if ( _sectionLabels is { Length: > 0 } )\n {\n Array.Copy(_sectionLabels, newLabels, _sectionLabels.Length);\n }\n\n newLabels[^1] = _newSectionLabel;\n _sectionLabels = newLabels;\n _newSectionLabel = string.Empty;\n sectionsChanged = true;\n }\n\n if ( sectionsChanged )\n {\n UpdateConfiguration();\n }\n }\n\n private void RenderStyleTab()\n {\n var availWidth = ImGui.GetContentRegionAvail().X;\n var configChanged = false;\n\n ImGui.Spacing();\n ImGui.SeparatorText(\"Text Appearance\");\n ImGui.Spacing();\n\n // Font selection with refresh button\n {\n ImGui.SetNextItemWidth(availWidth - 120);\n\n if ( _loadingFonts )\n {\n ImGui.BeginDisabled();\n var loadingText = \"Loading fonts...\";\n ImGui.InputText(\"##Font\", ref loadingText, 100, ImGuiInputTextFlags.ReadOnly);\n ImGui.EndDisabled();\n }\n else\n {\n var fontChanged = false;\n if ( ImGui.BeginCombo(\"##Font\", string.IsNullOrEmpty(_fontName) ? \"