-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.xaml.cpp
More file actions
5694 lines (5036 loc) · 250 KB
/
MainWindow.xaml.cpp
File metadata and controls
5694 lines (5036 loc) · 250 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "pch.h"
#include "MainWindow.xaml.h"
#if __has_include("MainWindow.g.cpp")
#include "MainWindow.g.cpp"
#endif
#include "Rendering/PipelineFormat.h"
#include "Rendering/IccProfileParser.h"
#include "Rendering/EffectGraphFile.h"
#include "Rendering/PixelReadback.h"
#include "Effects/ShaderLabEffects.h"
#include "Effects/DxgiDuplicationSourceProvider.h"
#include "Effects/Performance.h"
#include "Version.h"
#include "EngineExport.h"
#include <microsoft.ui.xaml.media.dxinterop.h>
#include <shlobj.h>
#include <KnownFolders.h>
using namespace winrt;
using namespace Microsoft::UI::Xaml;
namespace winrt::ShaderLab::implementation
{
MainWindow::MainWindow()
{
InitializeComponent();
// Engine ABI compatibility check. Mismatch means the loaded
// ShaderLabEngine.dll is from a different build than the headers
// we compiled against -- abort early with a friendly message
// instead of failing later in an obscure way.
if (::ShaderLab_GetAbiVersion() != SHADERLAB_ENGINE_ABI_VERSION)
{
wchar_t msg[256];
swprintf_s(msg, L"ShaderLab engine ABI mismatch (header %u, DLL %u). Rebuild and redeploy.",
static_cast<unsigned>(SHADERLAB_ENGINE_ABI_VERSION),
static_cast<unsigned>(::ShaderLab_GetAbiVersion()));
::MessageBoxW(nullptr, msg, L"ShaderLab", MB_OK | MB_ICONERROR);
::ExitProcess(1);
}
Title(std::wstring(L"ShaderLab v") + ::ShaderLab::VersionString + L" \u2014 HDR Shader Effect Development");
// After Title() we'll refresh from RefreshTitleBar() once a graph
// is loaded; the initial state is "Untitled".
m_hwnd = GetWindowHandle();
// Close all output windows and exit the process when the main window closes.
this->Closed([this](auto&&, auto&&)
{
m_isShuttingDown = true;
m_outputWindows.clear();
// Best-effort: remove temp directories we extracted media
// archives into so the user's %TEMP% doesn't accumulate
// stale .effectgraph payloads.
std::error_code ec;
for (const auto& d : m_extractedMediaDirs)
std::filesystem::remove_all(d, ec);
// WinUI 3 keeps the process alive while any Window exists.
// Force exit so output windows don't keep us running.
::PostQuitMessage(0);
});
// Cancellable close: prompt the user when there are unsaved
// changes. AppWindow.Closing is the WinUI 3 hook that can take
// a deferral (so we can show an async dialog and decide whether
// to allow the close after the user picks an option).
this->AppWindow().Closing(
[this](auto&&, winrt::Microsoft::UI::Windowing::AppWindowClosingEventArgs const& args)
{
if (m_isShuttingDown || !m_unsavedChanges) return;
args.Cancel(true);
[](MainWindow* self) -> winrt::fire_and_forget
{
auto strong = self->get_strong();
int32_t choice = co_await self->PromptUnsavedChangesAsync();
if (choice == 2) co_return; // Cancel -> stay open
if (choice == 0) // Save then close
{
if (!self->m_currentFilePath.empty())
co_await self->RunSaveWithProgressAsync();
else
co_await self->SaveGraphAsAsync();
// If the user backed out of the picker, don't close.
if (self->m_unsavedChanges) co_return;
}
self->m_unsavedChanges = false;
self->Close();
}(this);
});
// Wire up event handlers (safe before panel is loaded).
PreviewPanel().SizeChanged({ this, &MainWindow::OnPreviewSizeChanged });
PreviewPanel().PointerMoved({ this, &MainWindow::OnPreviewPointerMoved });
PreviewPanel().KeyDown({ this, &MainWindow::OnPreviewKeyDown });
PreviewPanel().IsTabStop(true);
PopulateDisplayProfileSelector();
DisplayProfileSelector().SelectionChanged({ this, &MainWindow::OnDisplayProfileSelectionChanged });
PreviewPanel().PointerPressed({ this, &MainWindow::OnPreviewPointerPressed });
PreviewPanel().PointerReleased({ this, &MainWindow::OnPreviewPointerReleased });
PreviewPanel().PointerWheelChanged([this](auto&&, winrt::Microsoft::UI::Xaml::Input::PointerRoutedEventArgs const& args)
{
auto point = args.GetCurrentPoint(PreviewPanel());
int delta = point.Properties().MouseWheelDelta();
float cursorX = static_cast<float>(point.Position().X);
float cursorY = static_cast<float>(point.Position().Y);
float zoomFactor = (delta > 0) ? 1.1f : (1.0f / 1.1f);
float newZoom = std::clamp(m_previewZoom * zoomFactor, 0.01f, 100.0f);
// Zoom centered on cursor position (DIP coordinates).
m_previewPanX = cursorX - (cursorX - m_previewPanX) * (newZoom / m_previewZoom);
m_previewPanY = cursorY - (cursorY - m_previewPanY) * (newZoom / m_previewZoom);
m_previewZoom = newZoom;
m_forceRender = true;
args.Handled(true);
});
TraceUnitSelector().SelectedIndex(0);
TraceUnitSelector().SelectionChanged({ this, &MainWindow::OnTraceUnitSelectionChanged });
SaveGraphButton().Click({ this, &MainWindow::OnSaveGraphClicked });
LoadGraphButton().Click({ this, &MainWindow::OnLoadGraphClicked });
AutoArrangeButton().Click([this](auto&&, auto&&)
{
// Reset viewport so the laid-out nodes are visible even if the
// user had zoomed/panned the canvas off-screen.
m_nodeGraphController.SetZoom(1.0f);
m_nodeGraphController.SetPanOffset(0.0f, 0.0f);
m_nodeGraphController.AutoLayout();
m_nodeGraphController.SetNeedsRedraw();
m_forceRender = true;
});
UpdateAllEffectsButton().Click([this](auto&&, auto&&)
{
auto& registry = ::ShaderLab::Effects::ShaderLabEffects::Instance();
for (auto& node : const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes()))
{
if (!node.customEffect.has_value() || node.customEffect->shaderLabEffectId.empty())
continue;
auto* desc = registry.FindById(node.customEffect->shaderLabEffectId);
if (!desc || desc->effectVersion <= node.customEffect->shaderLabEffectVersion)
continue;
auto savedProps = node.properties;
auto freshNode = ::ShaderLab::Effects::ShaderLabEffects::CreateNode(*desc);
if (!freshNode.customEffect.has_value()) continue;
node.customEffect = std::move(freshNode.customEffect.value());
node.inputPins = std::move(freshNode.inputPins);
node.outputPins = std::move(freshNode.outputPins);
node.isClock = freshNode.isClock;
node.properties = std::move(freshNode.properties);
for (const auto& [key, val] : savedProps)
{
auto it = node.properties.find(key);
if (it != node.properties.end())
it->second = val;
}
node.dirty = true;
node.cachedOutput = nullptr; // raw pointer is now dangling
m_graphEvaluator.InvalidateNode(node.id);
}
m_graph.MarkAllDirty();
m_nodeGraphController.RebuildLayout();
PopulatePreviewNodeSelector();
UpdatePropertiesPanel();
UpdateOutdatedEffectsButton();
});
// Populate the Add Node flyout with effects from the registry.
PopulateAddNodeFlyout();
BottomTabView().SelectionChanged([this](auto&&, auto&&)
{
if (m_isShuttingDown) return;
UpdateCrosshairOverlay();
});
// Defer GPU initialization until the SwapChainPanel is in the visual tree.
PreviewPanel().Loaded([this](auto&&, auto&&) { OnPreviewPanelLoaded(); });
NodeGraphPanel().SizeChanged([this](auto&&, winrt::Microsoft::UI::Xaml::SizeChangedEventArgs const& e)
{
ResizeGraphPanel(
static_cast<float>(e.NewSize().Width),
static_cast<float>(e.NewSize().Height));
});
NodeGraphPanel().CompositionScaleChanged([this](auto&&, auto&&)
{
UpdateGraphPanelScale();
ResizeGraphPanel(
static_cast<float>(NodeGraphPanel().ActualWidth()),
static_cast<float>(NodeGraphPanel().ActualHeight()));
});
NodeGraphContainer().PointerPressed({ this, &MainWindow::OnGraphPanelPointerPressed });
NodeGraphContainer().PointerMoved({ this, &MainWindow::OnGraphPanelPointerMoved });
NodeGraphContainer().PointerReleased({ this, &MainWindow::OnGraphPanelPointerReleased });
NodeGraphContainer().PointerWheelChanged({ this, &MainWindow::OnGraphPanelPointerWheel });
NodeGraphContainer().KeyDown([this](auto&&, winrt::Microsoft::UI::Xaml::Input::KeyRoutedEventArgs const& args)
{
auto key = args.Key();
auto ctrlState = winrt::Microsoft::UI::Input::InputKeyboardSource::GetKeyStateForCurrentThread(
winrt::Windows::System::VirtualKey::Control);
bool ctrlDown = (static_cast<uint32_t>(ctrlState) & static_cast<uint32_t>(winrt::Windows::UI::Core::CoreVirtualKeyStates::Down)) != 0;
// Ctrl+A: select all nodes.
if (ctrlDown && key == winrt::Windows::System::VirtualKey::A)
{
m_nodeGraphController.SelectAll();
args.Handled(true);
return;
}
// Ctrl+C: copy selected nodes.
if (ctrlDown && key == winrt::Windows::System::VirtualKey::C)
{
auto& sel = m_nodeGraphController.SelectedNodes();
if (sel.empty() && m_selectedNodeId != 0)
{
m_nodeGraphController.SelectNode(m_selectedNodeId);
}
m_nodeClipboard.clear();
m_edgeClipboard.clear();
for (uint32_t nodeId : m_nodeGraphController.SelectedNodes())
{
auto* node = m_graph.FindNode(nodeId);
if (node)
m_nodeClipboard.push_back({ *node, nodeId });
}
// Copy internal edges (edges where both src and dst are in the selection).
for (const auto& edge : m_graph.Edges())
{
bool srcIn = m_nodeGraphController.SelectedNodes().count(edge.sourceNodeId) > 0;
bool dstIn = m_nodeGraphController.SelectedNodes().count(edge.destNodeId) > 0;
if (srcIn && dstIn)
m_edgeClipboard.push_back(edge);
}
args.Handled(true);
return;
}
// Ctrl+V: paste copied nodes.
if (ctrlDown && key == winrt::Windows::System::VirtualKey::V && !m_nodeClipboard.empty())
{
// Map old IDs to new IDs.
std::unordered_map<uint32_t, uint32_t> idMap;
float offsetX = 40.0f, offsetY = 40.0f;
for (auto& entry : m_nodeClipboard)
{
auto newNode = entry.node;
newNode.position.x += offsetX;
newNode.position.y += offsetY;
newNode.dirty = true;
newNode.cachedOutput = nullptr;
newNode.runtimeError.clear();
// Fresh GUID for custom effects to avoid D2D shader ID collisions.
if (newNode.customEffect.has_value())
CoCreateGuid(&newNode.customEffect->shaderGuid);
uint32_t newId = m_nodeGraphController.AddNode(std::move(newNode), { 0.0f, 0.0f });
idMap[entry.originalId] = newId;
}
// Reconnect internal edges with new IDs.
for (const auto& edge : m_edgeClipboard)
{
auto srcIt = idMap.find(edge.sourceNodeId);
auto dstIt = idMap.find(edge.destNodeId);
if (srcIt != idMap.end() && dstIt != idMap.end())
m_graph.Connect(srcIt->second, edge.sourcePin, dstIt->second, edge.destPin);
}
m_graph.MarkAllDirty();
m_nodeGraphController.RebuildLayout();
PopulatePreviewNodeSelector();
args.Handled(true);
return;
}
// Ctrl+L: auto-arrange graph layout.
if (ctrlDown && key == winrt::Windows::System::VirtualKey::L)
{
m_nodeGraphController.AutoLayout();
m_forceRender = true;
args.Handled(true);
return;
}
// Delete: remove all selected nodes (or single selected node).
if (key == winrt::Windows::System::VirtualKey::Delete &&
(!m_nodeGraphController.SelectedNodes().empty() || m_selectedNodeId != 0))
{
// If only a single node is selected via click (not multi-select), select it for deletion.
if (m_nodeGraphController.SelectedNodes().empty() && m_selectedNodeId != 0)
{
const auto* node = m_graph.FindNode(m_selectedNodeId);
if (node && node->type == ::ShaderLab::Graph::NodeType::Output)
return;
m_nodeGraphController.SelectNode(m_selectedNodeId);
}
// Close output windows for nodes being deleted.
for (uint32_t nodeId : m_nodeGraphController.SelectedNodes())
CloseOutputWindow(nodeId);
m_nodeGraphController.DeleteSelected();
m_selectedNodeId = 0;
m_graph.MarkAllDirty();
m_nodeGraphController.RebuildLayout();
PopulatePreviewNodeSelector();
UpdatePropertiesPanel();
MarkUnsaved();
// Reset preview to Output node.
for (const auto& n : m_graph.Nodes())
{
if (n.type == ::ShaderLab::Graph::NodeType::Output)
{
m_previewNodeId = n.id;
break;
}
}
PreviewOverlayBorder().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);
args.Handled(true);
}
});
NodeGraphContainer().IsTabStop(true);
SaveImageButton().Click({ this, &MainWindow::OnSaveImageClicked });
EffectDesignerButton().Click([this](auto&&, auto&&) { OpenEffectDesigner(); });
// MCP server toggle.
McpServerToggle().Click([this](auto&&, auto&&)
{
bool checked = McpServerToggle().IsChecked().GetBoolean();
if (checked)
{
if (!m_mcpServer)
SetupMcpRoutes();
if (m_mcpServer && !m_mcpServer->IsRunning())
m_mcpServer->Start(47808);
// Wait briefly for the listener thread to bind and set the port.
Sleep(100);
uint16_t actualPort = m_mcpServer ? m_mcpServer->Port() : 47808;
McpServerLabel().Text(std::format(L"MCP Server :{}", actualPort));
McpExportConfigButton().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Visible);
ResetMcpActivityState();
UpdateMcpActivityIndicator();
}
else
{
if (m_mcpServer)
m_mcpServer->Stop();
McpServerLabel().Text(L"MCP Server");
McpExportConfigButton().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);
ResetMcpActivityState();
UpdateMcpActivityIndicator();
}
});
McpExportConfigButton().Click([this](auto&&, auto&&)
{
uint16_t port = m_mcpServer ? m_mcpServer->Port() : 47808;
namespace DP = winrt::Windows::ApplicationModel::DataTransfer;
auto pkg = DP::DataPackage();
std::wstring config = std::format(
L"{{\n"
L" \"mcpServers\": {{\n"
L" \"shaderlab\": {{\n"
L" \"url\": \"http://localhost:{}/\"\n"
L" }}\n"
L" }}\n"
L"}}", port);
pkg.SetText(config);
DP::Clipboard::SetContent(pkg);
PipelineFormatText().Text(std::format(L"MCP config copied to clipboard (http://localhost:{})", port));
});
}
MainWindow::~MainWindow()
{
m_isShuttingDown = true;
m_renderShouldStop.store(true, std::memory_order_release);
// Stop MCP server before tearing down resources.
if (m_mcpServer)
m_mcpServer->Stop();
if (m_renderTimer)
{
m_renderTimer.Stop();
m_renderTimer = nullptr;
}
// Two-phase shutdown of the render worker:
m_renderDispatcher.Shutdown();
if (m_renderWorker.joinable())
{
m_renderWorker.request_stop();
m_renderWorker.join();
}
m_traceSwapChain = nullptr;
m_traceSwatchTarget = nullptr;
// Close all output windows.
m_outputWindows.clear();
// Release UI-side offscreen wrappers before tearing down render engine.
for (auto& b : m_offscreenSourceBitmapUi) b = nullptr;
m_graphEvaluator.ReleaseCache(m_graph);
m_displayMonitor.Shutdown();
m_renderEngine.Shutdown();
}
HWND MainWindow::GetWindowHandle()
{
HWND hwnd{ nullptr };
auto windowNative = this->try_as<::IWindowNative>();
if (windowNative)
{
windowNative->get_WindowHandle(&hwnd);
}
return hwnd;
}
void MainWindow::InitializeRendering()
{
// Query display capabilities and pick a default pipeline format.
m_displayMonitor.Initialize(m_hwnd);
auto caps = m_displayMonitor.CachedCapabilities();
auto format = ::ShaderLab::Rendering::RecommendedFormat(caps);
// Create D3D11/D2D1 device stack and swap chain on the PreviewPanel.
m_renderEngine.Initialize(m_hwnd, PreviewPanel(), format, m_devicePref);
// Phase 8c: enable skip-unneeded-CPU-readback. Every frame the
// RenderTick installs `{m_selectedNodeId}` as the CPU-analysis
// interest set, so the selected node's Properties panel stays
// live while every other compute analysis dispatch's Map() is
// skipped when its consumers are entirely GPU-routed.
// MCP /analysis/{id} reads temporarily disable the flag so they
// always return fresh values regardless of selection.
::ShaderLab::Performance::SetSkipUnneededCpuReadbackEnabled(true);
// Now that we have a DXGI factory, register adapter-change monitoring.
if (m_renderEngine.DXGIFactory())
{
m_displayMonitor.Shutdown();
m_displayMonitor.Initialize(m_hwnd, m_renderEngine.DXGIFactory());
}
// Subscribe to display changes so we can update the status bar.
m_displayMonitor.SetCallback([this](const ::ShaderLab::Rendering::DisplayCapabilities& /*newCaps*/)
{
this->DispatcherQueue().TryEnqueue([this]()
{
// Re-evaluate graph so effects using monitor gamut
// pick up the new primaries.
m_graph.MarkAllDirty();
m_forceRender = true;
// Pick up new refresh rate (e.g. user changed displays
// or switched modes from 60 Hz to 144 Hz).
UpdateRenderTimerInterval();
// Push the new capabilities into any Working Space nodes
// so downstream binders see the live values immediately.
UpdateWorkingSpaceNodes();
UpdateStatusBar();
});
});
}
void MainWindow::RegisterCustomEffects()
{
if (m_customEffectsRegistered) return;
auto* factory = m_renderEngine.D2DFactory();
if (!factory) return;
winrt::com_ptr<ID2D1Factory1> factory1;
factory->QueryInterface(IID_PPV_ARGS(factory1.put()));
if (!factory1) return;
::ShaderLab::Effects::RegisterEngineD2DEffects(factory1.get());
OutputDebugStringW(L"[CustomFX] Registered engine D2D effects\n");
// Phase 8: enable on-disk bytecode cache under %LOCALAPPDATA%.
// Background-reap entries older than 90 days on engine init.
wchar_t* localAppData = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &localAppData)) && localAppData)
{
std::wstring cacheRoot = std::wstring(localAppData) + L"\\ShaderLab\\bytecode";
::CoTaskMemFree(localAppData);
::ShaderLab::Effects::ConfigureBytecodeCache(cacheRoot);
OutputDebugStringW((L"[CustomFX] BytecodeCache root: " + cacheRoot + L"\n").c_str());
}
m_customEffectsRegistered = true;
}
void MainWindow::OnPreviewPanelLoaded()
{
if (!m_hwnd || m_renderEngine.IsInitialized()) return;
InitializeRendering();
RegisterCustomEffects();
// Pre-setup MCP routes (server starts when user toggles the button or --mcp flag).
SetupMcpRoutes();
if (m_autoStartMcp && m_mcpServer)
{
m_mcpServer->Start(47808);
McpServerToggle().IsChecked(true);
// Delay slightly to let the listener thread bind.
DispatcherQueue().TryEnqueue([this]()
{
uint16_t actualPort = m_mcpServer ? m_mcpServer->Port() : 47808;
McpServerLabel().Text(std::format(L"MCP Server :{}", actualPort));
McpExportConfigButton().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Visible);
ResetMcpActivityState();
UpdateMcpActivityIndicator();
});
}
UpdateStatusBar();
// Refresh title bar now that the effect library is loaded so the
// title shows both the app and effect-library version.
RefreshTitleBar();
m_nodeGraphController.SetGraph(&m_graph);
m_nodeGraphController.SetDispatcher(&m_renderDispatcher);
m_nodeGraphController.SetConnectionCallback(
[this](uint32_t srcId, uint32_t srcPin, uint32_t dstId, uint32_t dstPin, bool isData) {
auto* srcNode = m_graph.FindNode(srcId);
auto* dstNode = m_graph.FindNode(dstId);
std::wstring srcName = srcNode ? srcNode->name : std::format(L"Node {}", srcId);
std::wstring dstName = dstNode ? dstNode->name : std::format(L"Node {}", dstId);
if (isData)
{
m_nodeLogs[dstId].Info(std::format(L"Property bound from {} (data pin)", srcName));
m_nodeLogs[srcId].Info(std::format(L"Data output bound to {}", dstName));
}
else
{
m_nodeLogs[dstId].Info(std::format(L"Input {} connected from {}", dstPin, srcName));
m_nodeLogs[srcId].Info(std::format(L"Output {} connected to {}", srcPin, dstName));
}
MarkUnsaved();
});
if (m_renderEngine.D3DDevice())
{
m_pixelInspector.Initialize(m_renderEngine.D3DDevice());
m_pixelTrace.Initialize(m_renderEngine.D3DDevice());
}
// Start render loop. The interval tracks the monitor's refresh
// rate (clamped to 60..240 Hz), so 120 Hz / 144 Hz / 240 Hz panels
// and high-FPS video sources actually run at their native cadence.
m_fpsTimePoint = std::chrono::steady_clock::now();
m_lastRenderTick = m_fpsTimePoint;
m_renderTimer = DispatcherQueue().CreateTimer();
m_renderTimer.Tick({ this, &MainWindow::OnRenderTick });
UpdateRenderTimerInterval();
m_renderTimer.Start();
// Spawn the render-worker thread (P7 offscreen-render path). Owns
// the engine D2D context and runs the graph + GPU loop independently
// of the UI thread, drawing into a double-buffered offscreen target.
// UI thread blits the latest published buffer into the SwapChainPanel-
// bound swap chain in OnRenderTick.
m_renderShouldStop.store(false, std::memory_order_release);
m_renderWorker = std::jthread([this](std::stop_token stop){
this->RenderWorkerLoop(stop);
});
// Initialize the node graph editor panel.
InitializeGraphPanel();
// Sweep %TEMP% for ShaderLab-* media dirs left behind by a
// crashed prior instance and offer to delete them. Runs after
// panel init so the dialog has a XamlRoot to attach to.
ReapStaleMediaDirsAsync();
// If the app was launched via file double-click, load that
// graph now that rendering is wired up.
if (!m_pendingOpenPath.empty())
{
auto path = std::move(m_pendingOpenPath);
m_pendingOpenPath.clear();
LoadGraphFromPathAsync(winrt::hstring(path));
}
else
{
RefreshTitleBar();
}
}
void MainWindow::UpdateStatusBar()
{
auto caps = m_displayMonitor.CachedCapabilities();
if (m_displayMonitor.IsSimulated())
{
auto profile = m_displayMonitor.ActiveProfile();
DisplayModeText().Text(L"Display: Simulated \u2014 " + winrt::hstring(profile.profileName));
}
else
{
DisplayModeText().Text(L"Display: " + caps.ModeString());
}
DisplayLuminanceText().Text(L"Max Luminance: " + caps.LuminanceString());
PipelineFormatText().Text(L"Pipeline: " + m_renderEngine.ActiveFormat().name);
// GPU info.
if (m_renderEngine.IsInitialized())
{
if (m_renderEngine.IsWarp())
GpuInfoText().Text(L"GPU: Software (WARP)");
else
GpuInfoText().Text(L"GPU: " + m_renderEngine.AdapterName());
}
}
void MainWindow::ResetMcpActivityState()
{
m_mcpLastActivityMs.store(0, std::memory_order_relaxed);
m_mcpRequestCount.store(0, std::memory_order_relaxed);
m_mcpUiUpdateSeq.store(0, std::memory_order_relaxed);
m_mcpLastUiUpdateSeq = 0;
std::lock_guard lock(m_mcpLastReqMutex);
m_mcpLastReqMethod.clear();
m_mcpLastReqPath.clear();
m_mcpLastReqPeer.clear();
m_mcpLastReqStatus = 0;
m_mcpKnownPeers.clear();
}
void MainWindow::UpdateMcpActivityIndicator()
{
// Hide the dot entirely when the server is off.
if (!m_mcpServer || !m_mcpServer->IsRunning())
{
McpActivityDot().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);
Controls::ToolTipService::SetToolTip(McpServerToggle(),
winrt::box_value(winrt::hstring(L"Start/stop MCP server for AI assistant integration")));
return;
}
McpActivityDot().Visibility(winrt::Microsoft::UI::Xaml::Visibility::Visible);
const int64_t lastMs = m_mcpLastActivityMs.load(std::memory_order_relaxed);
const int64_t nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
const int64_t ageMs = (lastMs == 0) ? -1 : (nowMs - lastMs);
const uint64_t totalCount = m_mcpRequestCount.load(std::memory_order_relaxed);
// Color ramp (chosen for high contrast against the accent-blue
// checked-toggle background AND the neutral unchecked background):
// no activity yet -> dark slate (#FF303030)
// <250ms -> amber (#FFFFC107) -- "live" pulse
// 250-1500ms -> linear fade amber -> dark slate
// >=1500ms -> dark slate (#FF303030)
winrt::Windows::UI::Color color{};
color.A = 0xFF;
if (ageMs < 0)
{
color.R = 0x30; color.G = 0x30; color.B = 0x30;
}
else if (ageMs < 250)
{
color.R = 0xFF; color.G = 0xC1; color.B = 0x07;
}
else if (ageMs < 1500)
{
const float t = static_cast<float>(ageMs - 250) / 1250.0f;
const float inv = 1.0f - t;
const float r = 0xFF * inv + 0x30 * t;
const float g = 0xC1 * inv + 0x30 * t;
const float b = 0x07 * inv + 0x30 * t;
color.R = static_cast<uint8_t>(r);
color.G = static_cast<uint8_t>(g);
color.B = static_cast<uint8_t>(b);
}
else
{
color.R = 0x30; color.G = 0x30; color.B = 0x30;
}
McpActivityDotBrush().Color(color);
// Tooltip: only rebuild on a callback-driven change OR while we're
// still in the active fade window (so "Xs ago" stays current).
const uint64_t seq = m_mcpUiUpdateSeq.load(std::memory_order_acquire);
const bool inFade = (ageMs >= 0 && ageMs < 1500);
if (seq == m_mcpLastUiUpdateSeq && !inFade)
return;
m_mcpLastUiUpdateSeq = seq;
std::wstring tooltip;
uint16_t port = m_mcpServer->Port();
if (totalCount == 0)
{
tooltip = std::format(L"MCP Server :{} \u2014 listening (no requests yet)", port);
}
else
{
std::string method, path, peer;
uint16_t status = 0;
size_t peerCount = 0;
{
std::lock_guard lock(m_mcpLastReqMutex);
method = m_mcpLastReqMethod;
path = m_mcpLastReqPath;
peer = m_mcpLastReqPeer;
status = m_mcpLastReqStatus;
peerCount = m_mcpKnownPeers.size();
}
std::wstring methodW(method.begin(), method.end());
int needed = MultiByteToWideChar(CP_UTF8, 0, path.c_str(),
static_cast<int>(path.size()), nullptr, 0);
std::wstring pathW(static_cast<size_t>(needed), L'\0');
if (needed > 0)
{
MultiByteToWideChar(CP_UTF8, 0, path.c_str(),
static_cast<int>(path.size()), pathW.data(), needed);
}
std::wstring peerW(peer.begin(), peer.end());
std::wstring ageStr;
if (ageMs < 1000) ageStr = L"just now";
else if (ageMs < 60000) ageStr = std::format(L"{}s ago", ageMs / 1000);
else ageStr = std::format(L"{}m ago", ageMs / 60000);
tooltip = std::format(
L"MCP Server :{} \u2014 {} request{}\n"
L"Last: {} {} \u2192 {} ({})\n"
L"From: {}{}",
port, totalCount, (totalCount == 1 ? L"" : L"s"),
methodW, pathW, status, ageStr,
peerW.empty() ? L"(unknown)" : peerW.c_str(),
peerCount > 1 ? std::format(L" (\u00d7{} distinct clients)", peerCount).c_str() : L"");
}
Controls::ToolTipService::SetToolTip(McpServerToggle(),
winrt::box_value(winrt::hstring(tooltip)));
}
uint32_t MainWindow::QueryDisplayRefreshHz() const noexcept
{
// Use EnumDisplaySettings on the monitor that contains the app HWND.
// dmDisplayFrequency is reported in whole Hz; modern panels round to
// 60/120/144/165/240 etc. Returning 0 here is the "unknown" signal.
if (!m_hwnd)
return 0;
HMONITOR mon = MonitorFromWindow(m_hwnd, MONITOR_DEFAULTTOPRIMARY);
if (!mon)
return 0;
MONITORINFOEXW mi{};
mi.cbSize = sizeof(mi);
if (!::GetMonitorInfoW(mon, &mi))
return 0;
DEVMODEW dm{};
dm.dmSize = sizeof(dm);
if (!::EnumDisplaySettingsW(mi.szDevice, ENUM_CURRENT_SETTINGS, &dm))
return 0;
return dm.dmDisplayFrequency;
}
void MainWindow::UpdateRenderTimerInterval()
{
// Pick a target Hz from the active monitor, clamped to [60, 240].
// - 60 Hz floor: avoid laggy interactions on 30 Hz TV-out modes.
// - 240 Hz ceiling: dispatcher tick scheduling becomes noisy below
// ~4 ms, and rendering faster than panel refresh is wasted work.
uint32_t hz = QueryDisplayRefreshHz();
if (hz < 60) hz = 60;
if (hz > 240) hz = 240;
if (hz == m_targetRefreshHz && m_renderTimer)
return;
m_targetRefreshHz = hz;
// Use microseconds so non-integer-ms periods (e.g. 144 Hz ~6.944 ms)
// don't get rounded to a slower or faster cadence than the panel.
const auto interval = std::chrono::microseconds(1'000'000 / hz);
if (m_renderTimer)
m_renderTimer.Interval(interval);
}
void MainWindow::OnGpuInfoTapped(
winrt::Windows::Foundation::IInspectable const& sender,
winrt::Microsoft::UI::Xaml::Input::TappedRoutedEventArgs const& /*args*/)
{
namespace Controls = winrt::Microsoft::UI::Xaml::Controls;
using namespace ::ShaderLab::Rendering;
auto adapters = RenderEngine::EnumerateAdapters();
if (adapters.empty()) return;
auto flyout = Controls::MenuFlyout();
for (size_t i = 0; i < adapters.size(); ++i)
{
auto& a = adapters[i];
auto item = Controls::MenuFlyoutItem();
std::wstring label = a.name;
if (a.dedicatedVideoMemoryMB > 0)
label += std::format(L" ({} MB)", a.dedicatedVideoMemoryMB);
if (a.isWarp)
label += L" [Software]";
// Mark current adapter.
if (a.name == m_renderEngine.AdapterName() ||
(a.isWarp && m_renderEngine.IsWarp()))
label = L"\u2713 " + label;
item.Text(winrt::hstring(label));
auto luid = a.luid;
bool isWarp = a.isWarp;
item.Click([this, luid, isWarp](auto&&, auto&&) {
SwitchAdapter(
isWarp ? DevicePreference::Warp : DevicePreference::Adapter,
luid);
});
flyout.Items().Append(item);
}
flyout.ShowAt(sender.as<winrt::Microsoft::UI::Xaml::FrameworkElement>());
}
void MainWindow::SwitchAdapter(
::ShaderLab::Rendering::DevicePreference pref, LUID adapterLuid)
{
// Stop UI render timer.
if (m_renderTimer) m_renderTimer.Stop();
// Stop the render worker thread before tearing down GPU resources.
m_renderShouldStop.store(true, std::memory_order_release);
m_renderDispatcher.Wake();
if (m_renderWorker.joinable())
{
m_renderWorker.request_stop();
m_renderWorker.join();
}
m_renderDispatcher.ResetConsumer();
// Save graph + view state.
auto graphJson = m_graph.ToJson();
uint32_t savedPreviewId = m_previewNodeId;
uint32_t savedSelectedId = m_selectedNodeId;
auto savedPan = m_nodeGraphController.PanOffset();
float savedZoom = m_nodeGraphController.Zoom();
float savedPreviewZoom = m_previewZoom;
float savedPreviewPanX = m_previewPanX;
float savedPreviewPanY = m_previewPanY;
// ---- NUKE EVERYTHING ----
m_graphEvaluator.ReleaseCache(m_graph);
m_sourceFactory.ReleaseCache();
m_nodeGraphController.ReleaseDeviceResources();
// Clear swap chain references from XAML panels before destroying them.
try {
auto panelNative = NodeGraphPanel().as<ISwapChainPanelNative>();
if (panelNative) panelNative->SetSwapChain(nullptr);
} catch (...) {}
m_graphRenderTarget = nullptr;
m_graphSwapChain = nullptr;
m_graphGridBrush = nullptr;
m_traceSwatchTarget = nullptr;
m_traceSwapChain = nullptr;
for (auto& b : m_offscreenSourceBitmapUi) b = nullptr;
m_offscreenWrapperWidth = 0;
m_offscreenWrapperHeight = 0;
m_offscreenPublishedIdx.store(-1, std::memory_order_release);
ReleaseUiD2dContext();
for (auto& w : m_outputWindows) w->Close();
m_outputWindows.clear();
for (auto& w : m_logWindows) w->Close();
m_logWindows.clear();
m_graph.Clear();
m_displayMonitor.SetCallback(nullptr);
m_displayMonitor.Shutdown();
m_renderEngine.Shutdown();
// ---- REBUILD FROM SCRATCH ----
m_devicePref = pref;
if (pref == ::ShaderLab::Rendering::DevicePreference::Adapter)
m_renderEngine.SetPreferredAdapterLuid(adapterLuid);
try
{
InitializeRendering();
}
catch (...)
{
// Requested adapter failed — fall back to default.
OutputDebugStringW(L"[GPU Switch] InitializeRendering failed, falling back to Default\n");
m_devicePref = ::ShaderLab::Rendering::DevicePreference::Default;
try { InitializeRendering(); }
catch (...) {
// Total failure — restart timer and bail.
if (m_renderTimer) m_renderTimer.Start();
return;
}
}
m_customEffectsRegistered = false;
RegisterCustomEffects();
InitializeGraphPanel();
if (m_renderEngine.D3DDevice())
{
m_pixelInspector.Initialize(m_renderEngine.D3DDevice());
m_pixelTrace.Initialize(m_renderEngine.D3DDevice());
}
// ---- RELOAD GRAPH ----
try { m_graph = ::ShaderLab::Graph::EffectGraph::FromJson(graphJson); }
catch (...) {}
ResetAfterGraphLoad(false);
m_nodeGraphController.RebuildLayout();
// Restore view state.
if (savedPreviewId != 0 && m_graph.FindNode(savedPreviewId))
m_previewNodeId = savedPreviewId;
m_nodeGraphController.SetPanOffset(savedPan.x, savedPan.y);
m_nodeGraphController.SetZoom(savedZoom);
m_previewZoom = savedPreviewZoom;
m_previewPanX = savedPreviewPanX;
m_previewPanY = savedPreviewPanY;
m_needsFitPreview = false;
if (savedSelectedId != 0 && m_graph.FindNode(savedSelectedId))
{
m_selectedNodeId = savedSelectedId;
m_nodeGraphController.SelectNode(savedSelectedId);
UpdatePropertiesPanel();
}
// Re-prepare source nodes on the new device.
// Skip video sources — they can be reopened by the user via file picker.
auto* dc = m_renderEngine.D2DDeviceContext();
if (dc)
{
for (auto& node : const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes()))
{
if (node.type == ::ShaderLab::Graph::NodeType::Source)
{
bool isVideo = false;
auto it = node.properties.find(L"IsVideo");
if (it != node.properties.end())
if (auto* b = std::get_if<bool>(&it->second)) isVideo = *b;
if (isVideo)
{
// Defer video reload — give the new device time to settle.
uint32_t videoNodeId = node.id;
node.dirty = true;
DispatcherQueue().TryEnqueue([this, videoNodeId]() {
auto* vn = m_graph.FindNode(videoNodeId);
auto* vdc = m_renderEngine.D2DDeviceContext();
if (vn && vdc)
{
try {
m_sourceFactory.PrepareSourceNode(*vn, vdc, 0.0,
m_renderEngine.D3DDevice(), m_renderEngine.D3DContext());
vn->runtimeError.clear();
} catch (...) {
vn->runtimeError = L"Video reload failed after GPU switch";
}
}
});
continue;
}
node.dirty = true;
try {
m_sourceFactory.PrepareSourceNode(node, dc, 0.0,
m_renderEngine.D3DDevice(), m_renderEngine.D3DContext());
} catch (...) {
node.dirty = false;
}
}
}
}
m_forceRender = true;
UpdateStatusBar();
// Restart the render worker thread on the new device. SwitchAdapter
// stopped+joined it before teardown so it could release engine
// resources cleanly; we need to bring it back so the graph evaluates
// on the new GPU. Without this, the app appears frozen after a
// /gpu/switch -- no clock ticks, no video frames, no Present.
m_renderShouldStop.store(false, std::memory_order_release);