-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
2930 lines (2501 loc) · 119 KB
/
MainWindow.xaml.cs
File metadata and controls
2930 lines (2501 loc) · 119 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using System.Runtime.InteropServices;
using WinRT;
using GlobalStructures;
using static GlobalStructures.GlobalTools;
using Windows.Graphics.Capture;
using DXGI;
using Direct2D;
using static DXGI.DXGITools;
using WebView2;
using static WebView2.WebView2Tools;
using D3D11;
using System.Text;
using System.Text.Json;
using System.ComponentModel;
using WIC;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace WinUI3_SwapChainPanel_WebView2
{
/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainWindow : Window
{
[DllImport("CoreMessaging.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern HRESULT CreateDispatcherQueueController(DispatcherQueueOptions options, /*PDISPATCHERQUEUECONTROLLER**/ [MarshalAs(UnmanagedType.IUnknown)] out object dispatcherQueueController);
public enum DISPATCHERQUEUE_THREAD_TYPE
{
DQTYPE_THREAD_DEDICATED = 1,
DQTYPE_THREAD_CURRENT = 2,
};
public enum DISPATCHERQUEUE_THREAD_APARTMENTTYPE
{
DQTAT_COM_NONE = 0,
DQTAT_COM_ASTA = 1,
DQTAT_COM_STA = 2
};
[StructLayout(LayoutKind.Sequential)]
public struct DispatcherQueueOptions
{
public uint dwSize;
public DISPATCHERQUEUE_THREAD_TYPE threadType;
public DISPATCHERQUEUE_THREAD_APARTMENTTYPE apartmentType;
}
[DllImport("d3d11.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern HRESULT CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgiDevice, out IntPtr graphicsDevice);
[ComImport]
[Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDirect3DDxgiInterfaceAccess
{
HRESULT GetInterface([MarshalAs(UnmanagedType.LPStruct)] Guid iid, out IntPtr ppv);
}
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
private static Windows.UI.Composition.Compositor? m_WindowsCompositor;
//private static Windows.UI.Composition.ContainerVisual? m_RootVisual;
private static Windows.UI.Composition.ContainerVisual? m_WebView2Visual;
private static Windows.System.DispatcherQueue? m_DispatcherQueue;
ID2D1Factory m_pD2DFactory = null;
ID2D1Factory1 m_pD2DFactory1 = null;
IWICImagingFactory m_pWICImagingFactory = null;
IWICImagingFactory2 m_pWICImagingFactory2 = null;
Windows.Graphics.DirectX.Direct3D11.IDirect3DDevice m_pDirect3DDevice = null;
ID3D11Device m_pD3D11Device= null;
IntPtr m_pD3D11DevicePtr = IntPtr.Zero;
D3D11.ID3D11DeviceContext m_pD3D11DeviceContext = null;
IntPtr m_pD3D11DeviceContextPtr = IntPtr.Zero;
IDXGIDevice1 m_pDXGIDevice = null;
ID2D1Device m_pD2DDevice = null; // Released in CreateDeviceContextAndDirect3DDevice
ID2D1DeviceContext m_pD2DDeviceContext = null;
IDXGISwapChain1 m_pDXGISwapChain1 = null;
ID2D1Bitmap1 m_pD2DTargetBitmap = null;
ID2D1Bitmap m_pD2DBitmap1 = null;
Direct3D11CaptureFramePool m_captureFramePool = null;
GraphicsCaptureSession m_captureSession = null;
private IntPtr hWndMain = IntPtr.Zero;
int m_nWebView2Width = 900, m_nWebView2Height = 900;
public MainWindow()
{
this.InitializeComponent();
hWndMain = WinRT.Interop.WindowNative.GetWindowHandle(this);
InitializeWindowsComposition(hWndMain);
this.Title = "WinUI 3 : Composited WebView2 rendered with SwapChainPanel";
Application.Current.Resources["ButtonBackgroundPointerOver"] = new SolidColorBrush(Microsoft.UI.Colors.SteelBlue);
Application.Current.Resources["ButtonBackgroundPressed"] = new SolidColorBrush(Microsoft.UI.Colors.LightSteelBlue);
m_pWICImagingFactory = (IWICImagingFactory)Activator.CreateInstance(Type.GetTypeFromCLSID(WICTools.CLSID_WICImagingFactory));
m_pWICImagingFactory2 = (IWICImagingFactory2)m_pWICImagingFactory;
HRESULT hr = CreateD2D1Factory();
if (SUCCEEDED(hr))
{
CreateDeviceContextAndDirect3DDevice();
hr = CreateSwapChain(IntPtr.Zero);
if (SUCCEEDED(hr))
{
hr = ConfigureSwapChain(hWndMain);
ISwapChainPanelNative panelNative = WinRT.CastExtensions.As<ISwapChainPanelNative>(scp1);
hr = panelNative.SetSwapChain(m_pDXGISwapChain1);
scp1.SizeChanged += Scp1_SizeChanged;
scp1.Loaded += Scp1_Loaded;
}
// Too slow for Direct3D, at least on my old PC :
// Intel Pentium G3260 3300 MHz
// Intel® HD Graphics : Intel Xeon E3-1200 v3/4th Gen Core Processor Integrated Graphics Controller
// Monitor Philips 247ELH PHLC085, 60-75 Hz
// CompositionTarget.Rendering += CompositionTarget_Rendering;
}
// Define JSON file path in LocalAppData
string sFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WebView2");
Directory.CreateDirectory(sFolder);
// C:\Users\Christian\AppData\Local\WebView2\url_history.json
m_sHistoryFile = Path.Combine(sFolder, "url_history.json");
LoadHistory();
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.AboveNormal;
this.Closed += MainWindow_Closed;
}
private async void Scp1_Loaded(object sender, RoutedEventArgs e)
{
HRESULT hr = HRESULT.S_OK;
var options = new CoreWebView2EnvironmentOptionsClass
{
AdditionalArgs = "--enable-features=OverlayScrollbar,OverlayScrollbarWinStyle,OverlayScrollbarWinStyleAnimation", // default ?
Language = "en-US", // MSDN : It applies to browser UIs such as context menu and dialogs. It also applies to the accept-languages HTTP header that WebView sends to websites
//TargetVersion = "123.0.0.0",
//TargetVersion = "142.0.3595.90",
TargetVersion = "144.0.3712.0",
AllowSSO = true
};
// To get first Canary Runtime
//options.ChannelSearchKind = COREWEBVIEW2_CHANNEL_SEARCH_KIND.COREWEBVIEW2_CHANNEL_SEARCH_KIND_LEAST_STABLE;
IntPtr pOptions = Marshal.GetIUnknownForObject(options);
hr = CreateCoreWebView2EnvironmentWithOptions(null, null, pOptions, new EnvironmentCompletedHandler(this, hWndMain));
if (!SUCCEEDED(hr))
{
string sError = "Could not create CoreWebView2" + "\r\n" + "HRESULT = 0x" + string.Format("{0:X}", hr) + "\r\n" + Marshal.GetExceptionForHR((int)hr)?.Message;
Windows.UI.Popups.MessageDialog md = new Windows.UI.Popups.MessageDialog(sError, "Error");
WinRT.Interop.InitializeWithWindow.Initialize(md, hWndMain);
_ = await md.ShowAsync();
}
Marshal.Release(pOptions);
}
private class EnvironmentCompletedHandler : ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler
{
private readonly MainWindow _owner;
private readonly IntPtr _hWnd;
public EnvironmentCompletedHandler(MainWindow owner, IntPtr hWnd)
{
_owner = owner;
_hWnd = hWnd;
}
public HRESULT Invoke(HRESULT result, ICoreWebView2Environment environment)
{
HRESULT hr = HRESULT.S_OK;
System.Diagnostics.Debug.WriteLine("WebView2 environment created");
var env3 = environment as ICoreWebView2Environment3;
if (env3 != null)
{
var env10 = (ICoreWebView2Environment10)env3;
// C:\Program Files (x86)\Microsoft\EdgeWebView\Application
// 145.0.3770.0 canary
hr = env3.get_BrowserVersionString(out string sVersion);
hr = env10.CreateCoreWebView2ControllerOptions(out ICoreWebView2ControllerOptions options);
var options4 = (ICoreWebView2ControllerOptions4)options;
hr = options4.get_AllowHostInputProcessing(out bool bHIP); // false
//hr = options4.put_AllowHostInputProcessing(true);
hr = options4.get_DefaultBackgroundColor(out COREWEBVIEW2_COLOR color);
// DimGray
//color.R = 0x69;
//color.G = 0x69;
//color.B = 0x69;
// MidnightBlue
color.R = 0x19;
color.G = 0x19;
color.B = 0x70;
//color.A = 255;
color.A = 0; // Transparent
hr = options4.put_DefaultBackgroundColor(color);
hr = env10.CreateCoreWebView2CompositionControllerWithOptions(_hWnd, options4, new CompositionControllerCompletedHandler(_owner, _hWnd));
SafeRelease(ref env10);
SafeRelease(ref options4);
}
else
{
System.Diagnostics.Debug.WriteLine("Environment does not support composition controller");
}
return hr;
}
}
private static void AttachWebViewToVisualTree(Windows.UI.Composition.ContainerVisual? containerVisual)
{
if (containerVisual != null && m_pCompositionController != null)
{
IntPtr pUnknown = Marshal.GetIUnknownForObject(containerVisual);
m_pCompositionController.put_RootVisualTarget(pUnknown);
Marshal.Release(pUnknown);
}
}
private static ICoreWebView2CompositionController? m_pCompositionController = null;
private static ICoreWebView2Controller2? m_pController2 = null;
private static ICoreWebView2? m_pCoreWebView2 = null;
private class CompositionControllerCompletedHandler : ICoreWebView2CreateCoreWebView2CompositionControllerCompletedHandler
{
private readonly MainWindow _owner;
private readonly IntPtr _hWnd;
public CompositionControllerCompletedHandler(MainWindow owner, IntPtr hWnd)
{
_owner = owner;
_hWnd = hWnd;
}
public HRESULT Invoke(HRESULT result, ICoreWebView2CompositionController compositionController)
{
HRESULT hr = HRESULT.S_OK;
if (compositionController != null)
{
System.Diagnostics.Debug.WriteLine("Composition controller created");
m_pCompositionController = compositionController;
ICoreWebView2Controller controller = (ICoreWebView2Controller)compositionController;
m_pController2 = (ICoreWebView2Controller2)controller;
hr = m_pController2.put_IsVisible(true);
hr = m_pController2.get_CoreWebView2(out m_pCoreWebView2);
// If no history, pre-load a url/video (actually "Guru Josh Project - Infinity 2008")
if (_owner.m_History.Count == 0)
{
//_owner.tbURL.Text = "http://www.google.com";
//_owner.tbURL.Text = "https://www.yout-ube.com/watch?v=DvyCbevQbtI&list=RDDvyCbevQbtI&iv_load_policy=3&loop=1&start=";
_owner.tbURL.Text = "https://www.yout-ube.com/watch?v=jzy2dgEUOhY&autoplay=1&iv_load_policy=3&loop=1&start=";
//string sURL = _owner.NormalizeUrl(_owner.tbURL.Text);
//hr = m_pCoreWebView2.Navigate(sURL);
}
AttachWebViewToVisualTree(m_WebView2Visual);
var c4 = (ICoreWebView2Controller4)m_pController2;
hr = c4.get_AllowExternalDrop(out bool bDrop); // true
hr = c4.get_BoundsMode(out COREWEBVIEW2_BOUNDS_MODE nBounsMode);
//hr = c4.put_BoundsMode(COREWEBVIEW2_BOUNDS_MODE.COREWEBVIEW2_BOUNDS_MODE_USE_RASTERIZATION_SCALE);
hr = m_pController2.get_Bounds(out RECT rcBounds);
if (SUCCEEDED(hr))
{
if (_owner.tsRender3D.IsOn)
{
if (m_WebView2Visual != null)
{
rcBounds.left = (int)m_WebView2Visual.Offset.X;
rcBounds.top = (int)m_WebView2Visual.Offset.Y;
rcBounds.right = (int)(m_WebView2Visual.Offset.X + m_WebView2Visual.Size.X);
rcBounds.bottom = (int)(m_WebView2Visual.Offset.Y + m_WebView2Visual.Size.Y);
hr = m_pController2.put_Bounds(rcBounds);
}
}
else
{
if (m_WebView2Visual != null)
{
m_WebView2Visual.Size = new System.Numerics.Vector2((float)_owner.scp1.ActualWidth, (float)_owner.scp1.ActualHeight);
rcBounds.left = (int)m_WebView2Visual.Offset.X;
rcBounds.top = (int)m_WebView2Visual.Offset.Y;
rcBounds.right = (int)(m_WebView2Visual.Offset.X + m_WebView2Visual.Size.X);
rcBounds.bottom = (int)(m_WebView2Visual.Offset.Y + m_WebView2Visual.Size.Y);
hr = m_pController2.put_Bounds(rcBounds);
}
}
}
//var cursorHandler = new CoreWebView2CursorChangedEventHandler(_hWnd);
//hr = m_pCompositionController.add_CursorChanged(cursorHandler, out EventRegistrationToken _);
}
else
{
System.Diagnostics.Debug.WriteLine("Failed to create Composition controller");
}
return hr;
}
}
// Vertex structure
[StructLayout(LayoutKind.Sequential)]
struct Vertex
{
public System.Numerics.Vector3 Position;
public System.Numerics.Vector2 TexCoord;
}
// Cube vertex buffer
Vertex[] cubeVertices = new Vertex[]
{
// Front face
new() { Position = new(-1, -1, -1), TexCoord = new(0,1) },
new() { Position = new(-1, 1, -1), TexCoord = new(0,0) },
new() { Position = new( 1, 1, -1), TexCoord = new(1,0) },
new() { Position = new( 1, -1, -1), TexCoord = new(1,1) },
// Back face
new() { Position = new( 1, -1, 1), TexCoord = new(0,1) },
new() { Position = new( 1, 1, 1), TexCoord = new(0,0) },
new() { Position = new(-1, 1, 1), TexCoord = new(1,0) },
new() { Position = new(-1, -1, 1), TexCoord = new(1,1) },
// Left face
new() { Position = new(-1, -1, 1), TexCoord = new(0,1) },
new() { Position = new(-1, 1, 1), TexCoord = new(0,0) },
new() { Position = new(-1, 1, -1), TexCoord = new(1,0) },
new() { Position = new(-1, -1, -1), TexCoord = new(1,1) },
// Right face
new() { Position = new( 1, -1, -1), TexCoord = new(0,1) },
new() { Position = new( 1, 1, -1), TexCoord = new(0,0) },
new() { Position = new( 1, 1, 1), TexCoord = new(1,0) },
new() { Position = new( 1, -1, 1), TexCoord = new(1,1) },
// Top face
new() { Position = new(-1, 1, -1), TexCoord = new(0,1) },
new() { Position = new(-1, 1, 1), TexCoord = new(0,0) },
new() { Position = new( 1, 1, 1), TexCoord = new(1,0) },
new() { Position = new( 1, 1, -1), TexCoord = new(1,1) },
// Bottom face
new() { Position = new(-1, -1, 1), TexCoord = new(0,1) },
new() { Position = new(-1, -1, -1), TexCoord = new(0,0) },
new() { Position = new( 1, -1, -1), TexCoord = new(1,0) },
new() { Position = new( 1, -1, 1), TexCoord = new(1,1) },
};
// Cube indices
ushort[] cubeIndices = new ushort[]
{
0,1,2, 0,2,3,
4,5,6, 4,6,7,
8,9,10, 8,10,11,
12,13,14, 12,14,15,
16,17,18, 16,18,19,
20,21,22, 20,22,23
};
D3D11.ID3D11Buffer? m_cubeVertexBuffer;
D3D11.ID3D11Buffer? m_cubeIndexBuffer;
D3D11.ID3D11Buffer? m_constantBuffer;
D3D11.ID3D11RasterizerState? m_rs;
// To draw cube edges (not visible if uniform background)
D3D11.ID3D11Buffer? m_edgeVertexBuffer;
D3D11.ID3D11Buffer? m_edgeIndexBuffer;
D3D11.ID3D11PixelShader? m_psEdge;
D3D11.ID3D11DepthStencilState? m_dsEdges;
// Edge vertex layout must match Vertex struct (Position, TexCoord).
// TexCoord are unused for edges — set to zero.
Vertex[] edgeVertices = new Vertex[]
{
new() { Position = new(-1f, -1f, -1f), TexCoord = new(0,0) }, // 0
new() { Position = new( 1f, -1f, -1f), TexCoord = new(0,0) }, // 1
new() { Position = new( 1f, 1f, -1f), TexCoord = new(0,0) }, // 2
new() { Position = new(-1f, 1f, -1f), TexCoord = new(0,0) }, // 3
new() { Position = new(-1f, -1f, 1f), TexCoord = new(0,0) }, // 4
new() { Position = new( 1f, -1f, 1f), TexCoord = new(0,0) }, // 5
new() { Position = new( 1f, 1f, 1f), TexCoord = new(0,0) }, // 6
new() { Position = new(-1f, 1f, 1f), TexCoord = new(0,0) } // 7
};
// 12 edges, each as a pair of vertex indices
ushort[] edgeIndices = new ushort[]
{
0,1, 1,2, 2,3, 3,0, // front rectangle (-z)
4,5, 5,6, 6,7, 7,4, // back rectangle (+z)
0,4, 1,5, 2,6, 3,7 // vertical edges
};
// Render targets
D3D11.ID3D11RenderTargetView? m_rtv;
D3D11.ID3D11DepthStencilView? m_dsv;
// Pipeline
D3D11.ID3D11VertexShader? m_cubeVS;
D3D11.ID3D11PixelShader? m_cubePS;
D3D11.ID3D11InputLayout? m_inputLayout;
D3D11.ID3D11SamplerState? m_sampler;
[StructLayout(LayoutKind.Sequential)]
public struct CBMVP
{
public float m11, m12, m13, m14;
public float m21, m22, m23, m24;
public float m31, m32, m33, m34;
public float m41, m42, m43, m44;
}
// Swirl
D3D11.ID3D11VertexShader? m_swirlVS;
D3D11.ID3D11PixelShader? m_swirlPS;
D3D11.ID3D11Buffer? m_cbTime;
// Paper
[StructLayout(LayoutKind.Sequential)]
struct PaperCB
{
public System.Numerics.Matrix4x4 WorldViewProj;
public float Theta;
public System.Numerics.Vector3 Padding; // 16-byte alignment
}
D3D11.ID3D11Buffer? m_paperVertexBuffer;
D3D11.ID3D11Buffer? m_paperIndexBuffer;
D3D11.ID3D11Buffer? m_paperConstantBuffer;
D3D11.ID3D11VertexShader? m_paperVS;
D3D11.ID3D11PixelShader? m_paperPS;
uint m_paperIndexCount;
// Tunnel
[StructLayout(LayoutKind.Sequential)]
struct TunnelVertex
{
public System.Numerics.Vector3 Position;
public System.Numerics.Vector3 Normal;
public System.Numerics.Vector2 UV;
}
D3D11.ID3D11Buffer? m_tunnelVB;
D3D11.ID3D11Buffer? m_tunnelIB;
D3D11.ID3D11Buffer? m_tunnelConstantBuffer;
D3D11.ID3D11VertexShader? m_tunnelVS;
D3D11.ID3D11PixelShader? m_tunnelPS;
D3D11.ID3D11InputLayout? m_tunnelInputLayout;
D3D11.ID3D11SamplerState? m_samplerWrap;
int m_nTunnelIndexCount;
[StructLayout(LayoutKind.Sequential)]
struct TunnelCB
{
public System.Numerics.Matrix4x4 World;
public System.Numerics.Matrix4x4 ViewProj;
public float Time;
public float Twist;
public float FadeStart;
public float FadeEnd;
public float DepthSpeed;
public System.Numerics.Vector3 Padding; // alignment
}
D3D11.ID3D11ShaderResourceView? m_tunnelSRV;
private Direct2D.ID3D11Texture2D GetTexture2D(Windows.Graphics.DirectX.Direct3D11.IDirect3DSurface surface)
{
var pAccess = surface.As<IDirect3DDxgiInterfaceAccess>();
Guid iid = typeof(Direct2D.ID3D11Texture2D).GUID;
pAccess.GetInterface(iid, out IntPtr ptexPtr);
var texture = (Direct2D.ID3D11Texture2D)Marshal.GetObjectForIUnknown(ptexPtr);
Marshal.Release(ptexPtr);
return texture;
}
D3D11.ID3D11ShaderResourceView? m_captureSRV;
void CreateOrUpdateSRV(Direct2D.ID3D11Texture2D texture)
{
texture.GetDesc(out var desc);
if (m_captureSRV != null && desc.Width == m_nRenderWidth && desc.Height == m_nRenderHeight)
return;
SafeRelease(ref m_captureSRV);
var srvDesc = new D3D11.D3D11_SHADER_RESOURCE_VIEW_DESC
{
Format = desc.Format,
ViewDimension = D3D11.D3D11_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE2D,
};
srvDesc.Anonymous.Texture2D = new D3D11.D3D11_TEX2D_SRV
{
MipLevels = 1,
MostDetailedMip = 0
};
m_pD3D11Device.CreateShaderResourceView((D3D11.ID3D11Resource)texture, ref srvDesc, out m_captureSRV);
}
HRESULT CreateRenderTargetView()
{
Guid iid = typeof(D3D11.ID3D11Texture2D).GUID;
HRESULT hr = m_pDXGISwapChain1.GetBuffer(0, ref iid, out IntPtr backBufferPtr);
if (SUCCEEDED(hr))
{
var backBuffer = (D3D11.ID3D11Texture2D)Marshal.GetObjectForIUnknown(backBufferPtr);
hr = m_pD3D11Device.CreateRenderTargetView(backBuffer, IntPtr.Zero, out m_rtv);
SafeRelease(ref backBuffer);
Marshal.Release(backBufferPtr);
}
return hr;
}
HRESULT CreateDepthStencilView(int nWidth, int nHeight)
{
D3D11.D3D11_TEXTURE2D_DESC depthDesc = new()
{
Width = (uint)nWidth,
Height = (uint)nHeight,
MipLevels = 1,
ArraySize = 1,
Format = DXGI_FORMAT.DXGI_FORMAT_D24_UNORM_S8_UINT,
SampleDesc = new DXGI_SAMPLE_DESC { Count = 1, Quality = 0 },
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_DEPTH_STENCIL
};
HRESULT hr = m_pD3D11Device.CreateTexture2D(ref depthDesc, IntPtr.Zero, out D3D11.ID3D11Texture2D pDepthTexture);
if (SUCCEEDED(hr))
{
hr = m_pD3D11Device.CreateDepthStencilView(pDepthTexture, IntPtr.Zero, out m_dsv);
SafeRelease(ref pDepthTexture);
}
return hr;
}
private async void btnCaptureRender_Click(object sender, RoutedEventArgs e)
{
if (m_pCoreWebView2 != null)
{
// Vertex/Pixel Shaders done with help from ChatGPT...
HRESULT hr = HRESULT.S_OK;
// Create vertex buffer
D3D11.D3D11_BUFFER_DESC vbDesc = new()
{
ByteWidth = (uint)(Marshal.SizeOf<Vertex>() * cubeVertices.Length),
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_VERTEX_BUFFER,
};
D3D11_SUBRESOURCE_DATA vbData = new() { pSysMem = Marshal.UnsafeAddrOfPinnedArrayElement(cubeVertices, 0) };
IntPtr pVerticesData = Marshal.AllocHGlobal(Marshal.SizeOf(vbData));
Marshal.StructureToPtr(vbData, pVerticesData, false);
hr = m_pD3D11Device.CreateBuffer(ref vbDesc, pVerticesData, out m_cubeVertexBuffer);
Marshal.FreeHGlobal(pVerticesData);
// Create index buffer
D3D11.D3D11_BUFFER_DESC ibDesc = new()
{
ByteWidth = (uint)(sizeof(ushort) * cubeIndices.Length),
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_INDEX_BUFFER,
};
D3D11_SUBRESOURCE_DATA ibData = new() { pSysMem = Marshal.UnsafeAddrOfPinnedArrayElement(cubeIndices, 0) };
IntPtr pIndicesData = Marshal.AllocHGlobal(Marshal.SizeOf(ibData));
Marshal.StructureToPtr(ibData, pIndicesData, false);
hr = m_pD3D11Device.CreateBuffer(ref ibDesc, pIndicesData, out m_cubeIndexBuffer);
Marshal.FreeHGlobal(pIndicesData);
// Create constant buffer
D3D11.D3D11_BUFFER_DESC cbDesc = new()
{
//ByteWidth = (uint)((Marshal.SizeOf<CBMVP>() + 15) & ~15), // 16-byte aligned
ByteWidth = 64,
//Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DYNAMIC,
CPUAccessFlags = D3D11_CPU_ACCESS_FLAG.D3D11_CPU_ACCESS_WRITE,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_CONSTANT_BUFFER,
};
hr = m_pD3D11Device.CreateBuffer(ref cbDesc, IntPtr.Zero, out m_constantBuffer);
m_pD3D11DeviceContext.VSSetConstantBuffers(0, 1, (new[] { m_constantBuffer }));
string vsSource = @"
cbuffer MVP : register(b0)
{
float4x4 mvp;
};
struct VSIn
{
float3 pos : POSITION;
float2 uv : TEXCOORD0;
};
struct PSIn
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
PSIn VSMain(VSIn input)
{
PSIn o;
o.pos = mul(float4(input.pos, 1), mvp);
o.uv = input.uv;
return o;
}
";
byte[] vsBytes = Encoding.ASCII.GetBytes(vsSource + "\0");
hr = D3D11Tools.D3DCompile(vsBytes, vsBytes.Length, null, IntPtr.Zero, IntPtr.Zero,
"VSMain", "vs_5_0", 0, 0, out IntPtr vsBlob, out IntPtr vsErrorBlob);
if (!SUCCEEDED(hr))
{
var vsErrorBlobObj = Marshal.GetObjectForIUnknown(vsErrorBlob) as ID3DBlob;
if (vsErrorBlobObj == null)
throw new Exception("Failed to get ID3DBlob from vsErrorBlob");
IntPtr ptr = vsErrorBlobObj.GetBufferPointer();
int nSize = (int)vsErrorBlobObj.GetBufferSize();
byte[] buf = new byte[nSize];
Marshal.Copy(ptr, buf, 0, nSize);
string sError = Encoding.ASCII.GetString(buf);
Marshal.Release(vsErrorBlob);
throw new Exception(sError);
}
var vsBlobObj = Marshal.GetObjectForIUnknown(vsBlob) as ID3DBlob;
if (vsBlobObj == null)
throw new Exception("Failed to get ID3DBlob from vsBlob");
IntPtr pVSBytecode = vsBlobObj.GetBufferPointer();
uint nBytecodeSize = (uint)vsBlobObj.GetBufferSize();
hr = m_pD3D11Device.CreateVertexShader(pVSBytecode, nBytecodeSize, null, out m_cubeVS);
SafeRelease(ref vsBlobObj);
D3D11_INPUT_ELEMENT_DESC[] layout =
{
new D3D11_INPUT_ELEMENT_DESC
{
SemanticName = "POSITION",
SemanticIndex = 0,
Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32_FLOAT,
InputSlot = 0,
AlignedByteOffset = 0,
InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA,
InstanceDataStepRate = 0
},
new D3D11_INPUT_ELEMENT_DESC
{
SemanticName = "TEXCOORD",
SemanticIndex = 0,
Format = DXGI_FORMAT.DXGI_FORMAT_R32G32_FLOAT,
InputSlot = 0,
AlignedByteOffset = 12,
InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA,
InstanceDataStepRate = 0
}
};
hr = m_pD3D11Device.CreateInputLayout(layout, (uint)layout.Length, pVSBytecode, (nint)nBytecodeSize, out m_inputLayout);
Marshal.Release(vsBlob);
string psSource = @"
Texture2D tex0 : register(t0);
SamplerState samp0 : register(s0);
struct PSIn
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
float4 PSMain(PSIn input) : SV_Target
{
float2 uv = input.uv;
uv.y = 1.0 - uv.y; // vertical flip
return tex0.Sample(samp0, uv);
}
";
byte[] psBytes = Encoding.ASCII.GetBytes(psSource + "\0");
hr = D3D11Tools.D3DCompile(psBytes, psBytes.Length, null, IntPtr.Zero, IntPtr.Zero,
"PSMain", "ps_5_0", 0, 0, out IntPtr psBlob, out IntPtr psErrorBlob);
if (!SUCCEEDED(hr))
{
var psErrorBlobObj = Marshal.GetObjectForIUnknown(psErrorBlob) as ID3DBlob;
if (psErrorBlobObj == null)
throw new Exception("Failed to get ID3DBlob from psErrorBlob");
IntPtr ptr = psErrorBlobObj.GetBufferPointer();
int nSize = (int)psErrorBlobObj.GetBufferSize();
byte[] buf = new byte[nSize];
Marshal.Copy(ptr, buf, 0, nSize);
string sError = Encoding.ASCII.GetString(buf);
Marshal.Release(psErrorBlob);
throw new Exception(sError);
}
var psBlobObj = Marshal.GetObjectForIUnknown(psBlob) as ID3DBlob;
if (psBlobObj == null)
throw new Exception("Failed to get ID3DBlob from vsBlob");
IntPtr pPSBytecode = psBlobObj.GetBufferPointer();
nBytecodeSize = (uint)psBlobObj.GetBufferSize();
hr = m_pD3D11Device.CreatePixelShader(pPSBytecode, nBytecodeSize, null, out m_cubePS);
SafeRelease(ref psBlobObj);
Marshal.Release(psBlob);
D3D11.D3D11_SAMPLER_DESC sampDesc = new()
{
Filter = D3D11.D3D11_FILTER.D3D11_FILTER_MIN_MAG_MIP_LINEAR,
AddressU = D3D11.D3D11_TEXTURE_ADDRESS_MODE.D3D11_TEXTURE_ADDRESS_CLAMP,
AddressV = D3D11.D3D11_TEXTURE_ADDRESS_MODE.D3D11_TEXTURE_ADDRESS_CLAMP,
AddressW = D3D11.D3D11_TEXTURE_ADDRESS_MODE.D3D11_TEXTURE_ADDRESS_CLAMP,
ComparisonFunc = D3D11.D3D11_COMPARISON_FUNC.D3D11_COMPARISON_NEVER,
MinLOD = 0,
MaxLOD = float.MaxValue
};
hr = m_pD3D11Device.CreateSamplerState(ref sampDesc, out m_sampler);
D3D11.D3D11_RASTERIZER_DESC rs = new()
{
FillMode = D3D11.D3D11_FILL_MODE.D3D11_FILL_SOLID,
CullMode = D3D11.D3D11_CULL_MODE.D3D11_CULL_NONE,
DepthClipEnable = true
};
m_pD3D11Device.CreateRasterizerState(ref rs, out m_rs);
string swirlVS = @"
struct VSOut
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
VSOut VSMain(uint id : SV_VertexID)
{
float2 pos[3] =
{
float2(-1, -1),
float2(-1, 3),
float2( 3, -1)
};
VSOut o;
o.pos = float4(pos[id], 0, 1);
o.uv = o.pos.xy * 0.5 + 0.5;
return o;
}
";
byte[] swirlVSBytes = Encoding.ASCII.GetBytes(swirlVS + "\0");
hr = D3D11Tools.D3DCompile(swirlVSBytes, swirlVSBytes.Length, null, IntPtr.Zero, IntPtr.Zero,
"VSMain", "vs_5_0", 0, 0, out IntPtr swirlVSBlob, out IntPtr swirlVSErrorBlob);
if (!SUCCEEDED(hr))
{
var swirlVSErrorBlobObj = Marshal.GetObjectForIUnknown(swirlVSErrorBlob) as ID3DBlob;
if (swirlVSErrorBlobObj == null)
throw new Exception("Failed to get ID3DBlob from swirlVSErrorBlob");
IntPtr ptr = swirlVSErrorBlobObj.GetBufferPointer();
int nSize = (int)swirlVSErrorBlobObj.GetBufferSize();
byte[] buf = new byte[nSize];
Marshal.Copy(ptr, buf, 0, nSize);
string sError = Encoding.ASCII.GetString(buf);
Marshal.Release(swirlVSErrorBlob);
throw new Exception(sError);
}
var swirlVSBlobObj = (ID3DBlob)Marshal.GetObjectForIUnknown(swirlVSBlob);
m_pD3D11Device.CreateVertexShader(swirlVSBlobObj.GetBufferPointer(), (uint)swirlVSBlobObj.GetBufferSize(), null, out m_swirlVS);
SafeRelease(ref swirlVSBlobObj);
Marshal.Release(swirlVSBlob);
string swirlPS = @"
cbuffer Time : register(b1)
{
float time;
};
float4 PSMain(float4 pos : SV_POSITION, float2 uv : TEXCOORD0) : SV_Target
{
float2 p = uv * 2.0 - 1.0;
float r = length(p);
float a = atan2(p.y, p.x);
float t = time * 2.0;
float depth = 1.0 / (r + 0.3);
float wave = sin(a * 6.0 + t + r * 10.0);
float glow = exp(-r * 3.0);
float3 color =
float3(
0.5 + 0.5 * sin(t + a),
0.5 + 0.5 * sin(t + a + 2.0),
0.5 + 0.5 * sin(t + a + 4.0)
);
color *= depth * glow * (1.0 + wave * 0.3);
return float4(color, 1.0);
}
";
byte[] swirlPSBytes = Encoding.ASCII.GetBytes(swirlPS + "\0");
hr = D3D11Tools.D3DCompile(swirlPSBytes, swirlPSBytes.Length, null, IntPtr.Zero, IntPtr.Zero,
"PSMain", "ps_5_0", 0, 0, out IntPtr swirlPSBlob, out IntPtr swirlPSErrorBlob);
if (!SUCCEEDED(hr))
{
var swirlPSErrorBlobObj = Marshal.GetObjectForIUnknown(swirlPSErrorBlob) as ID3DBlob;
if (swirlPSErrorBlobObj == null)
throw new Exception("Failed to get ID3DBlob from swirlPSErrorBlob");
IntPtr ptr = swirlPSErrorBlobObj.GetBufferPointer();
int nSize = (int)swirlPSErrorBlobObj.GetBufferSize();
byte[] buf = new byte[nSize];
Marshal.Copy(ptr, buf, 0, nSize);
string sError = Encoding.ASCII.GetString(buf);
Marshal.Release(swirlPSErrorBlob);
throw new Exception(sError);
}
var psBlobSwirlObj = (ID3DBlob)Marshal.GetObjectForIUnknown(swirlPSBlob);
m_pD3D11Device.CreatePixelShader(psBlobSwirlObj.GetBufferPointer(), (uint)psBlobSwirlObj.GetBufferSize(), null, out m_swirlPS);
SafeRelease(ref psBlobSwirlObj);
Marshal.Release(swirlPSBlob);
D3D11.D3D11_BUFFER_DESC desc = new()
{
ByteWidth = 16,
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DYNAMIC,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_CONSTANT_BUFFER,
CPUAccessFlags = D3D11_CPU_ACCESS_FLAG.D3D11_CPU_ACCESS_WRITE
};
m_pD3D11Device.CreateBuffer(ref desc, IntPtr.Zero, out m_cbTime);
// Added with Copilot...
// Create edge vertex buffer
D3D11.D3D11_BUFFER_DESC vbEdgeDesc = new()
{
ByteWidth = (uint)(Marshal.SizeOf<Vertex>() * edgeVertices.Length),
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_VERTEX_BUFFER,
};
D3D11_SUBRESOURCE_DATA vbEdgeData = new() { pSysMem = Marshal.UnsafeAddrOfPinnedArrayElement(edgeVertices, 0) };
IntPtr pVBEData = Marshal.AllocHGlobal(Marshal.SizeOf(vbEdgeData));
Marshal.StructureToPtr(vbEdgeData, pVBEData, false);
hr = m_pD3D11Device.CreateBuffer(ref vbEdgeDesc, pVBEData, out m_edgeVertexBuffer);
Marshal.FreeHGlobal(pVBEData);
// Create edge index buffer
D3D11.D3D11_BUFFER_DESC ibEdgeDesc = new()
{
ByteWidth = (uint)(sizeof(ushort) * edgeIndices.Length),
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_INDEX_BUFFER,
};
D3D11_SUBRESOURCE_DATA ibEdgeData = new() { pSysMem = Marshal.UnsafeAddrOfPinnedArrayElement(edgeIndices, 0) };
IntPtr pIBEData = Marshal.AllocHGlobal(Marshal.SizeOf(ibEdgeData));
Marshal.StructureToPtr(ibEdgeData, pIBEData, false);
hr = m_pD3D11Device.CreateBuffer(ref ibEdgeDesc, pIBEData, out m_edgeIndexBuffer);
Marshal.FreeHGlobal(pIBEData);
// Edge pixel shader (constant dark gray)
string psEdgeSrc = @"
float4 PSMain() : SV_Target
{
return float4(0.2f, 0.2f, 0.2f, 1.0f); // dark gray
}
";
byte[] psEdgeBytes = Encoding.ASCII.GetBytes(psEdgeSrc + "\0");
hr = D3D11Tools.D3DCompile(psEdgeBytes, (IntPtr)psEdgeBytes.Length, null, IntPtr.Zero, IntPtr.Zero,
"PSMain", "ps_5_0", 0, 0, out IntPtr psEdgeBlob, out IntPtr psEdgeError);
if (SUCCEEDED(hr))
{
var psEdgeBlobObj = Marshal.GetObjectForIUnknown(psEdgeBlob) as ID3DBlob;
IntPtr pPSEdgeBC = psEdgeBlobObj.GetBufferPointer();
uint nPSEdgeSize = (uint)psEdgeBlobObj.GetBufferSize();
hr = m_pD3D11Device.CreatePixelShader(pPSEdgeBC, nPSEdgeSize, null, out m_psEdge);
SafeRelease(ref psEdgeBlobObj);
Marshal.Release(psEdgeBlob);
}
else
{
// ...
}
// Depth-stencil state for edges: allow equal depth and do NOT write depth
D3D11.D3D11_DEPTH_STENCIL_DESC dsEdgesDesc = new()
{
DepthEnable = true,
DepthWriteMask = D3D11.D3D11_DEPTH_WRITE_MASK.D3D11_DEPTH_WRITE_MASK_ZERO,
DepthFunc = D3D11.D3D11_COMPARISON_FUNC.D3D11_COMPARISON_LESS_EQUAL,
StencilEnable = false
};
m_pD3D11Device.CreateDepthStencilState(ref dsEdgesDesc, out m_dsEdges);
// Paper
const int GRID = 30;
List<Vertex> paperVertices = new();
List<ushort> paperIndices = new();
// Create mesh grid
for (int y = 0; y <= GRID; y++)
{
for (int x = 0; x <= GRID; x++)
{
float fx = -1.5f + x * 3.0f / GRID;
float fy = -1.5f + y * 3.0f / GRID;
paperVertices.Add(new Vertex
{
Position = new System.Numerics.Vector3(fx, fy, 0.0f),
TexCoord = new System.Numerics.Vector2(x / (float)GRID, 1.0f - y / (float)GRID)
});
}
}
for (int y = 0; y < GRID; y++)
{
for (int x = 0; x < GRID; x++)
{
int i0 = y * (GRID + 1) + x;
int i1 = i0 + 1;
int i2 = i0 + (GRID + 1);
int i3 = i2 + 1;
paperIndices.Add((ushort)i0);
paperIndices.Add((ushort)i2);
paperIndices.Add((ushort)i1);
paperIndices.Add((ushort)i1);
paperIndices.Add((ushort)i2);
paperIndices.Add((ushort)i3);
}
}
m_paperIndexCount = (uint)paperIndices.Count;
// Vertex buffer
var vbDescPaper = new D3D11.D3D11_BUFFER_DESC
{
ByteWidth = (uint)(Marshal.SizeOf<Vertex>() * paperVertices.Count),
Usage = D3D11.D3D11_USAGE.D3D11_USAGE_DEFAULT,
BindFlags = D3D11_BIND_FLAG.D3D11_BIND_VERTEX_BUFFER,
};
var vbDataPaper = new D3D11_SUBRESOURCE_DATA