diff --git a/ComputeSharp.sln b/ComputeSharp.sln index cccc08d6..7e4f1344 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -47,6 +47,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internal EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Sample.SwapChain", "samples\ComputeSharp.Sample.SwapChain\ComputeSharp.Sample.SwapChain.csproj", "{E7C9247D-016B-4819-AF9F-0E9B3591E04B}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5 @@ -172,6 +174,14 @@ Global {BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.Build.0 = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.ActiveCfg = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.ActiveCfg = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.Build.0 = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.Build.0 = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.ActiveCfg = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -187,6 +197,7 @@ Global {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {BF52326F-E415-49E6-8595-62762216762B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} + {E7C9247D-016B-4819-AF9F-0E9B3591E04B} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs new file mode 100644 index 00000000..0cfc25da --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs @@ -0,0 +1,287 @@ +using System; +using System.Drawing; +using ComputeSharp.Interop; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Sample.SwapChain.Backend +{ + internal sealed class SwapChainApplication : Win32Application + where T : struct, IComputeShader + { + /// + /// The instance used to create shaders to run. + /// + private readonly Func, TimeSpan, T> shaderFactory; + + /// + /// The pointer for the device currently in use. + /// + private ComPtr d3D12Device; + + /// + /// The instance to use for graphics operations. + /// + private ComPtr d3D12CommandQueue; + + /// + /// The instance used for graphics operations. + /// + private ComPtr d3D12Fence; + + /// + /// The next fence value for graphics operations using . + /// + private ulong nextD3D12FenceValue = 1; + + /// + /// The object to create command lists. + /// + private ComPtr d3D12CommandAllocator; + + /// + /// The instance used to copy data to the back buffers. + /// + private ComPtr d3D12GraphicsCommandList; + + /// + /// The instance used to display content onto the target window. + /// + private ComPtr dxgiSwapChain1; + + /// + /// The first buffer within . + /// + private ComPtr d3D12Resource0; + + /// + /// The second buffer within . + /// + private ComPtr d3D12Resource1; + + /// + /// The index of the next buffer that can be used to present content. + /// + private uint currentBufferIndex; + + /// + /// The instance used to prepare frames to display. + /// + private ReadWriteTexture2D? texture; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to create shaders to run. + public SwapChainApplication(Func, TimeSpan, T> shaderFactory) + { + this.shaderFactory = shaderFactory; + } + + /// + public override string Title => default(T).ToString()!; + + /// + public override unsafe void OnInitialize(Size size, HWND hwnd) + { + // Get the underlying ID3D12Device in use + fixed (ID3D12Device** d3D12Device = this.d3D12Device) + { + _ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device); + } + + // Create the direct command queue to use + fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue) + { + D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc; + d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT; + d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; + d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE; + d3D12CommandQueueDesc.NodeMask = 0; + + _ = d3D12Device.Get()->CreateCommandQueue( + &d3D12CommandQueueDesc, + FX.__uuidof(), + (void**)d3D12CommandQueue); + } + + // Create the direct fence + fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence) + { + _ = this.d3D12Device.Get()->CreateFence( + 0, + D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE, + FX.__uuidof(), + (void**)d3D12Fence); + } + + // Create the swap chain to display frames + fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1) + { + using ComPtr dxgiFactory2 = default; + + _ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf()); + + DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default; + dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE; + dxgiSwapChainDesc1.BufferCount = 2; + dxgiSwapChainDesc1.Flags = 0; + dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM; + dxgiSwapChainDesc1.Width = 0; + dxgiSwapChainDesc1.Height = 0; + dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0); + dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH; + dxgiSwapChainDesc1.Stereo = 0; + dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + + _ = dxgiFactory2.Get()->CreateSwapChainForHwnd( + (IUnknown*)d3D12CommandQueue.Get(), + hwnd, + &dxgiSwapChainDesc1, + null, + null, + dxgiSwapChain1); + } + + // Create the command allocator to use + fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator) + { + this.d3D12Device.Get()->CreateCommandAllocator( + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + FX.__uuidof(), + (void**)d3D12CommandAllocator); + } + + // Create the reusable command list to copy data to the back buffers + fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList) + { + this.d3D12Device.Get()->CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + d3D12CommandAllocator, + null, + FX.__uuidof(), + (void**)d3D12GraphicsCommandList); + } + + // Close the command list to prepare it for future use + this.d3D12GraphicsCommandList.Get()->Close(); + } + + /// + public override unsafe void OnResize(Size size) + { + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); + + // Wait for the fence again to ensure there are no pending operations + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); + + this.nextD3D12FenceValue++; + + // Dispose the old buffers before resizing the buffer + this.d3D12Resource0.Dispose(); + this.d3D12Resource1.Dispose(); + + // Resize the swap chain buffers + this.dxgiSwapChain1.Get()->ResizeBuffers(0, 0, 0, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0); + + // Get the index of the initial back buffer + using (ComPtr dxgiSwapChain3 = default) + { + _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); + + this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + } + + // Retrieve the back buffers for the swap chain + fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) + fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) + { + _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0); + _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); + } + + this.texture?.Dispose(); + + D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); + + // Create the 2D texture to use to generate frames to display + this.texture = Gpu.Default.AllocateReadWriteTexture2D( + (int)d3D12Resource0Description.Width, + (int)d3D12Resource0Description.Height); + } + + /// + public override unsafe void OnUpdate(TimeSpan time) + { + // Generate the new frame + Gpu.Default.For(this.texture!.Width, this.texture.Height, this.shaderFactory(this.texture, time)); + + using ComPtr d3D12Resource = default; + + // Get the underlying ID3D12Resource pointer for the texture + _ = InteropServices.TryGetID3D12Resource(this.texture, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()); + + // Get the target back buffer to update + ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch + { + 0 => this.d3D12Resource0.Get(), + 1 => this.d3D12Resource1.Get(), + _ => null + }; + + this.currentBufferIndex ^= 1; + + // Reset the command list and command allocator + this.d3D12CommandAllocator.Get()->Reset(); + this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null); + + D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[] + { + D3D12_RESOURCE_BARRIER.InitTransition( + d3D12Resource.Get(), + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE), + D3D12_RESOURCE_BARRIER.InitTransition( + d3D12ResourceBackBuffer, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST) + }; + + // Transition the resources to COPY_DEST and COPY_SOURCE respectively + d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + + // Copy the generated frame to the target back buffer + d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get()); + + d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition( + d3D12Resource.Get(), + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition( + d3D12ResourceBackBuffer, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON); + + // Transition the resources back to COMMON and UNORDERED_ACCESS respectively + d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + + d3D12GraphicsCommandList.Get()->Close(); + + // Execute the command list to perform the copy + this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); + + // Present the new frame + this.dxgiSwapChain1.Get()->Present(0, 0); + + if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) + { + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); + } + + this.nextD3D12FenceValue++; + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs new file mode 100644 index 00000000..b207f3e8 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs @@ -0,0 +1,36 @@ +using System; +using System.Drawing; +using TerraFX.Interop; + +namespace ComputeSharp.Sample.SwapChain.Backend +{ + /// + /// A class representing a simple Win32 application. + /// + internal abstract class Win32Application + { + /// + /// Gets the title of the current application. + /// + public abstract string Title { get; } + + /// + /// Initializes the current application. + /// + /// The window size. + /// The handle for the window. + public abstract void OnInitialize(Size size, HWND hwnd); + + /// + /// Resizes the current application. + /// + /// The new window size. + public abstract void OnResize(Size size); + + /// + /// Updates the current application. + /// + /// The current time since the start of the application. + public abstract void OnUpdate(TimeSpan time); + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs new file mode 100644 index 00000000..047e0c65 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs @@ -0,0 +1,345 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Sample.SwapChain.Backend +{ + /// + /// A helper class to manage the creation and execution of Win32 applications. + /// + internal unsafe static class Win32ApplicationRunner + { + /// + /// Whether or not a resize operation is in progress. + /// + private static bool isResizing = false; + + /// + /// Whether or not the application is currently paused. + /// + private static bool isPaused = false; + + /// + /// The for the application window. + /// + private static HWND hwnd; + + /// + /// The current size of the application window. + /// + private static Size windowSize; + + /// + /// A instance used to track the elapsed time for the application. + /// + private static Stopwatch stopwatch = null!; + + /// + /// The application being run. + /// + private static Win32Application application = null!; + + /// + /// The number of elapsed milliseconds since the window title was last updated. + /// + private static long elapsedMillisecondsForLastTitleUpdate; + + /// + /// The number of elapsed frames since the window title was last updated. + /// + private static int elapsedFramesSinceLastTitleUpdate; + + /// + /// Runs a specified application and starts the main loop to update its state. + /// This is the entry point for a given application of type , and it should be + /// called as soon as the process is launched, excluding any other additional initialization needed. + /// To launch an application, simply add this line to the project being used: + /// Win32ApplicationRunner.Run<MyApplication>(); + /// + /// The type of application being launched. + /// The exit code for the application. + public static int Run(Win32Application application) + { + Win32ApplicationRunner.application = application; + + IntPtr hInstance = FX.GetModuleHandleW(null); + uint width = 1280; + uint height = 720; + + fixed (char* name = Assembly.GetExecutingAssembly().FullName) + fixed (char* windowTitle = application.Title) + { + // Initialize the window class + WNDCLASSEXW windowClassEx = new() + { + cbSize = (uint)sizeof(WNDCLASSEXW), + style = FX.CS_HREDRAW | FX.CS_VREDRAW, + lpfnWndProc = &WindowProc, + hInstance = hInstance, + hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)), + lpszClassName = (ushort*)name + }; + + // Register the window class + _ = FX.RegisterClassExW(&windowClassEx); + + Rectangle windowRect = new(0, 0, (int)width, (int)height); + + // Set the target window size + _ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE); + + height = (uint)(windowRect.Bottom - windowRect.Top); + width = (uint)(windowRect.Right - windowRect.Left); + + // Create the window and store a handle to it + hwnd = FX.CreateWindowExW( + 0, + windowClassEx.lpszClassName, + (ushort*)windowTitle, + FX.WS_OVERLAPPEDWINDOW, + FX.CW_USEDEFAULT, + FX.CW_USEDEFAULT, + (int)width, + (int)height, + HWND.NULL, + HMENU.NULL, + hInstance, + (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application)) + ); + + MARGINS margins = default; + margins.cxLeftWidth = -1; + margins.cxRightWidth = -1; + margins.cyTopHeight = -1; + margins.cyBottomHeight = -1; + + _ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins); + } + + windowSize = new Size((int)height, (int)width); + + // Initialize the application + application.OnInitialize(windowSize, hwnd); + + // Display the window + _ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT); + + // Start the timer + stopwatch = Stopwatch.StartNew(); + + MSG msg = default; + + // Process any messages in the queue + while (msg.message != FX.WM_QUIT) + { + if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0) + { + _ = FX.TranslateMessage(&msg); + _ = FX.DispatchMessageW(&msg); + } + else if (!isPaused || true) + { + RunApp(); + } + else + { + Thread.Sleep(100); + } + } + + // Return this part of the WM_QUIT message to Windows + return (int)msg.wParam; + } + + /// + /// The application state update method that is invoked within the main application loop. + /// + private static void RunApp() + { + // Update window title approx every second + if (stopwatch.ElapsedMilliseconds - elapsedMillisecondsForLastTitleUpdate >= 1000) + { + string title = isPaused switch + { + true => $"{application.Title} - Paused", + false => $"{application.Title} - FPS: {elapsedFramesSinceLastTitleUpdate}" + }; + + fixed (char* pTitle = title) + { + _ = FX.SetWindowTextW(hwnd, (ushort*)pTitle); + } + + elapsedMillisecondsForLastTitleUpdate = stopwatch.ElapsedMilliseconds; + elapsedFramesSinceLastTitleUpdate = 0; + } + + // Update the application state + application.OnUpdate(stopwatch.Elapsed); + + elapsedFramesSinceLastTitleUpdate++; + } + + /// + /// Processes incoming messages for a window. + /// + /// A handle to the window. + /// The message. + /// Additional message information (the contents depend on the value of ). + /// Additional message information (the contents depend on the value of ). + /// The result of the message processing for the input message. + [UnmanagedCallersOnly] + private static nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam) + { + switch (uMsg) + { + // Change the paused state on window activation + case FX.WM_ACTIVATE: + { + if (FX.LOWORD(wParam) == FX.WA_INACTIVE) + { + isPaused = true; + } + else + { + isPaused = false; + } + return 0; + } + + // Change the paused state when ESC is pressed + case FX.WM_KEYDOWN: + { + if ((ConsoleKey)wParam == ConsoleKey.Escape) + { + + if (isPaused) + { + FX.SetCapture(hwnd); + } + else + { + FX.ReleaseCapture(); + } + + isPaused = !isPaused; + } + + return 0; + } + + // Window resize started + case FX.WM_ENTERSIZEMOVE: + { + isResizing = true; + + return 0; + } + + // Window resize completed + case FX.WM_EXITSIZEMOVE: + { + isResizing = false; + application.OnResize(windowSize); + + return 0; + } + + // Size update + case FX.WM_SIZE: + { + uint size = (uint)lParam; + + windowSize = new Size(FX.LOWORD(size), FX.HIWORD(size)); + + if (!isResizing && wParam != FX.SIZE_MINIMIZED) + { + application.OnResize(windowSize); + } + + return 0; + } + + // Size and position of the window (needed to enable the borderless mode) + case FX.WM_NCCALCSIZE: + { + return 0; + } + + // Enable dragging the window + case FX.WM_NCHITTEST: + { + POINT point; + RECT rect; + + _ = FX.GetCursorPos(&point); + _ = FX.GetWindowRect(hwnd, &rect); + + bool + isAtTop = Math.Abs(point.y - rect.top) < 12, + isAtRight = Math.Abs(point.x - rect.right) < 12, + isAtBottom = Math.Abs(point.y - rect.bottom) < 12, + isAtLeft = Math.Abs(point.x - rect.left) < 12; + + if (isAtTop) + { + if (isAtRight) return FX.HTTOPRIGHT; + if (isAtLeft) return FX.HTTOPLEFT; + return FX.HTTOP; + } + + if (isAtRight) + { + if (isAtTop) return FX.HTTOPRIGHT; + if (isAtBottom) return FX.HTBOTTOMRIGHT; + return FX.HTRIGHT; + } + + if (isAtBottom) + { + if (isAtRight) return FX.HTBOTTOMRIGHT; + if (isAtLeft) return FX.HTBOTTOMLEFT; + return FX.HTBOTTOM; + } + + if (isAtLeft) + { + if (isAtTop) return FX.HTTOPLEFT; + if (isAtBottom) return FX.HTBOTTOMLEFT; + return FX.HTLEFT; + } + + return FX.HTCAPTION; + } + + // Restore the drop shadow + case FX.WM_DWMCOMPOSITIONCHANGED: + { + MARGINS margins = default; + margins.cxLeftWidth = -1; + margins.cxRightWidth = -1; + margins.cyTopHeight = -1; + margins.cyBottomHeight = -1; + + _ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins); + + return 0; + } + + // Shutdown + case FX.WM_DESTROY: + { + FX.PostQuitMessage(0); + return 0; + } + } + + return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam); + } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj b/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj new file mode 100644 index 00000000..333c078e --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj @@ -0,0 +1,13 @@ + + + + Exe + net5.0 + + + + + + + + diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs new file mode 100644 index 00000000..98d036cd --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -0,0 +1,45 @@ +using System; +using ComputeSharp.Sample.SwapChain.Backend; +using ComputeSharp.Sample.SwapChain.Shaders; + +namespace ComputeSharp.Sample.SwapChain +{ + class Program + { + /// + /// The mapping of available samples to choose from. + /// + private static readonly Win32Application[] Samples = new Win32Application[] + { + new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), + new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), + new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)) + }; + + static void Main() + { + Console.WriteLine("Available samples:"); + Console.WriteLine(); + + for (int i = 0; i < Samples.Length; i++) + { + Console.WriteLine($"{i}: {Samples[i].GetType().GenericTypeArguments[0].Name}"); + } + + Console.WriteLine(); + + int index; + + do + { + Console.Write("Enter the index of the sample to run: "); + } + while (!int.TryParse(Console.ReadLine(), out index)); + + Console.WriteLine(); + Console.WriteLine($"Starting {Samples[index].GetType().GenericTypeArguments[0].Name}..."); + + Win32ApplicationRunner.Run(Samples[index]); + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs new file mode 100644 index 00000000..f5566663 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs @@ -0,0 +1,79 @@ +namespace ComputeSharp.Sample.SwapChain.Shaders +{ + /// + /// A shader creating an abstract and colorful animation. + /// Ported from . + /// Created by Benoit Marini. + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct ColorfulInfinity : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + /// The total number of layers for the final animation. + /// + private const float NumberOfLayers = 16.0f; + + /// + /// The number of iterations to calculate a texel value. + /// + private const int NumberOfIterations = 23; + + /// + /// Makes some magic happen. + /// + private Float4 Tex(Float3 p) + { + float t = time + 78.0f; + Float4 o = new(p.X, p.Y, p.Z, 3.0f * Hlsl.Sin(t * 0.1f)); + Float4 dec = + new Float4(1.0f, 0.9f, 0.1f, 0.15f) + + new Float4(0.06f * Hlsl.Cos(t * 0.1f), 0, 0, 0.14f * Hlsl.Cos(t * 0.23f)); + + for (int i = 0; i++ < NumberOfIterations;) + { + o.XZYW = Hlsl.Abs(o / Hlsl.Dot(o, o) - dec); + } + + return o; + } + + /// + public void Execute() + { + int width = texture.Width; + int height = texture.Height; + + Float2 uv = ((Float2)ThreadIds.XY - (Float2)(new Int2(width, height)) * 0.5f) / height; + Float3 col = 0; + float t = time * 0.3f; + + for (float i = 0.0f; i <= 1.0f; i += 1.0f / NumberOfLayers) + { + float d = Hlsl.Frac(i + t); + float s = Hlsl.Lerp(5.0f, 0.5f, d); + float f = d * Hlsl.SmoothStep(1.0f, 0.9f, d); + + col += Tex(new Float3(uv.X * s, uv.Y * s, i * 4.0f)).XYZ * f; + } + + col /= NumberOfLayers; + col *= new Float3(2, 1.0f, 2.0f); + col = Hlsl.Pow(col, 0.5f); + + Float4 color = new(col.X, col.Y, col.Z, 1.0f); + + texture[ThreadIds.XY] = color; + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs new file mode 100644 index 00000000..a5be7ef9 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs @@ -0,0 +1,50 @@ +namespace ComputeSharp.Sample.SwapChain.Shaders +{ + /// + /// A shader creating a fractal tiling animation. + /// Ported from . + /// Created by Inigo Quilez. + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct FractalTiling : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + public void Execute() + { + Float2 position = ((Float2)(256 * ThreadIds.XY)) / texture.Width + time; + Float4 color = 0; + + for (int i = 0; i < 6; i++) + { + Float2 a = Hlsl.Floor(position); + Float2 b = Hlsl.Frac(position); + Float4 w = Hlsl.Frac( + (Hlsl.Sin(a.X * 7 + 31.0f * a.Y + 0.01f * time) + + new Float4(0.035f, 0.01f, 0, 0.7f)) + * 13.545317f); + + color.XYZ += w.XYZ * + 2.0f * Hlsl.SmoothStep(0.45f, 0.55f, w.W) * + Hlsl.Sqrt(16.0f * b.X * b.Y * (1.0f - b.X) * (1.0f - b.Y)); + + position /= 2.0f; + color /= 2.0f; + } + + color.XYZ = Hlsl.Pow(color.XYZ, new Float3(0.7f, 0.8f, 0.5f)); + + texture[ThreadIds.XY] = color; + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs new file mode 100644 index 00000000..176f330c --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs @@ -0,0 +1,152 @@ +namespace ComputeSharp.Sample.SwapChain.Shaders +{ + /// + /// A shader creating an animated two-tiles Truchet arrangement. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct TwoTiledTruchet : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + /// Calculates the Truchet distance field. + /// + /// The input value to compute the distance field for. + /// The resulting Truchet angle. + /// The distance field for the input value. + private Float2 DistanceField(Float2 p, out Float2 ang) + { + // Fast hash for a pair of floats + static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // HLSL's port of the GLSL mod intrinsic + static float Mod(float x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + Float2 ip2 = Hlsl.Floor(p / 2.0f); + Float2 ip = Hlsl.Floor(p); + float rnd = Hash21(ip); + float rnd3 = Hash21(ip + 0.57f); + Float2 d = 1e5f; + + p -= ip + 0.5f; + + if (Mod(ip2.X + ip2.Y, 2.0f) < 0.5f) + { + d = Hlsl.Abs(p); + ang = p.YX; + + if (Mod(ip.X + 1.0f, 2.0f) < 0.5f) + { + ang.X *= -1.0f; + + } + + if (Mod(ip.Y + 1.0f, 2.0f) > 0.5f) + { + ang.Y *= -1.0f; + } + + if (rnd3 < .5) + { + d = d.YX; + ang = ang.YX; + } + + ang += 0.5f; + ang *= 3.0f; + + } + else + { + if (rnd < .5) + { + p = p.YX * new Float2(1, -1); + } + + d.X = Hlsl.Length(p - 0.5f) - 0.5f; + d.Y = Hlsl.Length(p + 0.5f) - 0.5f; + + d = Hlsl.Abs(d); + + ang = 0; + ang.X = -Hlsl.Atan((p.Y - 0.5f) / (p.X - 0.5f)); + ang.Y = -Hlsl.Atan((p.Y + 0.5f) / (p.X + 0.5f)); + + if (Mod(ip.X + ip.Y, 2.0f) < 0.5f) + { + ang *= -1.0f; + } + + if (rnd < 0.5f) + { + ang *= -1.0f; + } + + if (rnd3 < 0.5f) + { + d = d.YX; + ang = ang.YX; + } + + ang *= 4.0f / 6.2831853f; + ang *= 2.0f; + } + + ang = Hlsl.Frac(ang + time / 4.0f); + + return d; + } + + /// + public void Execute() + { + int width = texture.Width; + int height = texture.Height; + + Float2 uv = ((Float2)ThreadIds.XY - (Float2)(new Int2(width, height)) * 0.5f) / height; + float gSc = 7.0f; + Float2 p = uv * gSc - new Float2(-1, -0.5f) * time / 2.0f; + float sf = 2.0f / height * gSc; + float lSc = 6.0f; + float lw = 1.0f / lSc / gSc; + Float2 d = DistanceField(p, out Float2 ang) - 2.5f / lSc; + Float3 col = new Float3(1.0f, 0.9f, 0.8f); + + for (int i = 0; i < 2; i++) + { + float di = d[i] - lw / 4.0f; + float tracks = Hlsl.Clamp(Hlsl.Sin(ang[i] * 6.2831f + time * 6.0f) * 4.0f, 0.0f, 1.0f); + float gap = 1.0f + lw; + + col = Hlsl.Lerp(col, 0, (1.0f - Hlsl.SmoothStep(0.0f, sf * 6.0f, di)) * 0.35f); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di)); + col = Hlsl.Lerp(col, new(1.0f, 0.9f, 0.8f), 1.0f - Hlsl.SmoothStep(0.0f, sf, di + lw * 2.0f)); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + gap / lSc)); + col = Hlsl.Lerp(col, 1, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + gap / lSc + lw)); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + 2.0f * gap / lSc)); + col = Hlsl.Lerp(col, 1 * tracks, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + 2.0f * gap / lSc + lw)); + } + + Float3 rgb = Hlsl.Sqrt(Hlsl.Max(col, 0.0f)); + Float4 color = new(rgb.X, rgb.Y, rgb.Z, 1.0f); + + texture[ThreadIds.XY] = color; + } + } +} diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs index 3d757637..dc8e838c 100644 --- a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs @@ -1240,6 +1240,30 @@ namespace ComputeSharp [Pure] public static Float4 Ldexp(Float4 x, Float4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ldexp)}({nameof(Float4)},{nameof(Float4)})"); + /// + /// Returns the length of the specified floating-point vector. + /// + /// The specified floating-point vector. + /// A floating-point scalar that represents the length of the x parameter. + [Pure] + public static float Length(Float2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Length)}({nameof(Float2)})"); + + /// + /// Returns the length of the specified floating-point vector. + /// + /// The specified floating-point vector. + /// A floating-point scalar that represents the length of the x parameter. + [Pure] + public static float Length(Float3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Length)}({nameof(Float3)})"); + + /// + /// Returns the length of the specified floating-point vector. + /// + /// The specified floating-point vector. + /// A floating-point scalar that represents the length of the x parameter. + [Pure] + public static float Length(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Length)}({nameof(Float4)})"); + /// /// Performs a linear interpolation. /// diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index f7f1bd7e..bf11e1db 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -236,7 +236,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; } - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, flags: d3D12ResourceFlags); + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, mipLevels: 1, flags: d3D12ResourceFlags); d3D12Device.CreateCommittedResource( &d3D12HeapProperties, @@ -302,7 +302,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; } - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex3D(dxgiFormat, width, height, depth, flags: d3D12ResourceFlags); + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex3D(dxgiFormat, width, height, depth, mipLevels: 1, flags: d3D12ResourceFlags); d3D12Device.CreateCommittedResource( &d3D12HeapProperties, diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs index 86418169..3a29bc8d 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -58,6 +58,12 @@ namespace ComputeSharp.SourceGenerators.Extensions _ => semanticModel.GetTypeInfo(sourceType).Type! }; + // Do nothing if the type is just void + if (typeSymbol.SpecialType == SpecialType.System_Void) + { + return node; + } + string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat); discoveredTypes.Add((INamedTypeSymbol)typeSymbol); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index aebad7c3..b6c54421 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -251,6 +251,12 @@ namespace ComputeSharp.SourceGenerators // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(localFunction.Value); + } + // If the method is the shader entry point, do additional processing if (isShaderEntryPoint) { @@ -259,12 +265,6 @@ namespace ComputeSharp.SourceGenerators entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } else methods.Add(processedMethod); - - // Emit the extracted local functions - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(localFunction.Value); - } } return (entryPoint!, methods); diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 38cf34f3..9c640fa4 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -153,7 +153,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { this.currentMethod = node; - var updatedNode = (MethodDeclarationSyntax?)base.Visit(node); + var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes); if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { @@ -358,6 +360,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes); + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 3cf860e9..09faf240 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -1,3 +1,4 @@ +using System.Threading; using ComputeSharp.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -10,11 +11,11 @@ namespace ComputeSharp.Tests [TestMethod] public void ReservedKeywords() { - ReflectionServices.GetShaderInfo(out _); + ReflectionServices.GetShaderInfo(out _); } [AutoConstructor] - public readonly partial struct SoftmaxActivation : IComputeShader + public readonly partial struct ReservedKeywords_Kernel : IComputeShader { public readonly ReadWriteBuffer row_major; public readonly float dword; @@ -27,5 +28,50 @@ namespace ComputeSharp.Tests row_major[ThreadIds.X] = log / dword; } } + + [TestMethod] + public void SpecialTypeAsReturnType() + { + ReflectionServices.GetShaderInfo(out _); + } + + [AutoConstructor] + public readonly partial struct SpecialTypeAsReturnType_Kernel : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + Float2 Foo(float x) => x; + + public void Execute() + { + static Float3 Bar(float x) => x; + + buffer[ThreadIds.X] = Foo(ThreadIds.X) + Bar(ThreadIds.X).XY; + } + } + + [TestMethod] + public void LocalFunctionInExternalMethods() + { + ReflectionServices.GetShaderInfo(out _); + } + + [AutoConstructor] + public readonly partial struct LocalFunctionInExternalMethods_Kernel : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + Float2 Foo(float x) + { + static Float2 Baz(float y) => y; + + return Baz(x); + } + + public void Execute() + { + buffer[ThreadIds.X] = Foo(ThreadIds.X); + } + } } }