-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.RenderTick.cpp
More file actions
881 lines (797 loc) · 40 KB
/
Copy pathMainWindow.RenderTick.cpp
File metadata and controls
881 lines (797 loc) · 40 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
// MainWindow partial (Phase 4 split): the OnRenderTick / RenderWorkerLoop
// render loop, including the dirty-propagation pre-pass, video tick,
// and output-window present. All methods are members of
// `winrt::ShaderLab::implementation::MainWindow`. Extracted from
// MainWindow.xaml.cpp at commit c177770. (The pre-worker RenderTickBody /
// RenderFrame were removed in stdio-migration Step 7 — dead since v1.7.0.)
#include "pch.h"
#include "MainWindow.xaml.h"
#include "Rendering/PipelineFormat.h"
namespace winrt::ShaderLab::implementation
{
// -----------------------------------------------------------------------
// Render loop
//
// The render loop is split across two threads:
// - UI thread (m_renderTimer DispatcherQueueTimer): runs OnRenderTick.
// Handles XAML-touching work only -- editor-canvas redraw on the
// UI-side D2D context, FPS panel text update, video seek slider,
// properties panel refresh, MCP indicator, log windows.
// - Render-worker thread (m_renderWorker): runs RenderWorkerLoop, whose
// per-tick body handles all graph + GPU work -- working space sync,
// capture/clock/video upload, dirty propagation, RenderFrameToOffscreen
// (evaluates the graph and draws into the double-buffered offscreen),
// and snapshot publication.
//
// The two threads communicate through:
// - m_renderDispatcher: closures from UI/MCP land on the render thread
// - m_uiGraphSnapshot: render thread publishes per-frame; UI reads
//
// This split exists so that a slow GPU evaluation (heavy graph, expensive
// synchronous compute readbacks) cannot block UI input handling. The
// user-visible win is that buttons / flyouts / canvas pan-zoom stay
// responsive even when the render side is at ~2 fps on a heavy graph.
// -----------------------------------------------------------------------
void MainWindow::OnRenderTick(
winrt::Microsoft::UI::Dispatching::DispatcherQueueTimer const& /*sender*/,
winrt::Windows::Foundation::IInspectable const& /*args*/)
{
if (m_isShuttingDown) return;
if (!m_renderEngine.IsInitialized()) return;
try
{
// Compute frame delta time (used by the render-tick body for clock
// node advancement and frame timing).
auto now = std::chrono::steady_clock::now();
double deltaSec = std::chrono::duration<double>(now - m_lastRenderTick).count();
m_lastRenderTick = now;
if (deltaSec > 0.1) deltaSec = 0.016;
auto tTickStart = std::chrono::high_resolution_clock::now();
// Cache the preview panel's DIP size (UI-thread-only XAML read) so the
// render worker can fit a newly-selected node to view after eval
// without touching XAML. See FitPreviewToView / m_needsFitPreview.
if (auto panel = PreviewPanel())
{
m_previewViewportW = static_cast<float>(panel.ActualWidth());
m_previewViewportH = static_cast<float>(panel.ActualHeight());
}
// Drain pending dispatcher closures: NO-OP from the UI side post-P7.
// The worker thread is the registered consumer and drains its own
// queue. UI thread reading the queue would race graph mutations and
// process closures slowly because OnRenderTick also does blit /
// canvas redraw / event handling. Leaving Drain() here is the
// primary cause of UI dropdown / hover input lag under load:
// long-running MCP closures end up running on the UI thread,
// blocking input event delivery for the duration. Worker calls
// m_renderDispatcher.Drain() in RenderWorkerLoop -- that's the only
// path closures should run on.
// m_renderDispatcher.Drain(); // <-- removed in 7fa7021+
// Blit the most recently published offscreen frame into the
// SwapChainPanel-bound swap chain and Present.
BlitOffscreenToSwapChain();
// Editor canvas redraw (UI-side D2D context, P4).
// Trigger a redraw whenever the worker has published a new snapshot
// since our last UI tick -- the canvas reads runtime fields like
// clockTime / analysisOutput from the live graph, but doesn't
// self-invalidate when those change. Without this, the canvas only
// redraws on UI-side interaction, so a playing Clock or Video looks
// frozen even though the worker is ticking and republishing.
const uint64_t curGen = m_frameGeneration.load(std::memory_order_acquire);
if (curGen != m_lastSeenFrameGeneration)
{
m_nodeGraphController.SetNeedsRedraw();
m_lastSeenFrameGeneration = curGen;
}
RenderNodeGraph();
// P7: present any open output windows on the UI thread. Render
// worker has already drawn into each sink's offscreen pair (see
// MainWindow::RenderOutputSinks called from RenderFrameToOffscreen);
// here we just sync UI view state + blit + Present1 per window.
PresentOutputWindows();
auto tNodeGraphEnd = std::chrono::high_resolution_clock::now();
// Accumulate UI-tick timing.
{
auto usec = [](auto a, auto b) {
return std::chrono::duration<double, std::micro>(b - a).count();
};
const double a = 0.1;
auto& t = m_frameTiming;
t.uiTickUs = t.uiTickUs * (1-a) + usec(tTickStart, tNodeGraphEnd) * a;
}
// Update video seek slider and position label while playing.
if (m_videoSeekSlider && m_videoSeekNodeId != 0)
{
auto* vp = m_sourceFactory.GetVideoProvider(m_videoSeekNodeId);
if (vp && vp->IsOpen())
{
double pos = vp->CurrentPosition();
m_videoSeekSuppressEvents = true;
m_videoSeekSlider.Value(pos);
m_videoSeekSuppressEvents = false;
if (m_videoPositionLabel)
m_videoPositionLabel.Text(std::format(L"Position: {:.1f}s / {:.1f}s", pos, vp->Duration()));
}
}
// Periodic UI updates at 250 ms (log windows, properties panel,
// MCP activity indicator, FPS tooltip) and 1 s (FPS counter).
auto fpsNow = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(fpsNow - m_fpsTimePoint).count();
if (elapsed >= 250)
{
if (!m_logWindows.empty())
UpdateLogWindows();
// Decide whether the selected node's Properties panel needs a
// refresh WITHOUT holding a live-graph pointer on the UI thread
// (the decision-#70 race). Read under a shared lock on
// m_graphMutex, capture a plain bool, release, THEN act -- never
// hold the lock across UpdatePropertiesPanel, which dispatches to
// the render worker (m_graphMutex is taken exclusively there;
// holding it across the dispatch would deadlock). Step 7 residual.
bool refreshBoundProps = false;
if (m_selectedNodeId != 0)
{
std::shared_lock<std::shared_mutex> graphLock(m_graphMutex);
if (m_graph.HasDirtyNodes())
{
auto* selNode = m_graph.FindNode(m_selectedNodeId);
refreshBoundProps = selNode && !selNode->propertyBindings.empty();
}
}
if (refreshBoundProps && !IsPropertiesPanelInteracting())
UpdatePropertiesPanel();
UpdateMcpActivityIndicator();
UpdateFpsTooltip();
}
if (elapsed >= 1000)
{
uint64_t framesSeen = m_frameCount.exchange(0, std::memory_order_relaxed);
float fps = static_cast<float>(framesSeen) * 1000.0f / static_cast<float>(elapsed);
uint64_t currentVideoUploads = m_sourceFactory.TotalVideoUploads();
float videoFps = static_cast<float>(currentVideoUploads - m_lastVideoUploadCount) * 1000.0f / static_cast<float>(elapsed);
m_lastVideoUploadCount = currentVideoUploads;
m_lastVideoFps = videoFps;
m_lastFps = fps;
FpsText().Text(std::format(L"{:.0f} fps | {:.1f} ms", fps, m_frameTiming.totalUs / 1000.0));
UpdateFpsTooltip();
m_fpsTimePoint = fpsNow;
}
} // end try
catch (const winrt::hresult_error& ex)
{
OutputDebugStringW(std::format(L"[OnRenderTick] Exception: 0x{:08X}\n",
static_cast<uint32_t>(ex.code())).c_str());
}
catch (const std::exception& ex)
{
OutputDebugStringW(std::format(L"[OnRenderTick] std::exception: {}\n",
std::wstring(ex.what(), ex.what() + strlen(ex.what()))).c_str());
}
catch (...)
{
OutputDebugStringW(L"[OnRenderTick] Unknown exception\n");
}
}
// ---------------------------------------------------------------------
// RenderWorkerLoop -- render thread entry point.
//
// Runs the offscreen render path: each iteration evaluates the graph
// and draws the preview image into a double-buffered offscreen target,
// then publishes the buffer index for UI thread to blit.
// ---------------------------------------------------------------------
void MainWindow::RenderWorkerLoop(std::stop_token stop)
{
winrt::init_apartment(winrt::apartment_type::multi_threaded);
m_renderDispatcher.RegisterConsumer();
auto last = std::chrono::steady_clock::now();
while (!stop.stop_requested() && !m_renderShouldStop.load(std::memory_order_acquire))
{
m_renderDispatcher.WaitFor(std::chrono::milliseconds(16));
{
// Every MCP mutation arrives as a closure drained here. Hold the
// graph exclusively across the whole drain rather than per
// closure: RenderThreadDispatcher runs a nested DispatchSync
// inline when already on the consumer thread, which would
// self-deadlock a non-recursive mutex taken per closure.
std::unique_lock<std::shared_mutex> graphLock(m_graphMutex);
m_renderDispatcher.Drain();
}
if (stop.stop_requested() || m_renderShouldStop.load(std::memory_order_acquire))
break;
if (m_isShuttingDown) break;
if (!m_renderEngine.IsInitialized()) continue;
auto now = std::chrono::steady_clock::now();
double dt = std::chrono::duration<double>(now - last).count();
last = now;
if (dt > 0.1) dt = 0.016;
try
{
// Per-tick non-GPU work that previously lived in OnRenderTick:
// working space sync, capture/clock tick, video upload, dirty
// propagation. Then the offscreen render itself.
//
// This whole body mutates m_graph -- UpdateWorkingSpaceNodes
// writes Working Space properties, the clock tick does
// node.properties[...] = (a std::map INSERT), and the evaluator
// walks and dirties nodes. Hold the graph exclusively so the UI
// thread's canvas paint cannot read a half-mutated node. Taken
// in a separate scope from the Drain() lock above so the two
// never nest.
std::unique_lock<std::shared_mutex> graphLock(m_graphMutex);
UpdateWorkingSpaceNodes();
// Use the render-thread D2D context for source uploads. They
// create D2D bitmaps that the evaluator (also using the
// render context) will draw -- everything stays on one
// context to avoid cross-context state races.
if (auto* dc5 = static_cast<ID2D1DeviceContext5*>(m_renderEngine.RenderD2DContext()))
{
auto& nodes = const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes());
if (m_sourceFactory.TickAndUploadLiveCaptures(nodes, dc5))
m_forceRender = true;
}
// Tick clock nodes: advance time. (Same code as OnRenderTick's
// body uses; safe to call from render thread because m_graph
// is single-writer in this design.)
for (auto& node : const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes()))
{
if (!node.isClock) continue;
auto getF = [&](const std::wstring& k, float def) {
auto it = node.properties.find(k);
if (it != node.properties.end())
if (auto* f = std::get_if<float>(&it->second)) return *f;
return def;
};
bool autoDuration = getF(L"AutoDuration", 1.0f) > 0.5f;
if (autoDuration && node.propertyBindings.count(L"StopTime"))
{
autoDuration = false;
node.properties[L"AutoDuration"] = 0.0f;
}
if (autoDuration)
{
float maxDur = 0.0f;
for (const auto& other : m_graph.Nodes())
{
if (other.id == node.id) continue;
bool boundToThisClock = false;
for (const auto& [propName, binding] : other.propertyBindings)
{
for (const auto& src : binding.sources)
{
if (src && src->sourceNodeId == node.id)
{ boundToThisClock = true; break; }
}
if (boundToThisClock) break;
}
if (!boundToThisClock) continue;
for (const auto& field : other.analysisOutput.fields)
{
if (field.name == L"Duration" && field.components[0] > 0.0f)
if (field.components[0] > maxDur) maxDur = field.components[0];
}
}
if (maxDur > 0.0f)
node.properties[L"StopTime"] = maxDur;
}
if (node.isPlaying)
{
float startTime = getF(L"StartTime", 0.0f);
float stopTime = getF(L"StopTime", 10.0f);
float speed = getF(L"Speed", 1.0f);
bool loop = getF(L"Loop", 1.0f) > 0.5f;
double duration = static_cast<double>(stopTime - startTime);
if (duration <= 0.0) duration = 1.0;
node.clockTime += dt * speed;
if (loop)
{
while (node.clockTime >= duration) node.clockTime -= duration;
while (node.clockTime < 0.0) node.clockTime += duration;
}
else
{
node.clockTime = std::clamp(node.clockTime, 0.0, duration);
if (node.clockTime >= duration) node.isPlaying = false;
}
node.dirty = true;
}
}
m_graphEvaluator.ResolveSourceBindings(m_graph);
if (auto* dc = m_renderEngine.RenderD2DContext())
{
try {
m_sourceFactory.TickAndUploadVideos(
const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes()),
dc, dt);
} catch (...) {}
}
// Dirty propagation downstream.
{
std::vector<uint32_t> queue;
for (const auto& node : m_graph.Nodes())
if (node.dirty) queue.push_back(node.id);
for (size_t i = 0; i < queue.size(); ++i)
{
for (const auto* edge : m_graph.GetOutputEdges(queue[i]))
{
auto* dn = m_graph.FindNode(edge->destNodeId);
if (dn && !dn->dirty)
{
dn->dirty = true;
queue.push_back(edge->destNodeId);
}
}
}
}
bool wasForceRender = m_forceRender;
bool hasDirty = m_graph.HasDirtyNodes();
// P7: when output windows are open, force eval every frame
// so the worker keeps producing frames into their offscreen
// pairs even if no graph node is dirty (e.g. static Gamut
// Source feeding an Output node). Same gate as the legacy
// RenderFrame had.
bool hasOutputWindows = false;
{
std::scoped_lock lk(m_outputSinksMutex);
hasOutputWindows = !m_outputSinks.empty();
}
bool needsEval = hasDirty || m_needsFitPreview || m_forceRender || hasOutputWindows;
if (needsEval)
{
RenderFrameToOffscreen(dt);
m_forceRender = false;
m_frameCount.fetch_add(1, std::memory_order_relaxed);
if (hasDirty || wasForceRender)
++m_graphGeneration;
// Fit-after-eval: the selected node's cachedOutput now has
// valid bounds, so a pending fit (set by SelectPreviewNode)
// computes zoom/pan here on the worker -- worker-owned
// bounds + the UI-cached viewport, no XAML. Force one more
// frame so the fitted transform actually renders.
if (m_needsFitPreview && FitPreviewToView())
{
m_needsFitPreview = false;
m_forceRender = true;
}
}
// Publish snapshot.
const uint64_t frameGen =
m_frameGeneration.fetch_add(1, std::memory_order_release) + 1;
auto snap = ::ShaderLab::Graph::BuildGraphUiSnapshot(
m_graph, m_previewNodeId, m_graphGeneration, frameGen);
std::atomic_store(&m_uiGraphSnapshot,
std::shared_ptr<const ::ShaderLab::Graph::GraphUiSnapshot>(snap));
}
catch (const winrt::hresult_error& ex)
{
OutputDebugStringW(std::format(L"[RenderWorker] hresult: 0x{:08X}\n",
static_cast<uint32_t>(ex.code())).c_str());
}
catch (...)
{
OutputDebugStringW(L"[RenderWorker] tick exception\n");
}
}
m_renderDispatcher.Drain();
}
// -------------------------------------------------------------------------
// RenderFrameToOffscreen / BlitOffscreenToSwapChain
//
// Phase 7 split: render thread renders the preview image into a double-
// buffered offscreen D2D bitmap (no swap-chain Present); UI thread later
// blits the most recently published buffer into the SwapChainPanel-bound
// swap chain and Presents it.
//
// The two-buffer publish protocol uses m_offscreenPublishedIdx (atomic
// int32 with -1 = nothing published yet) and m_offscreenPublishedVersion
// (atomic uint64 monotonic). Render thread writes index N (where N is
// the buffer it just rendered to), then UI thread reads that index and
// blits. Render thread then writes the OTHER index next time.
// -------------------------------------------------------------------------
bool MainWindow::EnsureOffscreenUiWrappers()
{
// UI thread only: rebuild m_offscreenSourceBitmapUi[0,1] when the
// render engine's offscreen size changes (or when context is
// recreated, e.g. adapter switch).
EnsureUiD2dContext();
if (!m_uiD2dContext) return false;
uint32_t w = m_renderEngine.OffscreenWidth();
uint32_t h = m_renderEngine.OffscreenHeight();
if (w == 0 || h == 0) return false;
if (w == m_offscreenWrapperWidth && h == m_offscreenWrapperHeight &&
m_offscreenSourceBitmapUi[0] && m_offscreenSourceBitmapUi[1])
{
return true;
}
for (uint32_t i = 0; i < 2; ++i)
{
m_offscreenSourceBitmapUi[i] = nullptr;
auto* tex = m_renderEngine.OffscreenTexture(i);
if (!tex) return false;
winrt::com_ptr<IDXGISurface> surface;
if (FAILED(tex->QueryInterface(IID_PPV_ARGS(surface.put()))))
return false;
// Source-side wrapper: no TARGET option, no CANNOT_DRAW (UI uses
// it as DrawImage source). Format must match what RenderEngine
// created the textures with (scRGB FP16 by default).
const auto& fmt = m_renderEngine.ActiveFormat();
D2D1_BITMAP_PROPERTIES1 bp = D2D1::BitmapProperties1(
D2D1_BITMAP_OPTIONS_NONE,
D2D1::PixelFormat(fmt.dxgiFormat, D2D1_ALPHA_MODE_PREMULTIPLIED),
96.0f, 96.0f);
if (FAILED(m_uiD2dContext->CreateBitmapFromDxgiSurface(
surface.get(), bp, m_offscreenSourceBitmapUi[i].put())))
return false;
}
m_offscreenWrapperWidth = w;
m_offscreenWrapperHeight = h;
return true;
}
void MainWindow::RenderFrameToOffscreen(double deltaSec)
{
// Runs on render thread once that path is enabled. Currently still
// safe to call from UI thread for the inline-fallback case (the
// synchronous dispatcher mode preserves today's behaviour).
if (m_isShuttingDown) return;
if (!m_renderEngine.IsInitialized()) return;
// Pick offscreen size = swap chain back buffer size for now.
uint32_t w = m_renderEngine.BackBufferWidth();
uint32_t h = m_renderEngine.BackBufferHeight();
if (w == 0 || h == 0) return;
if (!m_renderEngine.EnsureOffscreenTargets(w, h))
return;
auto tFrameStart = std::chrono::high_resolution_clock::now();
// Pick the buffer to write to. We use the OPPOSITE of whatever was
// just published, so UI thread can keep reading the other one
// concurrently without contention.
int32_t lastPub = m_offscreenPublishedIdx.load(std::memory_order_acquire);
int32_t writeIdx = (lastPub == 0) ? 1 : 0;
// Use the render-thread-dedicated D2D context (not the default one
// -- that one is shared with capture / pixel-inspector paths that
// run on UI thread, and concurrent BeginDraw on it would put it
// into a wrong-state error mid-tick).
auto* dc = m_renderEngine.RenderD2DContext();
if (!dc) return;
auto* targetBitmap = m_renderEngine.OffscreenRenderBitmap(writeIdx);
if (!targetBitmap) return;
// ---- Source preparation + graph evaluation (same as RenderFrame) ----
for (auto& node : const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes()))
{
if (node.type == ::ShaderLab::Graph::NodeType::Source &&
(node.dirty || m_sourceFactory.GetVideoProvider(node.id)))
{
try {
m_sourceFactory.PrepareSourceNode(node, dc, deltaSec,
m_renderEngine.D3DDevice(), m_renderEngine.D3DContext());
} catch (...) {
node.runtimeError = L"Source preparation failed";
node.dirty = false;
}
}
}
auto tSourcesEnd = std::chrono::high_resolution_clock::now();
// Compute which nodes are needed (mark roots + propagate upstream).
{
for (auto& node : const_cast<std::vector<::ShaderLab::Graph::EffectNode>&>(m_graph.Nodes()))
node.needed = false;
std::vector<uint32_t> roots;
for (const auto& node : m_graph.Nodes())
{
if (node.type == ::ShaderLab::Graph::NodeType::Output)
roots.push_back(node.id);
if (node.dirty && node.customEffect.has_value() &&
node.customEffect->analysisOutputType == ::ShaderLab::Graph::AnalysisOutputType::Typed)
roots.push_back(node.id);
}
if (m_previewNodeId != 0)
roots.push_back(m_previewNodeId);
for (const auto& window : m_outputWindows)
roots.push_back(window->NodeId());
std::unordered_set<uint32_t> visited;
std::vector<uint32_t> queue = roots;
while (!queue.empty())
{
uint32_t id = queue.back();
queue.pop_back();
if (visited.count(id)) continue;
visited.insert(id);
auto* node = m_graph.FindNode(id);
if (node) node->needed = true;
for (const auto* edge : m_graph.GetInputEdges(id))
queue.push_back(edge->sourceNodeId);
if (node)
{
for (const auto& [propName, binding] : node->propertyBindings)
{
if (binding.wholeArray)
queue.push_back(binding.wholeArraySourceNodeId);
for (const auto& src : binding.sources)
if (src.has_value()) queue.push_back(src->sourceNodeId);
}
}
}
}
m_graphEvaluator.Evaluate(m_graph, dc);
if (m_graph.HasDirtyNodes())
m_graphEvaluator.Evaluate(m_graph, dc); // second pass for new effects
auto tEvalEnd = std::chrono::high_resolution_clock::now();
// ---- BeginDraw on offscreen + ProcessDeferredCompute + draw preview --
winrt::com_ptr<ID2D1Image> oldTarget;
dc->GetTarget(oldTarget.put());
dc->SetTarget(targetBitmap);
dc->BeginDraw();
// CPU-analysis interest set (same as old RenderFrame).
{
std::unordered_set<uint32_t> interest;
if (m_selectedNodeId != 0)
{
interest.insert(m_selectedNodeId);
if (auto* sel = m_graph.FindNode(m_selectedNodeId))
{
for (const auto& [propName, binding] : sel->propertyBindings)
{
if (binding.wholeArray)
interest.insert(binding.wholeArraySourceNodeId);
for (const auto& srcOpt : binding.sources)
if (srcOpt.has_value())
interest.insert(srcOpt->sourceNodeId);
}
}
}
m_graphEvaluator.SetCpuAnalysisInterest(std::move(interest));
}
if (m_graphEvaluator.ProcessDeferredCompute(m_graph, dc))
{
m_nodeGraphController.SetNeedsRedraw();
if (m_graph.HasDirtyNodes())
{
m_graphEvaluator.SetDeferredComputeFrozen(true);
m_graphEvaluator.Evaluate(m_graph, dc);
m_graphEvaluator.SetDeferredComputeFrozen(false);
}
}
auto tComputeEnd = std::chrono::high_resolution_clock::now();
uint32_t computeCount = static_cast<uint32_t>(m_graphEvaluator.DeferredComputeCount());
// Set DPI to 96 to match WinUI DIPs — but only when the context
// isn't already there: a real per-frame DPI flip invalidates every
// D2D1_PROPERTY_CACHED effect intermediate in the context. The
// render context is pinned at 96 (RenderEngine), so this is
// normally a no-op kept as a safety net.
float oldDpiX, oldDpiY;
dc->GetDpi(&oldDpiX, &oldDpiY);
const bool dpiFlip = (oldDpiX != 96.0f || oldDpiY != 96.0f);
if (dpiFlip)
dc->SetDpi(96.0f, 96.0f);
dc->Clear(D2D1::ColorF(D2D1::ColorF::Black));
D2D1_MATRIX_3X2_F previewTransform =
D2D1::Matrix3x2F::Scale(m_previewZoom, m_previewZoom) *
D2D1::Matrix3x2F::Translation(m_previewPanX, m_previewPanY);
dc->SetTransform(previewTransform);
auto* previewImage = ResolveDisplayImage(m_previewNodeId);
if (previewImage)
dc->DrawImage(previewImage);
dc->SetTransform(D2D1::Matrix3x2F::Identity());
if (dpiFlip)
dc->SetDpi(oldDpiX, oldDpiY);
auto tDrawEnd = std::chrono::high_resolution_clock::now();
HRESULT hrEnd = dc->EndDraw();
dc->SetTarget(oldTarget.get());
auto tEndDraw = std::chrono::high_resolution_clock::now();
// Always bump framesSampled BEFORE deciding whether to publish, so
// /perf accurately reflects worker activity even when EndDraw fails
// (device-lost, transient state, etc.). Without this, a single
// EndDraw glitch would freeze the displayed FPS at a stale value.
{
auto usec = [](auto a, auto b) {
return std::chrono::duration<double, std::micro>(b - a).count();
};
const double a = 0.1;
auto& t = m_frameTiming;
t.sourcesPrepUs = t.sourcesPrepUs * (1-a) + usec(tFrameStart, tSourcesEnd) * a;
t.evaluateUs = t.evaluateUs * (1-a) + usec(tSourcesEnd, tEvalEnd) * a;
t.deferredComputeUs = t.deferredComputeUs * (1-a) + usec(tEvalEnd, tComputeEnd) * a;
t.drawUs = t.drawUs * (1-a) + usec(tComputeEnd, tDrawEnd) * a;
t.endDrawFlushUs = t.endDrawFlushUs * (1-a) + usec(tDrawEnd, tEndDraw) * a;
t.computeDispatches = computeCount;
t.totalUs = t.totalUs * (1-a) + usec(tFrameStart, tEndDraw) * a;
t.framesSampled++;
t.endDrawFailed = FAILED(hrEnd) ? (t.endDrawFailed + 1) : t.endDrawFailed;
if (t.framesSampled % 30 == 0)
m_lastFrameTiming = t;
}
if (FAILED(hrEnd))
return;
// Publish: store this buffer's index with release semantics so the
// UI thread sees a fully-rendered frame before reading.
m_offscreenPublishedIdx.store(writeIdx, std::memory_order_release);
m_offscreenPublishedVersion.fetch_add(1, std::memory_order_release);
// P7: render any open output windows into THEIR offscreen pairs.
// Each sink has its own double-buffered offscreen managed by this
// method. UI thread blits the published buffer in BlitAndPresent.
RenderOutputSinks();
}
// ---------------------------------------------------------------------
// RenderOutputSinks -- render-thread output-window rendering. Iterates
// a snapshot of m_outputSinks (so we don't hold m_outputSinksMutex while
// doing GPU work), and for each non-closed sink:
// - reads view state under sink->viewMutex
// - ensures buffers exist at requested size (creates D3D textures +
// render-side D2D bitmap targets, bumps bufferGen on size change)
// - resolves the node's cachedOutput
// - picks the write idx (opposite of publishedIdx)
// - BeginDraw on render-side bitmap, Clear, apply pan/zoom transform,
// DrawImage, EndDraw
// - publishes the new idx + version
// The actual blit-to-swap-chain + Present1 happens on the UI thread.
// ---------------------------------------------------------------------
void MainWindow::RenderOutputSinks()
{
std::vector<std::shared_ptr<::ShaderLab::Controls::OutputSinkRenderState>> snapshot;
{
std::scoped_lock lock(m_outputSinksMutex);
snapshot = m_outputSinks;
}
if (snapshot.empty()) return;
auto* dc = m_renderEngine.RenderD2DContext();
auto* d3dDevice = m_renderEngine.D3DDevice();
if (!dc || !d3dDevice) return;
const auto& fmt = m_renderEngine.ActiveFormat();
for (auto& sink : snapshot)
{
if (!sink) continue;
bool closed = false;
{
std::scoped_lock lock(sink->viewMutex);
closed = sink->closed;
}
if (closed) continue;
// Resolve the source image (the node's cachedOutput).
auto* image = ResolveDisplayImage(sink->nodeId);
if (!image) continue;
// Get the image's natural bounds in DIPs at 96 DPI.
float oldDpiX, oldDpiY;
dc->GetDpi(&oldDpiX, &oldDpiY);
dc->SetDpi(96.0f, 96.0f);
D2D1_RECT_F bounds{};
HRESULT bhr = dc->GetImageLocalBounds(image, &bounds);
if (FAILED(bhr))
{
dc->SetDpi(oldDpiX, oldDpiY);
continue;
}
uint32_t imgW = static_cast<uint32_t>(bounds.right - bounds.left);
uint32_t imgH = static_cast<uint32_t>(bounds.bottom - bounds.top);
if (imgW == 0 || imgH == 0)
{
dc->SetDpi(oldDpiX, oldDpiY);
continue;
}
// Cap to a sensible max so a runaway-bounds source can't OOM
// us. 8192 matches the per-effect cap in PreRenderInputBitmap.
imgW = (std::min)(imgW, 8192u);
imgH = (std::min)(imgH, 8192u);
// Allocate the offscreen at the IMAGE's native size. This
// keeps the render path stateless about the panel's display
// size / DPI -- UI's BlitAndPresent does the fit when blitting
// into the swap chain back buffer (which it knows the size of
// first-hand). Avoids the cross-thread DPI/scale math that
// produced misaligned output earlier.
if (sink->bufW != imgW || sink->bufH != imgH ||
!sink->textures[0] || !sink->textures[1])
{
D3D11_TEXTURE2D_DESC td{};
td.Width = imgW;
td.Height = imgH;
td.MipLevels = 1;
td.ArraySize = 1;
td.Format = fmt.dxgiFormat;
td.SampleDesc.Count = 1;
td.Usage = D3D11_USAGE_DEFAULT;
td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
bool ok = true;
for (uint32_t i = 0; i < 2 && ok; ++i)
{
sink->renderTargets[i] = nullptr;
sink->textures[i] = nullptr;
if (FAILED(d3dDevice->CreateTexture2D(&td, nullptr,
sink->textures[i].put())))
{ ok = false; break; }
winrt::com_ptr<IDXGISurface> surface;
if (FAILED(sink->textures[i]->QueryInterface(
IID_PPV_ARGS(surface.put()))))
{ ok = false; break; }
D2D1_BITMAP_PROPERTIES1 bp = D2D1::BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
D2D1::PixelFormat(fmt.dxgiFormat,
D2D1_ALPHA_MODE_PREMULTIPLIED),
96.0f, 96.0f);
if (FAILED(dc->CreateBitmapFromDxgiSurface(
surface.get(), bp, sink->renderTargets[i].put())))
{ ok = false; break; }
}
if (!ok)
{
for (uint32_t i = 0; i < 2; ++i)
{
sink->renderTargets[i] = nullptr;
sink->textures[i] = nullptr;
}
sink->bufW = sink->bufH = 0;
dc->SetDpi(oldDpiX, oldDpiY);
continue;
}
sink->bufW = imgW;
sink->bufH = imgH;
sink->bufferGen.fetch_add(1, std::memory_order_release);
}
// Pick write idx = opposite of last published.
int32_t lastPub = sink->publishedIdx.load(std::memory_order_acquire);
int32_t writeIdx = (lastPub == 0) ? 1 : 0;
auto* target = sink->renderTargets[writeIdx].get();
if (!target)
{
dc->SetDpi(oldDpiX, oldDpiY);
continue;
}
winrt::com_ptr<ID2D1Image> prevTarget;
dc->GetTarget(prevTarget.put());
dc->SetTarget(target);
dc->SetTransform(D2D1::Matrix3x2F::Translation(-bounds.left, -bounds.top));
dc->BeginDraw();
dc->Clear(D2D1::ColorF(D2D1::ColorF::Black));
dc->DrawImage(image);
dc->SetTransform(D2D1::Matrix3x2F::Identity());
HRESULT hr = dc->EndDraw();
dc->SetTarget(prevTarget.get());
dc->SetDpi(oldDpiX, oldDpiY);
if (FAILED(hr)) continue;
sink->publishedIdx.store(writeIdx, std::memory_order_release);
sink->publishedVersion.fetch_add(1, std::memory_order_release);
}
}
void MainWindow::BlitOffscreenToSwapChain()
{
// UI thread only. Blits the latest published offscreen buffer to the
// SwapChainPanel-bound swap chain via a UI-side D2D context that shares
// the engine's multi-threaded D2D device.
if (m_isShuttingDown) return;
if (!m_renderEngine.IsInitialized()) return;
if (!EnsureOffscreenUiWrappers()) return;
int32_t idx = m_offscreenPublishedIdx.load(std::memory_order_acquire);
if (idx < 0 || idx > 1) return;
// Skip blit when there's no new published frame since last UI tick.
// Without this the UI thread vsync-waits in Present1(1, 0) on EVERY
// 16 ms tick (60 Hz) even when the worker is producing frames at,
// say, 10 Hz. Each Present1 wait blocks input event delivery, so
// dropdowns / hover highlights get starved during heavy graph eval.
// The compositor keeps showing the last presented frame on its own;
// we only need to re-Present when the worker has actually published
// a new offscreen.
uint64_t version = m_offscreenPublishedVersion.load(std::memory_order_acquire);
if (version == m_lastBlittedVersion) return;
m_lastBlittedVersion = version;
auto* sourceBitmap = m_offscreenSourceBitmapUi[idx].get();
if (!sourceBitmap) return;
auto* swap = m_renderEngine.SwapChain();
if (!swap) return;
winrt::com_ptr<IDXGISurface> backBuffer;
HRESULT hr = swap->GetBuffer(0, IID_PPV_ARGS(backBuffer.put()));
if (FAILED(hr)) return;
const auto& fmt = m_renderEngine.ActiveFormat();
D2D1_BITMAP_PROPERTIES1 bp = D2D1::BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
D2D1::PixelFormat(fmt.dxgiFormat, D2D1_ALPHA_MODE_PREMULTIPLIED),
96.0f, 96.0f);
winrt::com_ptr<ID2D1Bitmap1> backBufferBitmap;
hr = m_uiD2dContext->CreateBitmapFromDxgiSurface(
backBuffer.get(), bp, backBufferBitmap.put());
if (FAILED(hr)) return;
m_uiD2dContext->SetTarget(backBufferBitmap.get());
m_uiD2dContext->BeginDraw();
m_uiD2dContext->Clear(D2D1::ColorF(D2D1::ColorF::Black));
m_uiD2dContext->DrawImage(sourceBitmap);
hr = m_uiD2dContext->EndDraw();
m_uiD2dContext->SetTarget(nullptr);
if (FAILED(hr)) return;
DXGI_PRESENT_PARAMETERS params{};
swap->Present1(1, 0, ¶ms);
}
}