Merge pull request #312 from Sergio0694/dev/dred-support

Add DirectX DRED support and PIX extensions
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-06-25 20:24:54 +02:00
コミット 405098cd63
65ファイル変更
+1982 -373

検索条件に一致するファイルはありません

+95 -14
ファイルの表示
@@ -79,6 +79,9 @@ jobs:
- name: Build ComputeSharp.D2D1 package
run: dotnet build src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj -c Release
shell: cmd
- name: Build ComputeSharp.Pix package
run: dotnet build src\ComputeSharp.Pix.Package\ComputeSharp.Pix.Package.msbuildproj -c Release
shell: cmd
- name: Build ComputeSharp.Uwp package
run: msbuild src\ComputeSharp.Uwp\ComputeSharp.Uwp.csproj -t:restore,build,pack /p:Configuration=Release
shell: cmd
@@ -248,23 +251,101 @@ jobs:
with:
name: nuget_preview
path: artifacts
- name: Build ComputeSharp.Sample.NuGet (.NET 6)
run: dotnet build samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj -c Release -f net6.0
- name: Build ComputeSharp.NuGet (.NET 6)
run: dotnet build tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj -c Release -f net6.0
shell: cmd
- name: Run ComputeSharp.Sample.NuGet (.NET 6)
run: dotnet samples\ComputeSharp.Sample.NuGet\bin\Release\net6.0\ComputeSharp.Sample.NuGet.dll
- name: Run ComputeSharp.NuGet (.NET 6)
run: dotnet tests\ComputeSharp.NuGet\bin\Release\net6.0\ComputeSharp.NuGet.dll
shell: cmd
- name: Build ComputeSharp.Sample.NuGet (.NET Core 3.1)
run: dotnet build samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj -c Release -f netcoreapp3.1 -r win-x64
- name: Build ComputeSharp.NuGet (.NET Core 3.1)
run: dotnet build tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj -c Release -f netcoreapp3.1 -r win-x64
shell: cmd
- name: Run ComputeSharp.Sample.NuGet (.NET Core 3.1)
run: samples\ComputeSharp.Sample.NuGet\bin\Release\netcoreapp3.1\win-x64\ComputeSharp.Sample.NuGet.exe
- name: Run ComputeSharp.NuGet (.NET Core 3.1)
run: tests\ComputeSharp.NuGet\bin\Release\netcoreapp3.1\win-x64\ComputeSharp.NuGet.exe
shell: cmd
- name: Build ComputeSharp.Sample.NuGet (.NET Framework 4.7.2)
run: dotnet build samples\ComputeSharp.Sample.NuGet\ComputeSharp.Sample.NuGet.csproj -c Release -f net472 /p:Platform=x64
- name: Build ComputeSharp.NuGet (.NET Framework 4.7.2)
run: dotnet build tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj -c Release -f net472 /p:Platform=x64
shell: cmd
- name: Run ComputeSharp.Sample.NuGet (.NET Framework 4.7.2)
run: samples\ComputeSharp.Sample.NuGet\bin\x64\Release\net472\ComputeSharp.Sample.NuGet.exe
- name: Run ComputeSharp.NuGet (.NET Framework 4.7.2)
run: tests\ComputeSharp.NuGet\bin\x64\Release\net472\ComputeSharp.NuGet.exe
shell: cmd
# Download the NuGet packages and test the ComputeSharp.Dynamic dependency
verify-packages-dynamic:
if: success()
needs: [build-packages]
runs-on: windows-2022
steps:
- name: Git checkout
uses: actions/checkout@v2
- name: Setup .NET 6 SDK
uses: actions/setup-dotnet@v1
with:
dotnet-version: 6.0.x
- name: Create local NuGet feed
run: mkdir artifacts
shell: cmd
- name: Download package artifacts
uses: actions/download-artifact@v2
with:
name: nuget_preview
path: artifacts
- name: Build ComputeSharp.Dynamic.NuGet (.NET 6)
run: dotnet build tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj -c Release -f net6.0
shell: cmd
- name: Run ComputeSharp.Dynamic.NuGet (.NET 6)
run: dotnet tests\ComputeSharp.Dynamic.NuGet\bin\Release\net6.0\ComputeSharp.Dynamic.NuGet.dll
shell: cmd
- name: Build ComputeSharp.Dynamic.NuGet (.NET Core 3.1)
run: dotnet build tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj -c Release -f netcoreapp3.1 -r win-x64
shell: cmd
- name: Run ComputeSharp.Dynamic.NuGet (.NET Core 3.1)
run: tests\ComputeSharp.Dynamic.NuGet\bin\Release\netcoreapp3.1\win-x64\ComputeSharp.Dynamic.NuGet.exe
shell: cmd
- name: Build ComputeSharp.Dynamic.NuGet (.NET Framework 4.7.2)
run: dotnet build tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj -c Release -f net472 /p:Platform=x64
shell: cmd
- name: Run ComputeSharp.Dynamic.NuGet (.NET Framework 4.7.2)
run: tests\ComputeSharp.Dynamic.NuGet\bin\x64\Release\net472\ComputeSharp.Dynamic.NuGet.exe
shell: cmd
# Download the NuGet packages and test the ComputeSharp.Pix dependency
verify-packages-pix:
if: success()
needs: [build-packages]
runs-on: windows-2022
steps:
- name: Git checkout
uses: actions/checkout@v2
- name: Setup .NET 6 SDK
uses: actions/setup-dotnet@v1
with:
dotnet-version: 6.0.x
- name: Create local NuGet feed
run: mkdir artifacts
shell: cmd
- name: Download package artifacts
uses: actions/download-artifact@v2
with:
name: nuget_preview
path: artifacts
- name: Build ComputeSharp.Pix.NuGet (.NET 6)
run: dotnet build tests\ComputeSharp.Pix.NuGet\ComputeSharp.Pix.NuGet.csproj -c Release -f net6.0
shell: cmd
- name: Run ComputeSharp.Pix.NuGet (.NET 6)
run: dotnet tests\ComputeSharp.Pix.NuGet\bin\Release\net6.0\ComputeSharp.Pix.NuGet.dll
shell: cmd
- name: Build ComputeSharp.Pix.NuGet (.NET Core 3.1)
run: dotnet build tests\ComputeSharp.Pix.NuGet\ComputeSharp.Pix.NuGet.csproj -c Release -f netcoreapp3.1 -r win-x64
shell: cmd
- name: Run ComputeSharp.Pix.NuGet (.NET Core 3.1)
run: tests\ComputeSharp.Pix.NuGet\bin\Release\netcoreapp3.1\win-x64\ComputeSharp.Pix.NuGet.exe
shell: cmd
- name: Build ComputeSharp.Pix.NuGet (.NET Framework 4.7.2)
run: dotnet build tests\ComputeSharp.Pix.NuGet\ComputeSharp.Pix.NuGet.csproj -c Release -f net472 /p:Platform=x64
shell: cmd
- name: Run ComputeSharp.Pix.NuGet (.NET Framework 4.7.2)
run: tests\ComputeSharp.Pix.NuGet\bin\x64\Release\net472\ComputeSharp.Pix.NuGet.exe
shell: cmd
# Run the extra tests to validate a number of build and publishing configurations.
@@ -287,7 +368,7 @@ jobs:
# Publish the packages to GitHub packages
publish-nightlies-github:
needs: [ run-dx12-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-package-native-libs ]
needs: [run-dx12-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs]
runs-on: windows-2022
if: ${{github.event_name == 'push'}}
steps:
@@ -303,7 +384,7 @@ jobs:
# Publish the packages to Azure DevOps
publish-nightlies-azure-devops:
needs: [ run-dx12-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-package-native-libs ]
needs: [run-dx12-tests, run-d2d1-tests, run-dx12-samples, verify-packages, verify-packages-dynamic, verify-packages-pix, verify-package-native-libs]
runs-on: windows-2022
if: ${{github.event_name == 'push'}}
steps:
+40 -1
ファイルの表示
@@ -28,12 +28,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SourceGenerators", "src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj", "{EB52CB67-4162-4722-874B-44EA8DA5450E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{FB17EF84-9208-47AC-921F-680CB1DAD8BA}"
ProjectSection(SolutionItems) = preProject
src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj = src\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj
src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj = src\ComputeSharp.D2D1.Package\ComputeSharp.D2D1.Package.msbuildproj
src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj = src\ComputeSharp.Dynamic.Package\ComputeSharp.Dynamic.Package.msbuildproj
src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj = src\ComputeSharp.Package\ComputeSharp.Package.msbuildproj
src\ComputeSharp.Pix.Package\ComputeSharp.Pix.Package.msbuildproj = src\ComputeSharp.Pix.Package\ComputeSharp.Pix.Package.msbuildproj
src\ComputeSharp.Core.Package\icon.png = src\ComputeSharp.Core.Package\icon.png
src\ComputeSharp.Core.Package\icon_highres.png = src\ComputeSharp.Core.Package\icon_highres.png
EndProjectSection
@@ -100,6 +101,29 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.Tests", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.Tests.AssemblyLevelAttributes", "tests\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes.csproj", "{94178D51-0097-4AD2-B3D0-827E40D62F2E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Pix", "src\ComputeSharp.Pix\ComputeSharp.Pix.csproj", "{14EF12A3-90E6-4683-BD71-9896AF87026B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.Dynamic.NuGet", "ComputeSharp.Dynamic.NuGet", "{CBA545B4-31EF-4E9F-A1A8-2A1290B54046}"
ProjectSection(SolutionItems) = preProject
tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj = tests\ComputeSharp.Dynamic.NuGet\ComputeSharp.Dynamic.NuGet.csproj
tests\ComputeSharp.Dynamic.NuGet\nuget.config = tests\ComputeSharp.Dynamic.NuGet\nuget.config
tests\ComputeSharp.Dynamic.NuGet\Program.cs = tests\ComputeSharp.Dynamic.NuGet\Program.cs
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.Pix.NuGet", "ComputeSharp.Pix.NuGet", "{C0B903AA-F32C-4760-B4B6-199AC4FE1C5A}"
ProjectSection(SolutionItems) = preProject
tests\ComputeSharp.Pix.NuGet\ComputeSharp.Pix.NuGet.csproj = tests\ComputeSharp.Pix.NuGet\ComputeSharp.Pix.NuGet.csproj
tests\ComputeSharp.Pix.NuGet\nuget.config = tests\ComputeSharp.Pix.NuGet\nuget.config
tests\ComputeSharp.Pix.NuGet\Program.cs = tests\ComputeSharp.Pix.NuGet\Program.cs
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ComputeSharp.NuGet", "ComputeSharp.NuGet", "{E3403F19-A0D8-4317-8A54-322C7A13F2A2}"
ProjectSection(SolutionItems) = preProject
tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj = tests\ComputeSharp.NuGet\ComputeSharp.NuGet.csproj
tests\ComputeSharp.NuGet\nuget.config = tests\ComputeSharp.NuGet\nuget.config
tests\ComputeSharp.NuGet\Program.cs = tests\ComputeSharp.NuGet\Program.cs
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -410,6 +434,18 @@ Global
{94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|ARM64.Build.0 = Release|Any CPU
{94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|x64.ActiveCfg = Release|Any CPU
{94178D51-0097-4AD2-B3D0-827E40D62F2E}.Release|x64.Build.0 = Release|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|ARM64.ActiveCfg = Debug|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|ARM64.Build.0 = Debug|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|x64.ActiveCfg = Debug|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Debug|x64.Build.0 = Debug|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|Any CPU.Build.0 = Release|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|ARM64.ActiveCfg = Release|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|ARM64.Build.0 = Release|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|x64.ActiveCfg = Release|Any CPU
{14EF12A3-90E6-4683-BD71-9896AF87026B}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -439,6 +475,9 @@ Global
{3ACACF03-6B20-40BA-B8EC-11AC1624D2C9} = {8DCE343F-BA78-4FE1-B562-B57C603A8BAA}
{209C95A3-FA53-431B-B688-3299CA6C29D2} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
{94178D51-0097-4AD2-B3D0-827E40D62F2E} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
{CBA545B4-31EF-4E9F-A1A8-2A1290B54046} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
{C0B903AA-F32C-4760-B4B6-199AC4FE1C5A} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
{E3403F19-A0D8-4317-8A54-322C7A13F2A2} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
+1 -1
ファイルの表示
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2019 Sergio Pedri
Copyright (c) 2022 Sergio Pedri
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+1
ファイルの表示
@@ -23,6 +23,7 @@ The sample app is available in the Microsoft Store, showcasing several pixel sha
| ------ | ------ | ------ |
| **ComputeSharp** | The main library, with compiled shaders support | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.svg)](https://www.nuget.org/packages/ComputeSharp/) |
| **ComputeSharp.Dynamic** | An extension for **ComputeSharp**, enabling dynamic shader compilation at runtime and shader metaprogramming | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.Dynamic.svg)](https://www.nuget.org/packages/ComputeSharp.Dynamic/) |
| **ComputeSharp.Pix** | An extension library for **ComputeSharp**, enabling PIX support to produce debugging information | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.Pix.svg)](https://www.nuget.org/packages/ComputeSharp.Pix/) |
| **ComputeSharp.Uwp** | A UWP library (targeting .NET Standard 2.0) with controls to render DX12 shaders powered by **ComputeSharp** | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.Uwp.svg)](https://www.nuget.org/packages/ComputeSharp.Uwp/) |
| **ComputeSharp.WinUI** | A WinUI 3 library (targeting .NET 6) with controls to render DX12 shaders powered by **ComputeSharp** | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.WinUI.svg)](https://www.nuget.org/packages/ComputeSharp.WinUI/) |
| **ComputeSharp.D2D1** | A library to write D2D1 pixel shaders entirely with C# code, and to easily register and create ID2D1Effect-s from them | [![NuGet](https://img.shields.io/nuget/vpre/ComputeSharp.D2D1.svg)](https://www.nuget.org/packages/ComputeSharp.D2D1/) |
+89
ファイルの表示
@@ -0,0 +1,89 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize
This project incorporates components from the projects listed below.
1. PIX on Windows (https://devblogs.microsoft.com/pix/winpixeventruntime/), included in ComputeSharp.Pix.
%% PIX on Windows NOTICES AND INFORMATION BEGIN HERE
=========================================
MICROSOFT SOFTWARE LICENSE TERMS
PIX EVENT RUNTIME FOR WINDOWS
IF YOU LIVE IN (OR ARE A BUSINESS WITH A PRINCIPAL PLACE OF BUSINESS IN) THE UNITED STATES, PLEASE READ THE “BINDING ARBITRATION AND CLASS ACTION WAIVER” SECTION BELOW. IT AFFECTS HOW DISPUTES ARE RESOLVED.
These license terms are an agreement between you and Microsoft Corporation (or one of its affiliates). They apply to the software named above and any Microsoft services or software updates (except to the extent such services or updates are accompanied by new or additional terms, in which case those different terms apply prospectively and do not alter your or Microsoft’s rights relating to pre-updated software or services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS.
1. INSTALLATION AND USE RIGHTS.
a. General. You may install and use any number of copies of the software to design, develop and test your Microsoft Windows programs.
b. Third Party Software. The software may include third party applications that are licensed to you under this agreement or under their own terms. License terms, notices, and acknowledgements, if any, for the third party applications may be accessible online at http://aka.ms/thirdpartynotices or in an accompanying notices file. Even if such applications are governed by other agreements, the disclaimer, limitations on, and exclusions of damages below also apply to the extent allowed by applicable law.
2. DISTRIBUTABLE CODE.
a. Distributable Code. The software is comprised of Distributable Code. “Distributable Code” is code that you are permitted to distribute in programs you develop if you comply with the terms below.
(i) Right to Use and Distribute.
* You may copy and distribute the object code form of the software.
* Third Party Distribution. You may permit distributors of your programs to copy and distribute the Distributable Code as part of those programs.
(ii) Distribution Requirements. For any Distributable Code you distribute, you must
* add significant primary functionality to it in your programs;
* require distributors and external end users to agree to terms that protect it at least as much as this agreement;
* display your valid copyright notice on your programs; and
* indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your programs.
(iii) Distribution Restrictions. You may not
* alter any copyright, trademark or patent notice in the Distributable Code;
* use Microsoft’s trademarks in your programs’ names or in a way that suggests your programs come from or are endorsed by Microsoft;
* distribute Distributable Code to run on a platform other than a Windows platform;
* include Distributable Code in malicious, deceptive or unlawful programs; or
* modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An Excluded License is one that requires, as a condition of use, modification or distribution, that
* the code be disclosed or distributed in source code form; or
* others have the right to modify it.
3. SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to):
a. work around any technical limitations in the software that only allow you to use it in certain ways;
b. reverse engineer, decompile or disassemble the software;
c. remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software;
d. use the software in any way that is against the law or to create or propagate malware; or
e. share, publish, distribute, or lend the software, provide the software as a stand-alone hosted solution for others to use, or transfer the software or this agreement to any third party.
4. EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit http://aka.ms/exporting.
5. SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
6. BINDING ARBITRATION AND CLASS ACTION WAIVER. This Section applies if you live in (or, if a business, your principal place of business is in) the United States. If you and Microsoft have a dispute, you and Microsoft agree to try for 60 days to resolve it informally. If you and Microsoft can’t, you and Microsoft agree to binding individual arbitration before the American Arbitration Association under the Federal Arbitration Act (“FAA”), and not to sue in court in front of a judge or jury. Instead, a neutral arbitrator will decide. Class action lawsuits, class-wide arbitrations, private attorney-general actions, and any other proceeding where someone acts in a representative capacity are not allowed; nor is combining individual proceedings without the consent of all parties. The complete Arbitration Agreement contains more terms and is at http://aka.ms/arb-agreement-1. You and Microsoft agree to these terms.
7. ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software.
8. APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles, except that the FAA governs everything related to arbitration. If you acquired the software in any other country, its laws apply, except that the FAA governs everything related to arbitration. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court (excluding arbitration). If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court (excluding arbitration).
9. CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state, province, or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state, province, or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you:
a. Australia. You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights.
b. Canada. If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from the Internet (if and when you re-connect to the Internet, however, the software will resume checking for and installing updates), or uninstalling the software. The product documentation, if any, may also specify how to turn off updates for your specific device or software.
c. Germany and Austria.
(i) Warranty. The properly licensed software will perform substantially as described in any Microsoft materials that accompany the software. However, Microsoft gives no contractual guarantee in relation to the licensed software.
(ii) Limitation of Liability. In case of intentional conduct, gross negligence, claims based on the Product Liability Act, as well as, in case of death or personal or physical injury, Microsoft is liable according to the statutory law.
Subject to the foregoing clause (ii), Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence.
10. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
11. LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to (a) anything related to the software, services, content (including code) on third party Internet sites, or third party applications; and (b) claims for breach of contract, warranty, guarantee, or condition; strict liability, negligence, or other tort; or any other claim; in each case to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state, province, or country may not allow the exclusion or limitation of incidental, consequential, or other damages.
[Please note: As this software is distributed in Canada, some of the clauses in this agreement are provided below in French.
Remarque: Ce logiciel étant distribué au Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne:
* tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers; et
* les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.]
=========================================
END OF PIX on Windows NOTICES AND INFORMATION
+3 -3
ファイルの表示
@@ -21,9 +21,9 @@
<ItemGroup Label="Package">
<!-- Include the custom .targets file to check the source generator (.NET 6 is not needed as it guarantees Roslyn 4.x) -->
<None Include="..\ComputeSharp.Core\ComputeSharp.Core.targets" PackagePath="buildTransitive\netstandard2.0" Pack="true" />
<None Include="..\ComputeSharp.Core\ComputeSharp.Core.targets" PackagePath="build\netstandard2.0" Pack="true" />
<!-- Include the custom .targets file to check the source generator -->
<None Include="..\ComputeSharp.Core\ComputeSharp.Core.targets" PackagePath="buildTransitive\ComputeSharp.Core.targets" Pack="true" />
<None Include="..\ComputeSharp.Core\ComputeSharp.Core.targets" PackagePath="build\ComputeSharp.Core.targets" Pack="true" />
</ItemGroup>
</Project>
+1 -1
ファイルの表示
@@ -16,7 +16,7 @@ namespace ComputeSharp.Core.SourceGenerators;
/// A source generator creating constructors for types annotated with <see cref="AutoConstructorAttribute"/>.
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed partial class AutoConstructorGenerator : IIncrementalGenerator
public sealed class AutoConstructorGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
+4 -4
ファイルの表示
@@ -18,20 +18,20 @@
the same version) but Microsoft.Build.Tasks.CodeAnalysis.dll is where MSBuild loads the compiler tasks from so if
someone is getting creative with msbuild tasks/targets this is the "most correct" assembly to check. -->
<GetAssemblyIdentity AssemblyFiles="$([System.IO.Path]::Combine(`$([System.IO.Path]::GetDirectoryName($(CSharpCoreTargetsPath)))`,`Microsoft.Build.Tasks.CodeAnalysis.dll`))">
<Output TaskParameter="Assemblies" ItemName="CurrentCompilerAssemblyIdentity"/>
<Output TaskParameter="Assemblies" ItemName="ComputeSharpCoreCurrentCompilerAssemblyIdentity"/>
</GetAssemblyIdentity>
<PropertyGroup>
<!-- Transform the resulting item from GetAssemblyIdentity into a property representing its assembly version -->
<CurrentCompilerVersion>@(CurrentCompilerAssemblyIdentity->'%(Version)')</CurrentCompilerVersion>
<ComputeSharpCoreCurrentCompilerVersion>@(ComputeSharpCoreCurrentCompilerAssemblyIdentity->'%(Version)')</ComputeSharpCoreCurrentCompilerVersion>
<!-- The CurrentCompilerVersionIsNotNewEnough property can now be defined based on the Roslyn assembly version -->
<CurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(CurrentCompilerVersion), 4.2))">true</CurrentCompilerVersionIsNotNewEnough>
<ComputeSharpCoreCurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(ComputeSharpCoreCurrentCompilerVersion), 4.2))">true</ComputeSharpCoreCurrentCompilerVersionIsNotNewEnough>
</PropertyGroup>
<!-- If the Roslyn version is < 4.2, disable the source generators -->
<ItemGroup Condition ="'$(CurrentCompilerVersionIsNotNewEnough)' == 'true'">
<ItemGroup Condition ="'$(ComputeSharpCoreCurrentCompilerVersionIsNotNewEnough)' == 'true'">
<Analyzer Remove="@(_ComputeSharpCoreAnalyzer)"/>
</ItemGroup>
+3 -3
ファイルの表示
@@ -27,9 +27,9 @@
<ItemGroup Label="Package">
<!-- Include the custom .targets file to check the source generator (.NET 6 is not needed as it guarantees Roslyn 4.x) -->
<None Include="..\ComputeSharp.D2D1\ComputeSharp.D2D1.targets" PackagePath="buildTransitive\netstandard2.0" Pack="true" />
<None Include="..\ComputeSharp.D2D1\ComputeSharp.D2D1.targets" PackagePath="build\netstandard2.0" Pack="true" />
<!-- Include the custom .targets file to check the source generator -->
<None Include="..\ComputeSharp.D2D1\ComputeSharp.D2D1.targets" PackagePath="buildTransitive\ComputeSharp.D2D1.targets" Pack="true" />
<None Include="..\ComputeSharp.D2D1\ComputeSharp.D2D1.targets" PackagePath="build\ComputeSharp.D2D1.targets" Pack="true" />
</ItemGroup>
</Project>
@@ -7,7 +7,7 @@ using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptor
namespace ComputeSharp.D2D1.SourceGenerators.SyntaxRewriters;
/// <inheritdoc cref="HlslSourceRewriter"/>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
+5 -5
ファイルの表示
@@ -18,27 +18,27 @@
the same version) but Microsoft.Build.Tasks.CodeAnalysis.dll is where MSBuild loads the compiler tasks from so if
someone is getting creative with msbuild tasks/targets this is the "most correct" assembly to check. -->
<GetAssemblyIdentity AssemblyFiles="$([System.IO.Path]::Combine(`$([System.IO.Path]::GetDirectoryName($(CSharpCoreTargetsPath)))`,`Microsoft.Build.Tasks.CodeAnalysis.dll`))">
<Output TaskParameter="Assemblies" ItemName="CurrentCompilerAssemblyIdentity"/>
<Output TaskParameter="Assemblies" ItemName="ComputeSharpD2D1CurrentCompilerAssemblyIdentity"/>
</GetAssemblyIdentity>
<PropertyGroup>
<!-- Transform the resulting item from GetAssemblyIdentity into a property representing its assembly version -->
<CurrentCompilerVersion>@(CurrentCompilerAssemblyIdentity->'%(Version)')</CurrentCompilerVersion>
<ComputeSharpD2D1CurrentCompilerVersion>@(ComputeSharpD2D1CurrentCompilerAssemblyIdentity->'%(Version)')</ComputeSharpD2D1CurrentCompilerVersion>
<!-- The CurrentCompilerVersionIsNotNewEnough property can now be defined based on the Roslyn assembly version -->
<CurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(CurrentCompilerVersion), 4.2))">true</CurrentCompilerVersionIsNotNewEnough>
<ComputeSharpD2D1CurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(ComputeSharpD2D1CurrentCompilerVersion), 4.2))">true</ComputeSharpD2D1CurrentCompilerVersionIsNotNewEnough>
</PropertyGroup>
<!-- If the Roslyn version is < 4.2, disable the source generators -->
<ItemGroup Condition ="'$(CurrentCompilerVersionIsNotNewEnough)' == 'true'">
<ItemGroup Condition ="'$(ComputeSharpD2D1CurrentCompilerVersionIsNotNewEnough)' == 'true'">
<Analyzer Remove="@(_ComputeSharpD2D1Analyzer)"/>
</ItemGroup>
<!-- If the source generators are disabled, also emit an error. This would've been produced by MSBuild itself as well, but
emitting this manually lets us customize the message to inform developers as to why exactly the generators have been
disabled, and that ComputeSharp will not work at all unless a more up to date IDE or compiler version are used. -->
<Error Condition ="'$(CurrentCompilerVersionIsNotNewEnough)' == 'true'" Text="The ComputeSharp.D2D1 source generators have been disabled on the current configuration, as they need Roslyn 4.2 in order to work. ComputeSharp.D2D1 requires the source generators to run in order to process shaders, so the library cannot be used without a more up to date IDE (eg. VS2022) or .NET SDK version."/>
<Error Condition ="'$(ComputeSharpD2D1CurrentCompilerVersionIsNotNewEnough)' == 'true'" Text="The ComputeSharp.D2D1 source generators have been disabled on the current configuration, as they need Roslyn 4.2 in order to work. ComputeSharp.D2D1 requires the source generators to run in order to process shaders, so the library cannot be used without a more up to date IDE (eg. VS2022) or .NET SDK version."/>
</Target>
<!-- Remove the analyzer if Roslyn is missing -->
+1 -1
ファイルの表示
@@ -6,7 +6,7 @@ namespace ComputeSharp.D2D1.Helpers;
/// <summary>
/// Helper methods to efficiently throw exceptions.
/// </summary>
internal static partial class ThrowHelper
internal static class ThrowHelper
{
/// <summary>
/// Throws a new <see cref="ArgumentException"/>.
@@ -4,7 +4,7 @@ using System.Collections.Generic;
namespace ComputeSharp.__Internals;
/// <inheritdoc/>
public sealed partial class ShaderMethodSourceAttribute : Attribute
partial class ShaderMethodSourceAttribute : Attribute
{
/// <summary>
/// Appends the mapped source code for the current method.
+1 -1
ファイルの表示
@@ -9,7 +9,7 @@ using TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation;
/// <inheritdoc cref="ShaderCompiler"/>
internal sealed unsafe partial class ShaderCompiler
unsafe partial class ShaderCompiler
{
/// <summary>
/// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
+3 -3
ファイルの表示
@@ -27,9 +27,9 @@
<ItemGroup Label="Package">
<!-- Include the custom .targets file to check the source generator (.NET 6 is not needed as it guarantees Roslyn 4.x) -->
<None Include="..\ComputeSharp\ComputeSharp.targets" PackagePath="buildTransitive\netstandard2.0" Pack="true" />
<None Include="..\ComputeSharp\ComputeSharp.targets" PackagePath="build\netstandard2.0" Pack="true" />
<!-- Include the custom .targets file to check the source generator -->
<None Include="..\ComputeSharp\ComputeSharp.targets" PackagePath="buildTransitive\ComputeSharp.targets" Pack="true" />
<None Include="..\ComputeSharp\ComputeSharp.targets" PackagePath="build\ComputeSharp.targets" Pack="true" />
</ItemGroup>
</Project>
+51
ファイルの表示
@@ -0,0 +1,51 @@
<Project Sdk="Microsoft.Build.NoTargets/2.0.1" DefaultTargets="Pack">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<PackageId>ComputeSharp.Pix</PackageId>
<Title>ComputeSharp.Pix</Title>
<Description>An extension library for ComputeSharp to enable PIX support to produce debugging information</Description>
</PropertyGroup>
<ItemGroup>
<Content Include="..\ComputeSharp.Core.Package\icon.png" PackFolder="\" />
</ItemGroup>
<!-- Include the PIX license file -->
<ItemGroup>
<Content Include="..\ComputeSharp.Pix\LICENSE.txt" PackFolder="\" />
</ItemGroup>
<PropertyGroup>
<PackageLicenseExpression></PackageLicenseExpression>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ComputeSharp.Pix\ComputeSharp.Pix.csproj" />
<ProjectReference Include="..\ComputeSharp.Package\ComputeSharp.Package.msbuildproj" TargetFramework="net6.0">
<AdditionalProperties>PackageVersion=$(PackageVersion)</AdditionalProperties>
</ProjectReference>
<ProjectReference Include="..\ComputeSharp.Package\ComputeSharp.Package.msbuildproj" TargetFramework="netstandard2.0">
<AdditionalProperties>PackageVersion=$(PackageVersion)</AdditionalProperties>
</ProjectReference>
<!-- Also include the ComputeSharp.Core reference, so that it's packed as a package reference, and not as binaries (same as in ComputeSharp.Dynamic) -->
<ProjectReference Include="..\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj" TargetFramework="net6.0">
<AdditionalProperties>PackageVersion=$(PackageVersion)</AdditionalProperties>
</ProjectReference>
<ProjectReference Include="..\ComputeSharp.Core.Package\ComputeSharp.Core.Package.msbuildproj" TargetFramework="netstandard2.0">
<AdditionalProperties>PackageVersion=$(PackageVersion)</AdditionalProperties>
</ProjectReference>
</ItemGroup>
<ItemGroup Label="Package">
<!-- Include the custom .targets file extract the PIX native libraries -->
<None Include="..\ComputeSharp.Pix\ComputeSharp.Pix.targets" PackagePath="buildTransitive\ComputeSharp.Pix.targets" Pack="true" />
<None Include="..\ComputeSharp.Pix\ComputeSharp.Pix.targets" PackagePath="build\ComputeSharp.Pix.targets" Pack="true" />
</ItemGroup>
</Project>
+281
ファイルの表示
@@ -0,0 +1,281 @@
using System;
using System.Diagnostics;
using System.Drawing;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Interop;
namespace ComputeSharp;
/// <summary>
/// A <see langword="class"/> that contains extension methods using PIX APIs for the <see cref="ComputeContext"/> type.
/// </summary>
public static class ComputeContextExtensions
{
/// <summary>
/// Starts a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to start the PIX event.</param>
/// <param name="color">The color to use for the event (the alpha channel will be ignored).</param>
/// <param name="message">The message to use for the event.</param>
[Conditional("USE_PIX")]
public static unsafe void BeginEvent(this in ComputeContext context, Color color, string message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
int argb = color.ToArgb();
uint pixColor = Pix.PIX_COLOR((byte)((argb & 0x00FF0000) >> 16), (byte)((argb & 0x0000FF00) >> 8), (byte)(argb & 0x000000FF));
commandList.D3D12GraphicsCommandList->BeginEvent(pixColor, message);
}
/// <summary>
/// Starts a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to start the PIX event.</param>
/// <param name="index">The index to identify the group this event belongs to (PIX will choose a color to represent all entries in the group).</param>
/// <param name="message">The message to use for the event.</param>
[Conditional("USE_PIX")]
public static unsafe void BeginEvent(this in ComputeContext context, byte index, string message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
uint pixColor = Pix.PIX_COLOR_INDEX(index);
commandList.D3D12GraphicsCommandList->BeginEvent(pixColor, message);
}
/// <summary>
/// Starts a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to start the PIX event.</param>
/// <param name="message">The message to use for the event.</param>
[Conditional("USE_PIX")]
public static unsafe void BeginEvent(this in ComputeContext context, string message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
commandList.D3D12GraphicsCommandList->BeginEvent(0, message);
}
/// <summary>
/// Starts a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to start the PIX event.</param>
/// <param name="color">The color to use for the event (the alpha channel will be ignored).</param>
/// <param name="message">The message to use for the event (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
/// <remarks>
/// <para>
/// The <paramref name="message"/> parameter is not checked to ensure it has a <see langword="null"/>-terminator. This allows callers
/// to pass an UTF8 string literal containing only ASCII characters (as the byte contents would be a valid ANSI sequence in that case).
/// The compiler will automatically insert a terminator right past the end of the returned <see cref="ReadOnlySpan{T}"/> when doing so.
/// </para>
/// <para>
/// This method offers greatly reduced overhead compared to the overlods taking a <see cref="string"/>, as there is no need to create the
/// <see cref="string"/> instance nor to execute the transcoding at runtime. The behavior when the input is invalid though is undefined.
/// Callers must take extra care to ensure the input message is in fact <see langword="null"/>-terminated when invoking this API.
/// </para>
/// </remarks>
[Conditional("USE_PIX")]
public static unsafe void BeginEventUnsafe(this in ComputeContext context, Color color, ReadOnlySpan<byte> message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
int argb = color.ToArgb();
uint pixColor = Pix.PIX_COLOR((byte)((argb & 0x00FF0000) >> 16), (byte)((argb & 0x0000FF00) >> 8), (byte)(argb & 0x000000FF));
commandList.D3D12GraphicsCommandList->BeginEventUnsafe(pixColor, message);
}
/// <summary>
/// Starts a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to start the PIX event.</param>
/// <param name="index">The index to identify the group this event belongs to (PIX will choose a color to represent all entries in the group).</param>
/// <param name="message">The message to use for the event (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
/// <remarks>
/// <para>
/// The <paramref name="message"/> parameter is not checked to ensure it has a <see langword="null"/>-terminator. This allows callers
/// to pass an UTF8 string literal containing only ASCII characters (as the byte contents would be a valid ANSI sequence in that case).
/// The compiler will automatically insert a terminator right past the end of the returned <see cref="ReadOnlySpan{T}"/> when doing so.
/// </para>
/// <para>
/// This method offers greatly reduced overhead compared to the overlods taking a <see cref="string"/>, as there is no need to create the
/// <see cref="string"/> instance nor to execute the transcoding at runtime. The behavior when the input is invalid though is undefined.
/// Callers must take extra care to ensure the input message is in fact <see langword="null"/>-terminated when invoking this API.
/// </para>
/// </remarks>
[Conditional("USE_PIX")]
public static unsafe void BeginEventUnsafe(this in ComputeContext context, byte index, ReadOnlySpan<byte> message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
uint pixColor = Pix.PIX_COLOR_INDEX(index);
commandList.D3D12GraphicsCommandList->BeginEventUnsafe(pixColor, message);
}
/// <summary>
/// Starts a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to start the PIX event.</param>
/// <param name="message">The message to use for the event (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
/// <remarks>
/// <para>
/// The <paramref name="message"/> parameter is not checked to ensure it has a <see langword="null"/>-terminator. This allows callers
/// to pass an UTF8 string literal containing only ASCII characters (as the byte contents would be a valid ANSI sequence in that case).
/// The compiler will automatically insert a terminator right past the end of the returned <see cref="ReadOnlySpan{T}"/> when doing so.
/// </para>
/// <para>
/// This method offers greatly reduced overhead compared to the overlods taking a <see cref="string"/>, as there is no need to create the
/// <see cref="string"/> instance nor to execute the transcoding at runtime. The behavior when the input is invalid though is undefined.
/// Callers must take extra care to ensure the input message is in fact <see langword="null"/>-terminated when invoking this API.
/// </para>
/// </remarks>
[Conditional("USE_PIX")]
public static unsafe void BeginEventUnsafe(this in ComputeContext context, ReadOnlySpan<byte> message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
commandList.D3D12GraphicsCommandList->BeginEventUnsafe(0, message);
}
/// <summary>
/// Ends a PIX event on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to end the PIX event.</param>
[Conditional("USE_PIX")]
public static unsafe void EndEvent(this in ComputeContext context)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
Pix.PIXEndEventOnCommandList(commandList.D3D12GraphicsCommandList);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the PIX marker.</param>
/// <param name="color">The color to use for the log (the alpha channel will be ignored).</param>
/// <param name="message">The message to use for the marker.</param>
[Conditional("USE_PIX")]
public static unsafe void Log(this in ComputeContext context, Color color, string message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
int argb = color.ToArgb();
uint pixColor = Pix.PIX_COLOR((byte)((argb & 0x00FF0000) >> 16), (byte)((argb & 0x0000FF00) >> 8), (byte)(argb & 0x000000FF));
commandList.D3D12GraphicsCommandList->SetPixMarker(pixColor, message);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the PIX marker.</param>
/// <param name="index">The index to identify the group this log belongs to (PIX will choose a color to represent all entries in the group).</param>
/// <param name="message">The message to use for the marker.</param>
[Conditional("USE_PIX")]
public static unsafe void Log(this in ComputeContext context, byte index, string message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
uint pixColor = Pix.PIX_COLOR_INDEX(index);
commandList.D3D12GraphicsCommandList->SetPixMarker(pixColor, message);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the PIX marker.</param>
/// <param name="message">The message to use for the marker.</param>
[Conditional("USE_PIX")]
public static unsafe void Log(this in ComputeContext context, string message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
commandList.D3D12GraphicsCommandList->SetPixMarker(0, message);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the PIX marker.</param>
/// <param name="color">The color to use for the log (the alpha channel will be ignored).</param>
/// <param name="message">The message to use for the marker (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
/// <remarks>
/// <para>
/// The <paramref name="message"/> parameter is not checked to ensure it has a <see langword="null"/>-terminator. This allows callers
/// to pass an UTF8 string literal containing only ASCII characters (as the byte contents would be a valid ANSI sequence in that case).
/// The compiler will automatically insert a terminator right past the end of the returned <see cref="ReadOnlySpan{T}"/> when doing so.
/// </para>
/// <para>
/// This method offers greatly reduced overhead compared to the overlods taking a <see cref="string"/>, as there is no need to create the
/// <see cref="string"/> instance nor to execute the transcoding at runtime. The behavior when the input is invalid though is undefined.
/// Callers must take extra care to ensure the input message is in fact <see langword="null"/>-terminated when invoking this API.
/// </para>
/// </remarks>
[Conditional("USE_PIX")]
public static unsafe void LogUnsafe(this in ComputeContext context, Color color, ReadOnlySpan<byte> message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
int argb = color.ToArgb();
uint pixColor = Pix.PIX_COLOR((byte)((argb & 0x00FF0000) >> 16), (byte)((argb & 0x0000FF00) >> 8), (byte)(argb & 0x000000FF));
commandList.D3D12GraphicsCommandList->SetPixMarkerUnsafe(pixColor, message);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the PIX marker.</param>
/// <param name="index">The index to identify the group this log belongs to (PIX will choose a color to represent all entries in the group).</param>
/// <param name="message">The message to use for the marker (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
/// <remarks>
/// <para>
/// The <paramref name="message"/> parameter is not checked to ensure it has a <see langword="null"/>-terminator. This allows callers
/// to pass an UTF8 string literal containing only ASCII characters (as the byte contents would be a valid ANSI sequence in that case).
/// The compiler will automatically insert a terminator right past the end of the returned <see cref="ReadOnlySpan{T}"/> when doing so.
/// </para>
/// <para>
/// This method offers greatly reduced overhead compared to the overlods taking a <see cref="string"/>, as there is no need to create the
/// <see cref="string"/> instance nor to execute the transcoding at runtime. The behavior when the input is invalid though is undefined.
/// Callers must take extra care to ensure the input message is in fact <see langword="null"/>-terminated when invoking this API.
/// </para>
/// </remarks>
[Conditional("USE_PIX")]
public static unsafe void LogUnsafe(this in ComputeContext context, byte index, ReadOnlySpan<byte> message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
uint pixColor = Pix.PIX_COLOR_INDEX(index);
commandList.D3D12GraphicsCommandList->SetPixMarkerUnsafe(pixColor, message);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ComputeContext"/> object.
/// </summary>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the PIX marker.</param>
/// <param name="message">The message to use for the marker (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
/// <remarks>
/// <para>
/// The <paramref name="message"/> parameter is not checked to ensure it has a <see langword="null"/>-terminator. This allows callers
/// to pass an UTF8 string literal containing only ASCII characters (as the byte contents would be a valid ANSI sequence in that case).
/// The compiler will automatically insert a terminator right past the end of the returned <see cref="ReadOnlySpan{T}"/> when doing so.
/// </para>
/// <para>
/// This method offers greatly reduced overhead compared to the overlods taking a <see cref="string"/>, as there is no need to create the
/// <see cref="string"/> instance nor to execute the transcoding at runtime. The behavior when the input is invalid though is undefined.
/// Callers must take extra care to ensure the input message is in fact <see langword="null"/>-terminated when invoking this API.
/// </para>
/// </remarks>
[Conditional("USE_PIX")]
public static unsafe void LogUnsafe(this in ComputeContext context, ReadOnlySpan<byte> message)
{
ref CommandList commandList = ref ComputeContext.GetCommandList(in context, pipelineState: null);
commandList.D3D12GraphicsCommandList->SetPixMarkerUnsafe(0, message);
}
}
+70
ファイルの表示
@@ -0,0 +1,70 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net6.0</TargetFrameworks>
<OutputPath>bin\Release</OutputPath>
<DocumentationFile>ComputeSharp.Pix.xml</DocumentationFile>
<Platforms>AnyCPU;x64;ARM64</Platforms>
</PropertyGroup>
<!-- Enable trimming support on .NET 6 -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net6.0'">
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
<!-- Reference to the main library-->
<ItemGroup>
<ProjectReference Include="..\ComputeSharp\ComputeSharp.csproj" />
</ItemGroup>
<Choose>
<!-- When building locally for x64/ARM64, only support the non-UAP libraries -->
<When Condition="'$(Platform)' == 'x64'">
<ItemGroup>
<None Include="Libraries\x64\WinPixEventRuntime.dll"
Link="WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</When>
<When Condition="'$(Platform)' == 'ARM64'">
<ItemGroup>
<None Include="Libraries\arm64\WinPixEventRuntime.dll"
Link="WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</When>
<!-- When no RID is specified, it means the NuGet package is being packed. In this case,
copy all libraries, and then rely on the custom .targets file to unpack them correctly. -->
<Otherwise>
<PropertyGroup>
<WinPixEventRuntimeVersion>winpixeventruntime.1.0.220124001</WinPixEventRuntimeVersion>
</PropertyGroup>
<ItemGroup>
<None Include="Libraries\x64\WinPixEventRuntime.dll"
Link="$(WinPixEventRuntimeVersion)\x64\WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest"
PackFolder="$(WinPixEventRuntimeVersion)\x64" />
<None Include="Libraries\x64\WinPixEventRuntime_UAP.dll"
Link="$(WinPixEventRuntimeVersion)\x64\WinPixEventRuntime_UAP.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest"
PackFolder="$(WinPixEventRuntimeVersion)\x64" />
<None Include="Libraries\arm64\WinPixEventRuntime.dll"
Link="$(WinPixEventRuntimeVersion)\arm64\WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest"
PackFolder="$(WinPixEventRuntimeVersion)\arm64" />
<None Include="Libraries\arm64\WinPixEventRuntime_UAP.dll"
Link="$(WinPixEventRuntimeVersion)\arm64\WinPixEventRuntime_UAP.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest"
PackFolder="$(WinPixEventRuntimeVersion)\arm64" />
</ItemGroup>
</Otherwise>
</Choose>
</Project>
+53
ファイルの表示
@@ -0,0 +1,53 @@
<Project>
<!-- Get the analyzer from the ComputeSharp.Pix NuGet package -->
<Target Name="_ComputeSharpPixLinkNativeLibraries"
AfterTargets="ResolvePackageDependenciesForBuild;ResolveNuGetPackageAssets"
BeforeTargets="CheckForDuplicateItems;PrepareForBuild">
<PropertyGroup>
<!-- PIX version (this needs to be kept in sync with the one in the .csproj) -->
<ComputeSharpPixWinPixEventRuntimeVersion>winpixeventruntime.1.0.220124001</ComputeSharpPixWinPixEventRuntimeVersion>
<!-- Detect whether the target project is UWP-->
<ComputeSharpPixShouldUnpackUapPixNativeLibraries>false</ComputeSharpPixShouldUnpackUapPixNativeLibraries>
<ComputeSharpPixShouldUnpackUapPixNativeLibraries Condition="'$(TargetFrameworkIdentifier)' == 'UAP'">true</ComputeSharpPixShouldUnpackUapPixNativeLibraries>
<!-- Detect the target project CPU architecture -->
<ComputeSharpPixShouldUnpackArm64PixNativeLibraries>false</ComputeSharpPixShouldUnpackArm64PixNativeLibraries>
<ComputeSharpPixShouldUnpackArm64PixNativeLibraries Condition="'$(Platform)' == 'arm64'">true</ComputeSharpPixShouldUnpackArm64PixNativeLibraries>
</PropertyGroup>
<!-- Win32, x64 -->
<ItemGroup Condition="'$(ComputeSharpPixShouldUnpackUapPixNativeLibraries)' == 'False' AND '$(ComputeSharpPixShouldUnpackArm64PixNativeLibraries)' == 'False'">
<None Include="$(MSBuildThisFileDirectory)..\$(ComputeSharpPixWinPixEventRuntimeVersion)\x64\WinPixEventRuntime.dll"
Link="WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<!-- Win32, arm64 -->
<ItemGroup Condition="'$(ComputeSharpPixShouldUnpackUapPixNativeLibraries)' == 'False' AND '$(ComputeSharpPixShouldUnpackArm64PixNativeLibraries)' == 'True'">
<None Include="$(MSBuildThisFileDirectory)..\$(ComputeSharpPixWinPixEventRuntimeVersion)\arm64\WinPixEventRuntime.dll"
Link="WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<!-- UWP, x64 -->
<ItemGroup Condition="'$(ComputeSharpPixShouldUnpackUapPixNativeLibraries)' == 'True' AND '$(ComputeSharpPixShouldUnpackArm64PixNativeLibraries)' == 'False'">
<None Include="$(MSBuildThisFileDirectory)..\$(ComputeSharpPixWinPixEventRuntimeVersion)\x64\WinPixEventRuntime_UAP.dll"
Link="WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<!-- UWP, arm64 -->
<ItemGroup Condition="'$(ComputeSharpPixShouldUnpackUapPixNativeLibraries)' == 'True' AND '$(ComputeSharpPixShouldUnpackArm64PixNativeLibraries)' == 'True'">
<None Include="$(MSBuildThisFileDirectory)..\$(ComputeSharpPixWinPixEventRuntimeVersion)\arm64\WinPixEventRuntime_UAP.dll"
Link="WinPixEventRuntime.dll"
Visible="False"
CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>
+105
ファイルの表示
@@ -0,0 +1,105 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Text;
using TerraFX.Interop.DirectX;
namespace ComputeSharp.Interop;
/// <summary>
/// A <see langword="class"/> with extensions for the <see cref="ID3D12GraphicsCommandList"/> type.
/// </summary>
internal static class ID3D12GraphicsCommandListExtensions
{
/// <summary>
/// Begins a PIX event on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
/// <param name="color">The color to use for the event.</param>
/// <param name="message">The message to use for the event.</param>
public static unsafe void BeginEvent(this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, uint color, string message)
{
// Rent a byte buffer with space for the null-terminator too
int maxByteLength = Encoding.ASCII.GetMaxByteCount(message.Length) + 1;
byte[] buffer = ArrayPool<byte>.Shared.Rent(maxByteLength);
int bytesWritten;
fixed (byte* bufferPtr = buffer)
{
// Transcode from unicode to ASCII
fixed (char* messagePtr = message)
{
bytesWritten = Encoding.ASCII.GetBytes(messagePtr, message.Length, bufferPtr, buffer.Length);
}
// Add the null terminator
buffer[bytesWritten] = 0;
// Write the marker with the null-terminated ANSI message
Pix.PIXBeginEventOnCommandList((ID3D12GraphicsCommandList*)Unsafe.AsPointer(ref d3D12GraphicsCommandList), color, (sbyte*)bufferPtr);
}
// Return the buffer (if an exception is thrown, it's fine to not do so)
ArrayPool<byte>.Shared.Return(buffer);
}
/// <summary>
/// Begins a PIX event on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
/// <param name="color">The color to use for the event.</param>
/// <param name="message">The message to use for the event (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
public static unsafe void BeginEventUnsafe(this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, uint color, ReadOnlySpan<byte> message)
{
fixed (byte* messagePtr = message)
{
Pix.PIXBeginEventOnCommandList((ID3D12GraphicsCommandList*)Unsafe.AsPointer(ref d3D12GraphicsCommandList), color, (sbyte*)messagePtr);
}
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
/// <param name="color">The color to use for the marker.</param>
/// <param name="message">The message to use for the marker.</param>
public static unsafe void SetPixMarker(this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, uint color, string message)
{
// Rent a byte buffer with space for the null-terminator too
int maxByteLength = Encoding.ASCII.GetMaxByteCount(message.Length) + 1;
byte[] buffer = ArrayPool<byte>.Shared.Rent(maxByteLength);
int bytesWritten;
fixed (byte* bufferPtr = buffer)
{
// Transcode from unicode to ASCII
fixed (char* messagePtr = message)
{
bytesWritten = Encoding.ASCII.GetBytes(messagePtr, message.Length, bufferPtr, buffer.Length);
}
// Add the null terminator
buffer[bytesWritten] = 0;
// Write the marker with the null-terminated ANSI message
Pix.PIXSetMarkerOnCommandList((ID3D12GraphicsCommandList*)Unsafe.AsPointer(ref d3D12GraphicsCommandList), color, (sbyte*)bufferPtr);
}
// Return the buffer (if an exception is thrown, it's fine to not do so)
ArrayPool<byte>.Shared.Return(buffer);
}
/// <summary>
/// Sets a PIX marker on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
/// <param name="color">The color to use for the marker.</param>
/// <param name="message">The message to use for the event (it's assumed to be a <see langword="null"/>-terminated ANSI characters sequence).</param>
public static unsafe void SetPixMarkerUnsafe(this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, uint color, ReadOnlySpan<byte> message)
{
fixed (byte* messagePtr = message)
{
Pix.PIXSetMarkerOnCommandList((ID3D12GraphicsCommandList*)Unsafe.AsPointer(ref d3D12GraphicsCommandList), color, (sbyte*)messagePtr);
}
}
}
+44
ファイルの表示
@@ -0,0 +1,44 @@
using System.Runtime.InteropServices;
using TerraFX.Interop.DirectX;
namespace ComputeSharp.Interop;
/// <summary>
/// A collection of native bindings for PIX APIs (see <see href="https://devblogs.microsoft.com/pix/winpixeventruntime/"/>).
/// </summary>
internal static unsafe partial class Pix
{
/// <summary>
/// Starts a PIX event on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// <para>
/// C export: <c>typedef void(WINAPI* BeginEventOnCommandList)(ID3D12GraphicsCommandList* commandList, UINT64 color, _In_ PCSTR formatString)</c>.
/// </para>
/// </summary>
/// <param name="commandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
/// <param name="color">The color to use for the event.</param>
/// <param name="formatString">The format string to use for the event (in ANSI format, <see langword="null"/>-terminated).</param>
[DllImport("WinPixEventRuntime", ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern void PIXBeginEventOnCommandList(ID3D12GraphicsCommandList* commandList, ulong color, sbyte* formatString);
/// <summary>
/// Ends a PIX event on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// <para>
/// C export: <c>typedef void(WINAPI* EndEventOnCommandList)(ID3D12GraphicsCommandList* commandList)</c>.
/// </para>
/// </summary>
/// <param name="commandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
[DllImport("WinPixEventRuntime", ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern void PIXEndEventOnCommandList(ID3D12GraphicsCommandList* commandList);
/// <summary>
/// Sets a PIX marker on a target <see cref="ID3D12GraphicsCommandList"/> object.
/// <para>
/// C export: <c>typedef void(WINAPI* SetMarkerOnCommandList)(ID3D12GraphicsCommandList* commandList, UINT64 color, _In_ PCSTR formatString)</c>.
/// </para>
/// </summary>
/// <param name="commandList">The target <see cref="ID3D12GraphicsCommandList"/> object.</param>
/// <param name="color">The color to use for the marker.</param>
/// <param name="formatString">The format string to use for the marker (in ANSI format, <see langword="null"/>-terminated).</param>
[DllImport("WinPixEventRuntime", ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern void PIXSetMarkerOnCommandList(ID3D12GraphicsCommandList* commandList, ulong color, sbyte* formatString);
}
+43
ファイルの表示
@@ -0,0 +1,43 @@
/*==========================================================================;
*
* Copyright (C) Microsoft Corporation. All Rights Reserved.
*
* File: pix3.h
* Content: PIX include file
*
****************************************************************************/
// The following methods in this file have been ported from the
// pix3.h file in the winpixeventruntime.1.0.220124001 package.
using System.Runtime.CompilerServices;
namespace ComputeSharp.Interop;
/// <inheritdoc/>
partial class Pix
{
/// <summary>
/// Gets a <see cref="uint"/> value representing a color for a PIX event.
/// </summary>
/// <param name="r">The red channel value for the color.</param>
/// <param name="g">The green channel value for the color.</param>
/// <param name="b">The blue channel value for the color.</param>
/// <returns>A <see cref="uint"/> value representing a color for a PIX event.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint PIX_COLOR(byte r, byte g, byte b)
{
return 0xFF000000 | ((uint)r << 16) | ((uint)g << 8) | b;
}
/// <summary>
/// Gets a <see cref="uint"/> value representing an indexed color for a PIX event.
/// </summary>
/// <param name="i">The index of the event to get the color for.</param>
/// <returns>A <see cref="uint"/> value representing an indexed color for a PIX event.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint PIX_COLOR_INDEX(byte i)
{
return i;
}
}
+106
ファイルの表示
@@ -0,0 +1,106 @@
MIT License
Copyright (c) 2022 Sergio Pedri
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This project incorporates components from PIX on Windows (https://devblogs.microsoft.com/pix/winpixeventruntime/).
%% PIX on Windows NOTICES AND INFORMATION BEGIN HERE
=========================================
MICROSOFT SOFTWARE LICENSE TERMS
PIX EVENT RUNTIME FOR WINDOWS
IF YOU LIVE IN (OR ARE A BUSINESS WITH A PRINCIPAL PLACE OF BUSINESS IN) THE UNITED STATES, PLEASE READ THE “BINDING ARBITRATION AND CLASS ACTION WAIVER” SECTION BELOW. IT AFFECTS HOW DISPUTES ARE RESOLVED.
These license terms are an agreement between you and Microsoft Corporation (or one of its affiliates). They apply to the software named above and any Microsoft services or software updates (except to the extent such services or updates are accompanied by new or additional terms, in which case those different terms apply prospectively and do not alter your or Microsoft’s rights relating to pre-updated software or services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS.
1. INSTALLATION AND USE RIGHTS.
a. General. You may install and use any number of copies of the software to design, develop and test your Microsoft Windows programs.
b. Third Party Software. The software may include third party applications that are licensed to you under this agreement or under their own terms. License terms, notices, and acknowledgements, if any, for the third party applications may be accessible online at http://aka.ms/thirdpartynotices or in an accompanying notices file. Even if such applications are governed by other agreements, the disclaimer, limitations on, and exclusions of damages below also apply to the extent allowed by applicable law.
2. DISTRIBUTABLE CODE.
a. Distributable Code. The software is comprised of Distributable Code. “Distributable Code” is code that you are permitted to distribute in programs you develop if you comply with the terms below.
(i) Right to Use and Distribute.
* You may copy and distribute the object code form of the software.
* Third Party Distribution. You may permit distributors of your programs to copy and distribute the Distributable Code as part of those programs.
(ii) Distribution Requirements. For any Distributable Code you distribute, you must
* add significant primary functionality to it in your programs;
* require distributors and external end users to agree to terms that protect it at least as much as this agreement;
* display your valid copyright notice on your programs; and
* indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your programs.
(iii) Distribution Restrictions. You may not
* alter any copyright, trademark or patent notice in the Distributable Code;
* use Microsoft’s trademarks in your programs’ names or in a way that suggests your programs come from or are endorsed by Microsoft;
* distribute Distributable Code to run on a platform other than a Windows platform;
* include Distributable Code in malicious, deceptive or unlawful programs; or
* modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An Excluded License is one that requires, as a condition of use, modification or distribution, that
* the code be disclosed or distributed in source code form; or
* others have the right to modify it.
3. SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to):
a. work around any technical limitations in the software that only allow you to use it in certain ways;
b. reverse engineer, decompile or disassemble the software;
c. remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software;
d. use the software in any way that is against the law or to create or propagate malware; or
e. share, publish, distribute, or lend the software, provide the software as a stand-alone hosted solution for others to use, or transfer the software or this agreement to any third party.
4. EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit http://aka.ms/exporting.
5. SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
6. BINDING ARBITRATION AND CLASS ACTION WAIVER. This Section applies if you live in (or, if a business, your principal place of business is in) the United States. If you and Microsoft have a dispute, you and Microsoft agree to try for 60 days to resolve it informally. If you and Microsoft can’t, you and Microsoft agree to binding individual arbitration before the American Arbitration Association under the Federal Arbitration Act (“FAA”), and not to sue in court in front of a judge or jury. Instead, a neutral arbitrator will decide. Class action lawsuits, class-wide arbitrations, private attorney-general actions, and any other proceeding where someone acts in a representative capacity are not allowed; nor is combining individual proceedings without the consent of all parties. The complete Arbitration Agreement contains more terms and is at http://aka.ms/arb-agreement-1. You and Microsoft agree to these terms.
7. ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software.
8. APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles, except that the FAA governs everything related to arbitration. If you acquired the software in any other country, its laws apply, except that the FAA governs everything related to arbitration. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court (excluding arbitration). If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court (excluding arbitration).
9. CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state, province, or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state, province, or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you:
a. Australia. You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights.
b. Canada. If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from the Internet (if and when you re-connect to the Internet, however, the software will resume checking for and installing updates), or uninstalling the software. The product documentation, if any, may also specify how to turn off updates for your specific device or software.
c. Germany and Austria.
(i) Warranty. The properly licensed software will perform substantially as described in any Microsoft materials that accompany the software. However, Microsoft gives no contractual guarantee in relation to the licensed software.
(ii) Limitation of Liability. In case of intentional conduct, gross negligence, claims based on the Product Liability Act, as well as, in case of death or personal or physical injury, Microsoft is liable according to the statutory law.
Subject to the foregoing clause (ii), Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence.
10. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
11. LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to (a) anything related to the software, services, content (including code) on third party Internet sites, or third party applications; and (b) claims for breach of contract, warranty, guarantee, or condition; strict liability, negligence, or other tort; or any other claim; in each case to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state, province, or country may not allow the exclusion or limitation of incidental, consequential, or other damages.
[Please note: As this software is distributed in Canada, some of the clauses in this agreement are provided below in French.
Remarque: Ce logiciel étant distribué au Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne:
* tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers; et
* les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.]
=========================================
END OF PIX on Windows NOTICES AND INFORMATION
バイナリファイルは表示されません。
バイナリファイルは表示されません。
バイナリファイルは表示されません。
バイナリファイルは表示されません。
+1 -1
ファイルの表示
@@ -7,7 +7,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters;
/// <inheritdoc cref="HlslSourceRewriter"/>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
+3 -3
ファイルの表示
@@ -483,13 +483,13 @@ internal sealed unsafe partial class SwapChainManager<TOwner> : NativeObject
/// <inheritdoc/>
private unsafe partial void OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager)
{
using ComPtr<IDXGIFactory4> dxgiFactory4 = default;
using ComPtr<IDXGIFactory6> dxgiFactory6 = default;
DeviceHelper.CreateDXGIFactory4(dxgiFactory4.GetAddressOf());
DeviceHelper.CreateDXGIFactory6(dxgiFactory6.GetAddressOf());
using ComPtr<IDXGIAdapter> dxgiAdapter = default;
dxgiFactory4.Get()->EnumAdapters(0, dxgiAdapter.GetAddressOf()).Assert();
dxgiFactory6.Get()->EnumAdapters(0, dxgiAdapter.GetAddressOf()).Assert();
int targetFramerate = dxgiAdapter.Get()->GetCompositionRefreshRate(DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM);
+5 -5
ファイルの表示
@@ -18,27 +18,27 @@
the same version) but Microsoft.Build.Tasks.CodeAnalysis.dll is where MSBuild loads the compiler tasks from so if
someone is getting creative with msbuild tasks/targets this is the "most correct" assembly to check. -->
<GetAssemblyIdentity AssemblyFiles="$([System.IO.Path]::Combine(`$([System.IO.Path]::GetDirectoryName($(CSharpCoreTargetsPath)))`,`Microsoft.Build.Tasks.CodeAnalysis.dll`))">
<Output TaskParameter="Assemblies" ItemName="CurrentCompilerAssemblyIdentity"/>
<Output TaskParameter="Assemblies" ItemName="ComputeSharpCurrentCompilerAssemblyIdentity"/>
</GetAssemblyIdentity>
<PropertyGroup>
<!-- Transform the resulting item from GetAssemblyIdentity into a property representing its assembly version -->
<CurrentCompilerVersion>@(CurrentCompilerAssemblyIdentity->'%(Version)')</CurrentCompilerVersion>
<ComputeSharpCurrentCompilerVersion>@(ComputeSharpCurrentCompilerAssemblyIdentity->'%(Version)')</ComputeSharpCurrentCompilerVersion>
<!-- The CurrentCompilerVersionIsNotNewEnough property can now be defined based on the Roslyn assembly version -->
<CurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(CurrentCompilerVersion), 4.2))">true</CurrentCompilerVersionIsNotNewEnough>
<ComputeSharpCurrentCompilerVersionIsNotNewEnough Condition="$([MSBuild]::VersionLessThan($(ComputeSharpCurrentCompilerVersion), 4.2))">true</ComputeSharpCurrentCompilerVersionIsNotNewEnough>
</PropertyGroup>
<!-- If the Roslyn version is < 4.2, disable the source generators -->
<ItemGroup Condition ="'$(CurrentCompilerVersionIsNotNewEnough)' == 'true'">
<ItemGroup Condition ="'$(ComputeSharpCurrentCompilerVersionIsNotNewEnough)' == 'true'">
<Analyzer Remove="@(_ComputeSharpAnalyzer)"/>
</ItemGroup>
<!-- If the source generators are disabled, also emit an error. This would've been produced by MSBuild itself as well, but
emitting this manually lets us customize the message to inform developers as to why exactly the generators have been
disabled, and that ComputeSharp will not work at all unless a more up to date IDE or compiler version are used. -->
<Error Condition ="'$(CurrentCompilerVersionIsNotNewEnough)' == 'true'" Text="The ComputeSharp source generators have been disabled on the current configuration, as they need Roslyn 4.2 in order to work. ComputeSharp requires the source generators to run in order to process shaders, so the library cannot be used without a more up to date IDE (eg. VS2022) or .NET SDK version."/>
<Error Condition ="'$(ComputeSharpCurrentCompilerVersionIsNotNewEnough)' == 'true'" Text="The ComputeSharp source generators have been disabled on the current configuration, as they need Roslyn 4.2 in order to work. ComputeSharp requires the source generators to run in order to process shaders, so the library cannot be used without a more up to date IDE (eg. VS2022) or .NET SDK version."/>
</Target>
<!-- Remove the analyzer if Roslyn is missing -->
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
namespace ComputeSharp;
/// <inheritdoc cref="ThreadIds"/>
public static partial class ThreadIds
partial class ThreadIds
{
/// <summary>
/// A <see langword="class"/> that indicates the normalized ids of a given GPU thread running a compute shader.
+1 -1
ファイルの表示
@@ -7,7 +7,7 @@ using ComputeSharp.Resources;
namespace ComputeSharp;
/// <inheritdoc cref="GraphicsDeviceExtensions"/>
public static partial class GraphicsDeviceExtensions
partial class GraphicsDeviceExtensions
{
/// <summary>
/// Allocates a new constant buffer with the specified parameters.
+2 -3
ファイルの表示
@@ -17,6 +17,7 @@ internal static unsafe class ID3D12ResourceExtensions
/// </summary>
/// <param name="d3D12Resource">The target <see cref="ID3D12Resource"/> to map.</param>
/// <returns>A <see cref="ID3D12ResourceMap"/> instance representing the mapped resource.</returns>
/// <exception cref="Exception">Thrown when the mapping operation fails.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ID3D12ResourceMap Map(this ref ID3D12Resource d3D12Resource)
{
@@ -32,7 +33,6 @@ internal static unsafe class ID3D12ResourceExtensions
/// </summary>
/// <param name="d3D12Resource">The target <see cref="ID3D12Resource"/> to map.</param>
/// <returns>A pointer to the mapped area for <paramref name="d3D12Resource"/>.</returns>
/// <exception cref="Exception">Thrown when the mapping operation fails.</exception>
/// <remarks>Only use this method to unmap resources that were mapped with <see cref="Map(ref ID3D12Resource)"/>.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Unmap(this ref ID3D12Resource d3D12Resource)
@@ -43,9 +43,8 @@ internal static unsafe class ID3D12ResourceExtensions
/// <summary>
/// Assigns a name to a given <see cref="ID3D12Resource"/>.
/// </summary>
/// <param name="d3D12Resource">The target <see cref="ID3D12Resource"/> to map.</param>
/// <param name="d3D12Resource">The target <see cref="ID3D12Resource"/> to set the name for.</param>
/// <param name="wrapper">The wrapper object to get the name from.</param>
/// <exception cref="Exception">Thrown when the mapping operation fails.</exception>
[Conditional("DEBUG")]
public static void SetName(this ref ID3D12Resource d3D12Resource, object wrapper)
{
+1 -1
ファイルの表示
@@ -21,7 +21,7 @@ using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.In
namespace ComputeSharp.Graphics.Extensions;
/// <inheritdoc/>
internal static unsafe partial class IWICStreamExtensions
unsafe partial class IWICStreamExtensions
{
/// <summary>
/// Initializes an input <see cref="IWICStream"/> wrapping a given <see cref="IBufferWriter{T}"/> instance.
+1 -1
ファイルの表示
@@ -15,7 +15,7 @@ using static TerraFX.Interop.DirectX.DXGI_GPU_PREFERENCE;
namespace ComputeSharp.Graphics.Helpers;
/// <inheritdoc/>
internal static partial class DeviceHelper
partial class DeviceHelper
{
/// <summary>
/// A custom query type that iterates through devices matching a given predicate.
+1 -1
ファイルの表示
@@ -6,7 +6,7 @@ using TerraFX.Interop.Windows;
namespace ComputeSharp.Graphics.Helpers;
/// <inheritdoc/>
internal static partial class DeviceHelper
partial class DeviceHelper
{
/// <summary>
/// The local cache of <see cref="GraphicsDevice"/> instances that are currently usable.
+109 -26
ファイルの表示
@@ -2,8 +2,10 @@
using System.Runtime.InteropServices;
using System.Text;
using CommunityToolkit.Diagnostics;
using ComputeSharp.Core.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static TerraFX.Interop.DirectX.D3D12_MESSAGE_ID;
using static TerraFX.Interop.DirectX.D3D12_MESSAGE_SEVERITY;
#if NET6_0_OR_GREATER
using Enum = System.Enum;
@@ -14,8 +16,13 @@ using Enum = ComputeSharp.NetStandard.System.Enum;
namespace ComputeSharp.Graphics.Helpers;
/// <inheritdoc/>
internal static partial class DeviceHelper
partial class DeviceHelper
{
/// <summary>
/// A shared <see cref="StringBuilder"/> used from <see cref="FlushAllID3D12InfoQueueMessagesAndCheckForErrorsOrWarnings"/> to create messages.
/// </summary>
private static StringBuilder? infoQueueMessageBuilder;
/// <summary>
/// Flushes all the pending debug messages for all existing <see cref="ID3D12Device"/> instances to the console/debugger.
/// It also checks whether or not there are any error messages being logged that didn't result in an actual crash yet.
@@ -27,7 +34,7 @@ internal static partial class DeviceHelper
lock (DevicesCache)
{
StringBuilder builder = new(1024);
StringBuilder builder = infoQueueMessageBuilder ??= new(1024);
foreach (var pair in D3D12InfoQueueMap)
{
@@ -53,7 +60,106 @@ internal static partial class DeviceHelper
builder.AppendLine($"[Category]: {Enum.GetName(message->Category)}");
builder.AppendLine($"[Severity]: {Enum.GetName(message->Severity)}");
builder.AppendLine($"[ID]: {Enum.GetName(message->ID)}");
builder.Append($"[Description]: \"{new string(message->pDescription)}\"");
bool isDeviceRemovedMessage = message->ID is D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT or D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT or D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT;
// Special handling for device removal messages
if (isDeviceRemovedMessage)
{
HRESULT result = device.D3D12Device->GetDeviceRemovedReason();
// If the device removal reason is available, also include that in the output message
if (result != S.S_OK)
{
string deviceRemovalReason = (int)result switch
{
DXGI.DXGI_ERROR_DEVICE_HUNG => nameof(DXGI.DXGI_ERROR_DEVICE_HUNG),
DXGI.DXGI_ERROR_DEVICE_REMOVED => nameof(DXGI.DXGI_ERROR_DEVICE_REMOVED),
DXGI.DXGI_ERROR_DEVICE_RESET => nameof(DXGI.DXGI_ERROR_DEVICE_RESET),
DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => nameof(DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR),
DXGI.DXGI_ERROR_INVALID_CALL => nameof(DXGI.DXGI_ERROR_INVALID_CALL),
_ => ThrowHelper.ThrowArgumentOutOfRangeException<string>("Invalid GetDeviceRemovedReason HRESULT.")
};
builder.AppendLine($"[Reason]: {deviceRemovalReason}");
}
}
// If DRED is enabled, also output the available auto breadcrumbs
if (isDeviceRemovedMessage && Configuration.IsDeviceRemovedExtendedDataEnabled)
{
builder.AppendLine($"[Description]: \"{new string(message->pDescription)}\"");
using ComPtr<ID3D12DeviceRemovedExtendedData1> d3D12DeviceRemovedExtendedData = default;
// Get the DRED data
int hresult = device.D3D12Device->QueryInterface(
riid: Windows.__uuidof<ID3D12DeviceRemovedExtendedData1>(),
ppvObject: d3D12DeviceRemovedExtendedData.GetVoidAddressOf());
if (hresult != S.S_OK)
{
ThrowHelper.ThrowWin32Exception(hresult);
}
D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1 d3D12DredAutoBreadcrumbsOutput;
// Get the auto breadcrumbs for the current event
hresult = d3D12DeviceRemovedExtendedData.Get()->GetAutoBreadcrumbsOutput1(&d3D12DredAutoBreadcrumbsOutput);
if (hresult != S.S_OK)
{
ThrowHelper.ThrowWin32Exception(hresult);
}
builder.AppendLine("[DRED breadcrumbs START] ===============================");
int breadcrumbNodeIndex = 0;
// Traverse all the auto breadcrumb nodes and print their contents
for (D3D12_AUTO_BREADCRUMB_NODE1* d3D12AutoBreadcrumbNode = d3D12DredAutoBreadcrumbsOutput.pHeadAutoBreadcrumbNode;
d3D12AutoBreadcrumbNode is not null;
d3D12AutoBreadcrumbNode = d3D12AutoBreadcrumbNode->pNext, breadcrumbNodeIndex++)
{
uint numberOfExecutedOps = *d3D12AutoBreadcrumbNode->pLastBreadcrumbValue;
// For each auto breadcrumb node, not all recorded breadcrumb have actually been executed. To reduce the verbosity of the
// output and only show the most relevant info, indicate how many breadcrumbs were recorded and how many were actually
// executed, but then only display the executed ones in the code below. This makes it easier to debug hangs for users.
builder.AppendLine($"[NODE #{breadcrumbNodeIndex}]: {d3D12AutoBreadcrumbNode->BreadcrumbCount} total breadcrumb(s), {numberOfExecutedOps} executed breadcrumb(s)");
uint contextIndex = 0;
for (uint commandIndex = 0; commandIndex < numberOfExecutedOps; commandIndex++)
{
// An D3D12_AUTO_BREADCRUMB_NODE1 object has two pointers:
// - pCommandHistory, pointing to the full list of available breadcrumbs.
// - pBreadcrumbContexts, pointing to the list of available contexts.
// Each context also has a field to indicate the index of the breadcrumb it belongs to. Since these indices are
// sorted in ascending order, the following code loops through the executed breadcrumbs and then only checks if
// the current index for the context list is within bounds, and if so, if the current context has a matching index.
// If that is the case, the context message is extracted and the index is incremented, otherwise just the opcode
// is added to the debug output. Essentially, this is somewhat similar to a merge algorithm for two ordered lists.
if (contextIndex < d3D12AutoBreadcrumbNode->BreadcrumbContextsCount &&
d3D12AutoBreadcrumbNode->pBreadcrumbContexts[contextIndex].BreadcrumbIndex == commandIndex)
{
string context = new((char*)d3D12AutoBreadcrumbNode->pBreadcrumbContexts[contextIndex++].pContextString);
builder.AppendLine($">> [OP #{commandIndex}]: {d3D12AutoBreadcrumbNode->pCommandHistory[commandIndex]}, \"{context}\"");
}
else
{
builder.AppendLine($">> [OP #{commandIndex}]: {d3D12AutoBreadcrumbNode->pCommandHistory[commandIndex]}");
}
}
}
builder.AppendLine("================================= [DRED breadcrumbs END]");
}
else
{
builder.Append($"[Description]: \"{new string(message->pDescription)}\"");
}
}
finally
{
@@ -69,29 +175,6 @@ internal static partial class DeviceHelper
}
queue->ClearStoredMessages();
HRESULT result = device.D3D12Device->GetDeviceRemovedReason();
if (result != S.S_OK)
{
string message = (int)result switch
{
DXGI.DXGI_ERROR_DEVICE_HUNG => nameof(DXGI.DXGI_ERROR_DEVICE_HUNG),
DXGI.DXGI_ERROR_DEVICE_REMOVED => nameof(DXGI.DXGI_ERROR_DEVICE_REMOVED),
DXGI.DXGI_ERROR_DEVICE_RESET => nameof(DXGI.DXGI_ERROR_DEVICE_RESET),
DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => nameof(DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR),
DXGI.DXGI_ERROR_INVALID_CALL => nameof(DXGI.DXGI_ERROR_INVALID_CALL),
_ => ThrowHelper.ThrowArgumentOutOfRangeException<string>("Invalid GetDeviceRemovedReason HRESULT.")
};
builder.Clear();
builder.AppendLine($"[D3D12 device \"{device}\" removed (HW: {device.IsHardwareAccelerated}, UMA: {device.IsCacheCoherentUMA})]");
builder.AppendLine($"[Reason]: {message}");
hasErrorsOrWarnings = true;
Trace.WriteLine(builder);
}
}
}
+43 -17
ファイルの表示
@@ -15,7 +15,7 @@ using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.In
namespace ComputeSharp.Graphics.Helpers;
/// <inheritdoc cref="DeviceHelper"/>
internal static partial class DeviceHelper
partial class DeviceHelper
{
/// <summary>
/// The creation flags for <see cref="IDXGIFactory"/> instances.
@@ -27,33 +27,24 @@ internal static partial class DeviceHelper
Configuration.IsDebugOutputEnabled ? (uint)DXGI.DXGI_CREATE_FACTORY_DEBUG : 0;
#endif
/// <summary>
/// Creates a new <see cref="IDXGIFactory4"/> instance to be used to enumerate devices.
/// </summary>
/// <param name="dxgiFactory4">The resulting <see cref="IDXGIFactory4"/> instance.</param>
internal static unsafe void CreateDXGIFactory4(IDXGIFactory4** dxgiFactory4)
{
if (Configuration.IsDebugOutputEnabled)
{
EnableDebugMode();
}
DirectX.CreateDXGIFactory2(IDXGIFactoryCreationFlags, Windows.__uuidof<IDXGIFactory4>(), (void**)dxgiFactory4).Assert();
}
/// <summary>
/// Creates a new <see cref="IDXGIFactory6"/> instance to be used to enumerate devices.
/// </summary>
/// <param name="dxgiFactory6">The resulting <see cref="IDXGIFactory6"/> instance.</param>
internal static unsafe void CreateDXGIFactory6(IDXGIFactory6** dxgiFactory6)
{
using ComPtr<IDXGIFactory4> dxgiFactory4 = default;
if (Configuration.IsDebugOutputEnabled)
{
EnableDebugMode();
}
if (Configuration.IsDeviceRemovedExtendedDataEnabled)
{
EnableDeviceRemovedExtendedDataConfiguration();
}
using ComPtr<IDXGIFactory4> dxgiFactory4 = default;
DirectX.CreateDXGIFactory2(IDXGIFactoryCreationFlags, Windows.__uuidof<IDXGIFactory4>(), dxgiFactory4.GetVoidAddressOf()).Assert();
HRESULT result = dxgiFactory4.CopyTo(dxgiFactory6);
@@ -94,6 +85,23 @@ internal static partial class DeviceHelper
}
}
/// <summary>
/// Enables the DRED settings are enabled (see <see href="https://devblogs.microsoft.com/directx/dred/"/>).
/// </summary>
private static unsafe void EnableDeviceRemovedExtendedDataConfiguration()
{
using ComPtr<ID3D12DeviceRemovedExtendedDataSettings1> d3D12DeviceRemovedExtendedDataSettings = default;
DirectX.D3D12GetDebugInterface(
riid: Windows.__uuidof<ID3D12DeviceRemovedExtendedDataSettings1>(),
ppvDebug: d3D12DeviceRemovedExtendedDataSettings.GetVoidAddressOf()).Assert();
// Enable the auto-breadcrumbs and page faults reporting
d3D12DeviceRemovedExtendedDataSettings.Get()->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT.D3D12_DRED_ENABLEMENT_FORCED_ON);
d3D12DeviceRemovedExtendedDataSettings.Get()->SetBreadcrumbContextEnablement(D3D12_DRED_ENABLEMENT.D3D12_DRED_ENABLEMENT_FORCED_ON);
d3D12DeviceRemovedExtendedDataSettings.Get()->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT.D3D12_DRED_ENABLEMENT_FORCED_ON);
}
/// <summary>
/// A custom <see cref="IDXGIFactory6"/> fallback implementation to use on systems with no support for it.
/// </summary>
@@ -104,6 +112,10 @@ internal static partial class DeviceHelper
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(IDXGIFactory4As6Backcompat* @this);
/// <inheritdoc cref="EnumAdapters"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EnumAdaptersDelegate(IDXGIFactory4As6Backcompat* @this, uint Adapter, IDXGIAdapter** ppAdapter);
/// <inheritdoc cref="EnumWarpAdapter"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EnumWarpAdapterDelegate(IDXGIFactory4As6Backcompat* @this, Guid* riid, void** ppvAdapter);
@@ -117,6 +129,11 @@ internal static partial class DeviceHelper
/// </summary>
private static readonly ReleaseDelegate ReleaseWrapper = Release;
/// <summary>
/// A cached <see cref="EnumAdaptersDelegate"/> instance wrapping <see cref="EnumAdapters"/>.
/// </summary>
private static readonly EnumAdaptersDelegate EnumAdaptersWrapper = EnumAdapters;
/// <summary>
/// A cached <see cref="EnumWarpAdapterDelegate"/> instance wrapping <see cref="EnumWarpAdapter"/>.
/// </summary>
@@ -145,10 +162,12 @@ internal static partial class DeviceHelper
#if NET6_0_OR_GREATER
lpVtbl[2] = (delegate* unmanaged<IDXGIFactory4As6Backcompat*, uint>)&Release;
lpVtbl[7] = (delegate* unmanaged<IDXGIFactory4As6Backcompat*, uint, IDXGIAdapter**, int>)&EnumAdapters;
lpVtbl[27] = (delegate* unmanaged<IDXGIFactory4As6Backcompat*, Guid*, void**, int>)&EnumWarpAdapter;
lpVtbl[29] = (delegate* unmanaged<IDXGIFactory4As6Backcompat*, uint, DXGI_GPU_PREFERENCE, Guid*, void**, int>)&EnumAdapterByGpuPreference;
#else
lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ReleaseWrapper);
lpVtbl[7] = (void*)Marshal.GetFunctionPointerForDelegate(EnumAdaptersWrapper);
lpVtbl[27] = (void*)Marshal.GetFunctionPointerForDelegate(EnumWarpAdapterWrapper);
lpVtbl[29] = (void*)Marshal.GetFunctionPointerForDelegate(EnumAdapterByGpuPreferenceWrapper);
#endif
@@ -194,6 +213,13 @@ internal static partial class DeviceHelper
return 0;
}
/// <inheritdoc cref="IDXGIFactory6.EnumAdapters(uint, IDXGIAdapter**)"/>
[UnmanagedCallersOnly]
public static int EnumAdapters(IDXGIFactory4As6Backcompat* @this, uint Adapter, IDXGIAdapter** ppAdapter)
{
return @this->dxgiFactory4->EnumAdapters(Adapter, ppAdapter);
}
/// <inheritdoc cref="IDXGIFactory6.EnumWarpAdapter(Guid*, void**)"/>
[UnmanagedCallersOnly]
public static int EnumWarpAdapter(IDXGIFactory4As6Backcompat* @this, Guid* riid, void** ppvAdapter)
+1
ファイルの表示
@@ -3,6 +3,7 @@
[module: SkipLocalsInit]
[assembly: InternalsVisibleTo("ComputeSharp.Dynamic")]
[assembly: InternalsVisibleTo("ComputeSharp.Pix")]
[assembly: InternalsVisibleTo("ComputeSharp.Uwp")]
[assembly: InternalsVisibleTo("ComputeSharp.WinUI")]
+10
ファイルの表示
@@ -13,11 +13,21 @@ internal static class Configuration
/// </summary>
private const string EnableDebugOutput = "COMPUTESHARP_ENABLE_DEBUG_OUTPUT";
/// <summary>
/// The configuration property name for <see cref="IsDeviceRemovedExtendedDataEnabled"/>.
/// </summary>
private const string EnableDeviceRemovedExtendedDataInfo = "COMPUTESHARP_ENABLE_DEVICE_REMOVED_EXTENDED_DATA";
/// <summary>
/// Indicates whether or not the debug output is enabled.
/// </summary>
public static readonly bool IsDebugOutputEnabled = GetConfigurationValue(EnableDebugOutput);
/// <summary>
/// Indicates whether or not the debug output is enabled.
/// </summary>
public static readonly bool IsDeviceRemovedExtendedDataEnabled = GetConfigurationValue(EnableDeviceRemovedExtendedDataInfo);
/// <summary>
/// Gets a configuration value for a specified property.
/// </summary>
+4 -4
ファイルの表示
@@ -81,7 +81,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
{
ThrowInvalidOperationExceptionIfDeviceIsNull();
ref CommandList commandList = ref GetCommandList(in this, null);
ref CommandList commandList = ref GetCommandList(in this, pipelineState: null);
commandList.D3D12GraphicsCommandList->ClearUnorderedAccessView(d3D12Resource, d3D12GpuDescriptorHandle, d3D12CpuDescriptorHandle, isNormalized);
}
@@ -101,7 +101,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
{
ThrowInvalidOperationExceptionIfDeviceIsNull();
ref CommandList commandList = ref GetCommandList(in this, null);
ref CommandList commandList = ref GetCommandList(in this, pipelineState: null);
commandList.D3D12GraphicsCommandList->FillUnorderedAccessView(d3D12Resource, d3D12GpuDescriptorHandle, d3D12CpuDescriptorHandle, value);
}
@@ -275,7 +275,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
{
ThrowInvalidOperationExceptionIfDeviceIsNull();
ref CommandList commandList = ref GetCommandList(in this, null);
ref CommandList commandList = ref GetCommandList(in this, pipelineState: null);
commandList.D3D12GraphicsCommandList->TransitionBarrier(d3D12Resource, d3D12ResourceStatesBefore, d3D12ResourceStatesAfter);
}
@@ -345,7 +345,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// <param name="pipelineState">The input <see cref="ID3D12PipelineState"/> to load.</param>
/// <returns>A reference to the <see cref="CommandList"/> instance to use.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe ref CommandList GetCommandList(in ComputeContext @this, ID3D12PipelineState* pipelineState)
internal static unsafe ref CommandList GetCommandList(in ComputeContext @this, ID3D12PipelineState* pipelineState)
{
ref ComputeContext context = ref Unsafe.AsRef(in @this);
+7
ファイルの表示
@@ -42,6 +42,13 @@ namespace TerraFX.Interop.DirectX
return ((delegate* unmanaged[Stdcall]<IDXGIFactory6*, uint>)(lpVtbl[2]))((IDXGIFactory6*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
public HRESULT EnumAdapters(uint Adapter, IDXGIAdapter** ppAdapter)
{
return ((delegate* unmanaged[Stdcall]<IDXGIFactory6*, uint, IDXGIAdapter**, int>)(lpVtbl[7]))((IDXGIFactory6*)Unsafe.AsPointer(ref this), Adapter, ppAdapter);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(24)]
public HRESULT CreateSwapChainForComposition(IUnknown* pDevice, [NativeTypeName("const DXGI_SWAP_CHAIN_DESC1 *")] DXGI_SWAP_CHAIN_DESC1* pDesc, IDXGIOutput* pRestrictToOutput, IDXGISwapChain1** ppSwapChain)
+36
ファイルの表示
@@ -0,0 +1,36 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
namespace TerraFX.Interop.DirectX
{
internal unsafe partial struct D3D12_AUTO_BREADCRUMB_NODE1
{
[NativeTypeName("const char *")]
public sbyte* pCommandListDebugNameA;
[NativeTypeName("const wchar_t *")]
public ushort* pCommandListDebugNameW;
[NativeTypeName("const char *")]
public sbyte* pCommandQueueDebugNameA;
[NativeTypeName("const wchar_t *")]
public ushort* pCommandQueueDebugNameW;
public ID3D12GraphicsCommandList* pCommandList;
public ID3D12CommandQueue* pCommandQueue;
public uint BreadcrumbCount;
[NativeTypeName("const UINT *")]
public uint* pLastBreadcrumbValue;
[NativeTypeName("const D3D12_AUTO_BREADCRUMB_OP *")]
public D3D12_AUTO_BREADCRUMB_OP* pCommandHistory;
[NativeTypeName("const struct D3D12_AUTO_BREADCRUMB_NODE1 *")]
public D3D12_AUTO_BREADCRUMB_NODE1* pNext;
public uint BreadcrumbContextsCount;
public D3D12_DRED_BREADCRUMB_CONTEXT* pBreadcrumbContexts;
}
}
+56
ファイルの表示
@@ -0,0 +1,56 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
namespace TerraFX.Interop.DirectX
{
internal enum D3D12_AUTO_BREADCRUMB_OP
{
D3D12_AUTO_BREADCRUMB_OP_SETMARKER = 0,
D3D12_AUTO_BREADCRUMB_OP_BEGINEVENT = 1,
D3D12_AUTO_BREADCRUMB_OP_ENDEVENT = 2,
D3D12_AUTO_BREADCRUMB_OP_DRAWINSTANCED = 3,
D3D12_AUTO_BREADCRUMB_OP_DRAWINDEXEDINSTANCED = 4,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT = 5,
D3D12_AUTO_BREADCRUMB_OP_DISPATCH = 6,
D3D12_AUTO_BREADCRUMB_OP_COPYBUFFERREGION = 7,
D3D12_AUTO_BREADCRUMB_OP_COPYTEXTUREREGION = 8,
D3D12_AUTO_BREADCRUMB_OP_COPYRESOURCE = 9,
D3D12_AUTO_BREADCRUMB_OP_COPYTILES = 10,
D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCE = 11,
D3D12_AUTO_BREADCRUMB_OP_CLEARRENDERTARGETVIEW = 12,
D3D12_AUTO_BREADCRUMB_OP_CLEARUNORDEREDACCESSVIEW = 13,
D3D12_AUTO_BREADCRUMB_OP_CLEARDEPTHSTENCILVIEW = 14,
D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER = 15,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEBUNDLE = 16,
D3D12_AUTO_BREADCRUMB_OP_PRESENT = 17,
D3D12_AUTO_BREADCRUMB_OP_RESOLVEQUERYDATA = 18,
D3D12_AUTO_BREADCRUMB_OP_BEGINSUBMISSION = 19,
D3D12_AUTO_BREADCRUMB_OP_ENDSUBMISSION = 20,
D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME = 21,
D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES = 22,
D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT = 23,
D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT64 = 24,
D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCEREGION = 25,
D3D12_AUTO_BREADCRUMB_OP_WRITEBUFFERIMMEDIATE = 26,
D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME1 = 27,
D3D12_AUTO_BREADCRUMB_OP_SETPROTECTEDRESOURCESESSION = 28,
D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME2 = 29,
D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES1 = 30,
D3D12_AUTO_BREADCRUMB_OP_BUILDRAYTRACINGACCELERATIONSTRUCTURE = 31,
D3D12_AUTO_BREADCRUMB_OP_EMITRAYTRACINGACCELERATIONSTRUCTUREPOSTBUILDINFO = 32,
D3D12_AUTO_BREADCRUMB_OP_COPYRAYTRACINGACCELERATIONSTRUCTURE = 33,
D3D12_AUTO_BREADCRUMB_OP_DISPATCHRAYS = 34,
D3D12_AUTO_BREADCRUMB_OP_INITIALIZEMETACOMMAND = 35,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEMETACOMMAND = 36,
D3D12_AUTO_BREADCRUMB_OP_ESTIMATEMOTION = 37,
D3D12_AUTO_BREADCRUMB_OP_RESOLVEMOTIONVECTORHEAP = 38,
D3D12_AUTO_BREADCRUMB_OP_SETPIPELINESTATE1 = 39,
D3D12_AUTO_BREADCRUMB_OP_INITIALIZEEXTENSIONCOMMAND = 40,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEEXTENSIONCOMMAND = 41,
D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH = 42,
D3D12_AUTO_BREADCRUMB_OP_ENCODEFRAME = 43,
D3D12_AUTO_BREADCRUMB_OP_RESOLVEENCODEROUTPUTMETADATA = 44,
}
}
+13
ファイルの表示
@@ -0,0 +1,13 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
namespace TerraFX.Interop.DirectX
{
internal unsafe partial struct D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1
{
[NativeTypeName("const D3D12_AUTO_BREADCRUMB_NODE1 *")]
public D3D12_AUTO_BREADCRUMB_NODE1* pHeadAutoBreadcrumbNode;
}
}
+15
ファイルの表示
@@ -0,0 +1,15 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
namespace TerraFX.Interop.DirectX
{
internal unsafe partial struct D3D12_DRED_BREADCRUMB_CONTEXT
{
public uint BreadcrumbIndex;
[NativeTypeName("const wchar_t *")]
public ushort* pContextString;
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
namespace TerraFX.Interop.DirectX
{
internal enum D3D12_DRED_ENABLEMENT
{
D3D12_DRED_ENABLEMENT_SYSTEM_CONTROLLED = 0,
D3D12_DRED_ENABLEMENT_FORCED_OFF = 1,
D3D12_DRED_ENABLEMENT_FORCED_ON = 2,
}
}
+50
ファイルの表示
@@ -0,0 +1,50 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
namespace TerraFX.Interop.DirectX
{
[Guid("9727A022-CF1D-4DDA-9EBA-EFFA653FC506")]
[NativeTypeName("struct ID3D12DeviceRemovedExtendedData1 : ID3D12DeviceRemovedExtendedData")]
[NativeInheritance("ID3D12DeviceRemovedExtendedData")]
internal unsafe partial struct ID3D12DeviceRemovedExtendedData1
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedData1*, Guid*, void**, int>)(lpVtbl[0]))((ID3D12DeviceRemovedExtendedData1*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedData1*, uint>)(lpVtbl[1]))((ID3D12DeviceRemovedExtendedData1*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedData1*, uint>)(lpVtbl[2]))((ID3D12DeviceRemovedExtendedData1*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public HRESULT GetAutoBreadcrumbsOutput1(D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1* pOutput)
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedData1*, D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1*, int>)(lpVtbl[5]))((ID3D12DeviceRemovedExtendedData1*)Unsafe.AsPointer(ref this), pOutput);
}
}
}
@@ -0,0 +1,62 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from d3d12.h in Microsoft.Direct3D.D3D12 v1.600.10
// Original source is Copyright © Microsoft. Licensed under the MIT license
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
namespace TerraFX.Interop.DirectX
{
[Guid("DBD5AE51-3317-4F0A-ADF9-1D7CEDCAAE0B")]
[NativeTypeName("struct ID3D12DeviceRemovedExtendedDataSettings1 : ID3D12DeviceRemovedExtendedDataSettings")]
[NativeInheritance("ID3D12DeviceRemovedExtendedDataSettings")]
internal unsafe partial struct ID3D12DeviceRemovedExtendedDataSettings1
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedDataSettings1*, Guid*, void**, int>)(lpVtbl[0]))((ID3D12DeviceRemovedExtendedDataSettings1*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
public uint AddRef()
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedDataSettings1*, uint>)(lpVtbl[1]))((ID3D12DeviceRemovedExtendedDataSettings1*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
public uint Release()
{
return ((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedDataSettings1*, uint>)(lpVtbl[2]))((ID3D12DeviceRemovedExtendedDataSettings1*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public void SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT Enablement)
{
((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedDataSettings1*, D3D12_DRED_ENABLEMENT, void>)(lpVtbl[3]))((ID3D12DeviceRemovedExtendedDataSettings1*)Unsafe.AsPointer(ref this), Enablement);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public void SetPageFaultEnablement(D3D12_DRED_ENABLEMENT Enablement)
{
((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedDataSettings1*, D3D12_DRED_ENABLEMENT, void>)(lpVtbl[4]))((ID3D12DeviceRemovedExtendedDataSettings1*)Unsafe.AsPointer(ref this), Enablement);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public void SetBreadcrumbContextEnablement(D3D12_DRED_ENABLEMENT Enablement)
{
((delegate* unmanaged[Stdcall]<ID3D12DeviceRemovedExtendedDataSettings1*, D3D12_DRED_ENABLEMENT, void>)(lpVtbl[6]))((ID3D12DeviceRemovedExtendedDataSettings1*)Unsafe.AsPointer(ref this), Enablement);
}
}
}
+7
ファイルの表示
@@ -72,6 +72,8 @@
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12shader\D3D12_SHADER_DESC.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12shader\ID3D12ShaderReflection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_AUTO_BREADCRUMB_NODE1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_AUTO_BREADCRUMB_OP.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_BOX.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_BUFFER_SRV.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_BUFFER_SRV_FLAGS.cs" />
@@ -98,6 +100,9 @@
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_DESCRIPTOR_RANGE1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_DESCRIPTOR_RANGE_FLAGS.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_DESCRIPTOR_RANGE_TYPE.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_DRED_AUTO_BREADCRUMB_OUTPUT1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_DRED_BREADCRUMB_CONTEXT.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_DRED_ENABLEMENT.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_FEATURE.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_FEATURE_DATA_ARCHITECTURE.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\D3D12_FEATURE_DATA_ARCHITECTURE1.cs" />
@@ -188,6 +193,8 @@
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12CommandQueue.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12DescriptorHeap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12Device.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12DeviceRemovedExtendedData1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12DeviceRemovedExtendedDataSettings1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12Fence.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12GraphicsCommandList.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d3d12\ID3D12Heap.cs" />
@@ -12,6 +12,4 @@
<PackageReference Include="ComputeSharp.Dynamic" Version="$(PackageVersion)" />
</ItemGroup>
<Import Project="..\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems" Label="Shared" />
</Project>
+35
ファイルの表示
@@ -0,0 +1,35 @@
using System.Diagnostics;
using System.Linq;
using ComputeSharp;
float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
// Create the graphics buffer
using ReadWriteBuffer<float> gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array);
// Run the shader
GraphicsDevice.Default.For(100, new MultiplyByTwo(gpuBuffer));
// Get the data back
float[] result = gpuBuffer.ToArray();
// Validate results
for (int i = 0; i < array.Length; i++)
{
Trace.Assert(result[i] == array[i] * 2);
}
/// <summary>
/// A sample kernel that requires dynamic compilation, as it's not precompiled.
/// </summary>
[AutoConstructor]
internal readonly partial struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
buffer[ThreadIds.X] *= 2;
}
}
差分なしでファイル名を変更。
+14
ファイルの表示
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net472;netcoreapp3.1;net6.0</TargetFrameworks>
<Platforms>AnyCPU;x64;ARM64</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ComputeSharp.Core" Version="$(PackageVersion)" />
<PackageReference Include="ComputeSharp" Version="$(PackageVersion)" />
</ItemGroup>
</Project>
+36
ファイルの表示
@@ -0,0 +1,36 @@
using System.Diagnostics;
using System.Linq;
using ComputeSharp;
float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
// Create the graphics buffer
using ReadWriteBuffer<float> gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array);
// Run the shader
GraphicsDevice.Default.For(100, new MultiplyByTwo(gpuBuffer));
// Get the data back
float[] result = gpuBuffer.ToArray();
// Validate results
for (int i = 0; i < array.Length; i++)
{
Trace.Assert(result[i] == array[i] * 2);
}
/// <summary>
/// A sample kernel that is precompiled.
/// </summary>
[EmbeddedBytecode(DispatchAxis.X)]
[AutoConstructor]
internal readonly partial struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
buffer[ThreadIds.X] *= 2;
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<!-- This source is for the local NuGet packages, which are all generated in the centralized artifacts root folder -->
<add key="artifacts" value="..\..\artifacts" />
</packageSources>
</configuration>
+15
ファイルの表示
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net472;netcoreapp3.1;net6.0</TargetFrameworks>
<Platforms>AnyCPU;x64;ARM64</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ComputeSharp.Core" Version="$(PackageVersion)" />
<PackageReference Include="ComputeSharp" Version="$(PackageVersion)" />
<PackageReference Include="ComputeSharp.Pix" Version="$(PackageVersion)" />
</ItemGroup>
</Project>
+42
ファイルの表示
@@ -0,0 +1,42 @@
using System.Diagnostics;
using System.Linq;
using ComputeSharp;
float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
// Create the graphics buffer
using ReadWriteBuffer<float> gpuBuffer = GraphicsDevice.Default.AllocateReadWriteBuffer(array);
// Run the shader
using (var context = GraphicsDevice.Default.CreateComputeContext())
{
context.Log("Dispatching shader");
context.BeginEvent("Dispatching event");
context.For(100, new MultiplyByTwo(gpuBuffer));
context.EndEvent();
}
// Get the data back
float[] result = gpuBuffer.ToArray();
// Validate results
for (int i = 0; i < array.Length; i++)
{
Trace.Assert(result[i] == array[i] * 2);
}
/// <summary>
/// A sample kernel that is precompiled.
/// </summary>
[EmbeddedBytecode(DispatchAxis.X)]
[AutoConstructor]
internal readonly partial struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
buffer[ThreadIds.X] *= 2;
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<!-- This source is for the local NuGet packages, which are all generated in the centralized artifacts root folder -->
<add key="artifacts" value="..\..\artifacts" />
</packageSources>
</configuration>
@@ -11,4 +11,9 @@
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Project\*" />
<None Include="Project\*" />
</ItemGroup>
</Project>
@@ -0,0 +1,37 @@
using System.Diagnostics;
using System.IO;
using ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.NativeLibrariesResolver;
[TestClass]
public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
{
/// <inheritdoc/>
protected override string SampleProjectName => "ComputeSharp.Dynamic.NuGet";
/// <summary>
/// Performs static initialization for the assembly before any unit tests are run.
/// </summary>
/// <param name="_">The <see cref="TestContext"/> for the test runner instance in use.</param>
[ClassInitialize]
public static void InitializeDynamicDependencies(TestContext _)
{
string path = Path.GetDirectoryName(typeof(DynamicNativeLibrariesResolverTests).Assembly.Location)!;
while (Path.GetFileName(path) is not "ComputeSharp")
{
path = Path.GetDirectoryName(path)!;
}
string corePackagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.msbuildproj");
string packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj");
string dynamicPackagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Dynamic.Package", "ComputeSharp.Dynamic.Package.msbuildproj");
// Run dotnet pack and on the packaging projects, to ensure the local NuGet packages are available
Process.Start("dotnet", $"pack {corePackagingProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {dynamicPackagingProjectPath} -c Release").WaitForExit();
}
}
@@ -0,0 +1,285 @@
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
/// <summary>
/// A base class to implement native libraries tests.
/// </summary>
public abstract class NativeLibrariesResolverTestsBase
{
/// <summary>
/// Gets the name of the test project.
/// </summary>
protected abstract string SampleProjectName { get; }
/// <summary>
/// Gets the directory containing the current test project.
/// </summary>
private string SampleProjectDirectory
{
get
{
string path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTestsBase).Assembly.Location)!;
while (Path.GetFileName(path) is not "tests")
{
path = Path.GetDirectoryName(path)!;
}
return Path.Combine(path, SampleProjectName);
}
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetRunWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", $"run -c {configuration} -f net6.0 {ToOption(rid)}"));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningDotnetHostFromProjectDirectoryWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string realtivePathToDll = Path.Combine("bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}", $"{SampleProjectName}.dll");
Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", realtivePathToDll));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningDotnetHostDirectlyWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}");
Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", $"{SampleProjectName}.dll"));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningAppHostFromProjectDirectoryWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}", $"{SampleProjectName}.exe");
Assert.AreEqual(0, Exec(SampleProjectDirectory, relativePathToAppHost, ""));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningAppHostDirectlyWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}");
Assert.AreEqual(0, Exec(pathToAppHostDirectory, $"{SampleProjectName}.exe", ""));
}
[TestMethod]
[DataRow(PublishMode.SelfContained, DeploymentMode.Multiassembly, NativeLibrariesDeploymentMode.NotApplicable)]
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.Multiassembly, NativeLibrariesDeploymentMode.NotApplicable)]
[DataRow(PublishMode.SelfContained, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.CopyToApplicationDirectory)]
[DataRow(PublishMode.SelfContained, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory)]
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.CopyToApplicationDirectory)]
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory)]
public void DotnetPublishWorks(PublishMode publishMode, DeploymentMode deploymentMode, NativeLibrariesDeploymentMode nativeLibsDeploymentMode)
{
// Publishing without specifying a RID is not supported.
// Furthermore, only publishing in Release mode is tested.
CleanSampleProject(Configuration.Release, RID.Win_x64);
Exec(SampleProjectDirectory, "dotnet", $"publish -c Release -f net6.0 -r win-x64 {ToOption(publishMode)} {ToOption(deploymentMode)} {ToOption(nativeLibsDeploymentMode)} /bl");
string pathToAppHost = Path.Combine("bin", $"Release", "net6.0", "win-x64", "publish", $"{SampleProjectName}.exe");
Assert.AreEqual(0, Exec(SampleProjectDirectory, pathToAppHost, ""));
}
/// <summary>
/// Cleans the sample project's artifacts for a specific configuration and target runtime.
/// This method is called at the start of each test method to work around bugs around some up-to-date checks
/// Causing certain targets to not run and effectively corrupting the build output.
/// </summary>
/// <param name="configuration">The configuration for which the output is cleaned.</param>
/// <param name="rid">The RID for which the output is cleaned.</param>
private void CleanSampleProject(Configuration configuration, RID rid)
{
Exec(SampleProjectDirectory, "dotnet", $"clean -c {configuration} {ToOption(rid)}");
}
/// <summary>
/// Builds the sample project with a specific configuration and target runtime.
/// </summary>
/// <param name="configuration">The configuration to use to build the project.</param>
/// <param name="rid">The RID to use to build the project.</param>
private void BuildSampleProject(Configuration configuration, RID rid)
{
Exec(SampleProjectDirectory, "dotnet", $"build -c {configuration} {ToOption(rid)}");
}
/// <summary>
/// Executes a specified process from the command line and returns the exit code.
/// </summary>
/// <param name="workingDirectory">The working directory to execute the process.</param>
/// <param name="filePath">The target file path for the process to execute.</param>
/// <param name="arguments">The arguments to invoke the process.</param>
/// <returns>The exit code for the executed process.</returns>
private static int Exec(string workingDirectory, string filePath, string arguments)
{
ProcessStartInfo startInfo = new()
{
UseShellExecute = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = filePath,
Arguments = arguments,
WorkingDirectory = workingDirectory
};
using Process process = Process.Start(startInfo)!;
process.WaitForExit();
return process.ExitCode;
}
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="RID"/>.
/// </summary>
/// <param name="rid">The input <see cref="RID"/> value.</param>
/// <returns>A text representation for <paramref name="rid"/>.</returns>
private static string ToOption(RID rid) => rid switch
{
RID.None => "",
RID.Win_x64 => "-r win-x64",
_ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID))
};
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="PublishMode"/>.
/// </summary>
/// <param name="publishMode">The input <see cref="PublishMode"/> value.</param>
/// <returns>A text representation for <paramref name="publishMode"/>.</returns>
private static string ToOption(PublishMode publishMode) => publishMode switch
{
PublishMode.FrameworkDependent => "--self-contained false",
PublishMode.SelfContained => "--self-contained true",
_ => throw new InvalidEnumArgumentException(nameof(publishMode), (int)publishMode, typeof(PublishMode))
};
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="DeploymentMode"/>.
/// </summary>
/// <param name="deploymentMode">The input <see cref="DeploymentMode"/> value.</param>
/// <returns>A text representation for <paramref name="deploymentMode"/>.</returns>
private static string ToOption(DeploymentMode deploymentMode) => deploymentMode switch
{
DeploymentMode.Multiassembly => "/p:PublishSingleFile=false",
DeploymentMode.SingleFile => "/p:PublishSingleFile=true",
_ => throw new InvalidEnumArgumentException(nameof(deploymentMode), (int)deploymentMode, typeof(DeploymentMode))
};
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="NativeLibrariesDeploymentMode"/>.
/// </summary>
/// <param name="deploymentMode">The input <see cref="NativeLibrariesDeploymentMode"/> value.</param>
/// <returns>A text representation for <paramref name="deploymentMode"/>.</returns>
private static string ToOption(NativeLibrariesDeploymentMode deploymentMode) => deploymentMode switch
{
NativeLibrariesDeploymentMode.NotApplicable => "",
NativeLibrariesDeploymentMode.CopyToApplicationDirectory => "/p:IncludeNativeLibrariesForSelfExtract=false",
NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory => "/p:IncludeNativeLibrariesForSelfExtract=true",
_ => throw new InvalidEnumArgumentException(nameof(deploymentMode), (int)deploymentMode, typeof(NativeLibrariesDeploymentMode))
};
/// <summary>
/// Gets a text representation of the build folder for the given <see cref="RID"/>.
/// </summary>
/// <param name="rid">The input <see cref="RID"/> value.</param>
/// <returns>A text representation for <paramref name="rid"/>.</returns>
private static string ToDirectory(RID rid) => rid switch
{
RID.None => "",
RID.Win_x64 => "win-x64",
_ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID))
};
}
/// <summary>
/// A build configuration.
/// </summary>
public enum Configuration
{
Debug,
Release
}
/// <summary>
/// A runtime identifier.
/// </summary>
public enum RID
{
None,
Win_x64
}
/// <summary>
/// Indicates how should the application carry the framework with itself.
/// </summary>
public enum PublishMode
{
FrameworkDependent,
SelfContained
}
/// <summary>
/// Indicates how should the application be packaged. Notably, these tests employ .NET 6 style SingleFile,
/// aka SuperHost. It does not affect native libraries packaging in .NET 6, but may in the future.
/// </summary>
public enum DeploymentMode
{
Multiassembly,
SingleFile
}
/// <summary>
/// Indicates the deployment mode for application's native dependencies.
/// Not applicable to multiassembly deployment mode.
/// </summary>
public enum NativeLibrariesDeploymentMode
{
NotApplicable,
ExtractToTemporaryDirectory,
CopyToApplicationDirectory
}
+12 -268
ファイルの表示
@@ -1,291 +1,35 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics;
using System.IO;
[assembly: Parallelize(Workers = 0, Scope = ExecutionScope.ClassLevel)]
using ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.NativeLibrariesResolver;
[TestClass]
public class NativeLibrariesResolverTests
public class NativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
{
/// <inheritdoc/>
protected override string SampleProjectName => "ComputeSharp.NuGet";
/// <summary>
/// Performs static initialization for the assembly before any unit tests are run.
/// </summary>
/// <param name="_">The <see cref="TestContext"/> for the test runner instance in use.</param>
[AssemblyInitialize]
public static void Initialize(TestContext _)
[ClassInitialize]
public static void InitializeDynamicDependencies(TestContext _)
{
string path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location)!;
string path = Path.GetDirectoryName(typeof(DynamicNativeLibrariesResolverTests).Assembly.Location)!;
while (Path.GetFileName(path) is not "ComputeSharp")
{
path = Path.GetDirectoryName(path)!;
}
SampleProjectDirectory = Path.Combine(path, "samples", "ComputeSharp.Sample.NuGet");
string corePackagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.msbuildproj");
string packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj");
string dynamicPackagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Dynamic.Package", "ComputeSharp.Dynamic.Package.msbuildproj");
// Run dotnet pack and on the packaging projects, to ensure the local NuGet packages are available
Process.Start("dotnet", $"pack {corePackagingProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {dynamicPackagingProjectPath} -c Release").WaitForExit();
}
/// <summary>
/// Gets the directory of the ComputeSharp.Sample.NuGet project.
/// </summary>
private static string? SampleProjectDirectory { get; set; }
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetRunWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
Assert.AreEqual(0, Exec(SampleProjectDirectory!, "dotnet", $"run -c {configuration} -f net6.0 {ToOption(rid)}"));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningDotnetHostFromProjectDirectoryWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string realtivePathToDll = Path.Combine("bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.dll");
Assert.AreEqual(0, Exec(SampleProjectDirectory!, "dotnet", realtivePathToDll));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningDotnetHostDirectlyWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string pathToDllDirectory = Path.Combine(SampleProjectDirectory!, "bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}");
Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", "ComputeSharp.Sample.NuGet.dll"));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningAppHostFromProjectDirectoryWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.exe");
Assert.AreEqual(0, Exec(SampleProjectDirectory!, relativePathToAppHost, ""));
}
[TestMethod]
[DataRow(Configuration.Debug, RID.None)]
[DataRow(Configuration.Debug, RID.Win_x64)]
[DataRow(Configuration.Release, RID.None)]
[DataRow(Configuration.Release, RID.Win_x64)]
public void DotnetBuildWithRunningAppHostDirectlyWorks(Configuration configuration, RID rid)
{
CleanSampleProject(configuration, rid);
BuildSampleProject(configuration, rid);
string pathToAppHostDirectory = Path.Combine(SampleProjectDirectory!, "bin", $"{configuration}", "net6.0", $"{ToDirectory(rid)}");
Assert.AreEqual(0, Exec(pathToAppHostDirectory, "ComputeSharp.Sample.NuGet.exe", ""));
}
[TestMethod]
[DataRow(PublishMode.SelfContained, DeploymentMode.Multiassembly, NativeLibrariesDeploymentMode.NotApplicable)]
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.Multiassembly, NativeLibrariesDeploymentMode.NotApplicable)]
[DataRow(PublishMode.SelfContained, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.CopyToApplicationDirectory)]
[DataRow(PublishMode.SelfContained, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory)]
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.CopyToApplicationDirectory)]
[DataRow(PublishMode.FrameworkDependent, DeploymentMode.SingleFile, NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory)]
public void DotnetPublishWorks(PublishMode publishMode, DeploymentMode deploymentMode, NativeLibrariesDeploymentMode nativeLibsDeploymentMode)
{
// Publishing without specifying a RID is not supported.
// Furthermore, only publishing in Release mode is tested.
CleanSampleProject(Configuration.Release, RID.Win_x64);
Exec(SampleProjectDirectory!, "dotnet", $"publish -c Release -f net6.0 -r win-x64 {ToOption(publishMode)} {ToOption(deploymentMode)} {ToOption(nativeLibsDeploymentMode)} /bl");
string pathToAppHost = Path.Combine("bin", $"Release", "net6.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe");
Assert.AreEqual(0, Exec(SampleProjectDirectory!, pathToAppHost, ""));
}
/// <summary>
/// Cleans the sample project's artifacts for a specific configuration and target runtime.
/// This method is called at the start of each test method to work around bugs around some up-to-date checks
/// Causing certain targets to not run and effectively corrupting the build output.
/// </summary>
/// <param name="configuration">The configuration for which the output is cleaned.</param>
/// <param name="rid">The RID for which the output is cleaned.</param>
private static void CleanSampleProject(Configuration configuration, RID rid)
{
Exec(SampleProjectDirectory!, "dotnet", $"clean -c {configuration} {ToOption(rid)}");
}
/// <summary>
/// Builds the sample project with a specific configuration and target runtime.
/// </summary>
/// <param name="configuration">The configuration to use to build the project.</param>
/// <param name="rid">The RID to use to build the project.</param>
private static void BuildSampleProject(Configuration configuration, RID rid)
{
Exec(SampleProjectDirectory!, "dotnet", $"build -c {configuration} {ToOption(rid)}");
}
/// <summary>
/// Executes a specified process from the command line and returns the exit code.
/// </summary>
/// <param name="workingDirectory">The working directory to execute the process.</param>
/// <param name="filePath">The target file path for the process to execute.</param>
/// <param name="arguments">The arguments to invoke the process.</param>
/// <returns>The exit code for the executed process.</returns>
private static int Exec(string workingDirectory, string filePath, string arguments)
{
ProcessStartInfo startInfo = new()
{
UseShellExecute = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = filePath,
Arguments = arguments,
WorkingDirectory = workingDirectory
};
using Process process = Process.Start(startInfo)!;
process.WaitForExit();
return process.ExitCode;
}
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="RID"/>.
/// </summary>
/// <param name="rid">The input <see cref="RID"/> value.</param>
/// <returns>A text representation for <paramref name="rid"/>.</returns>
private static string ToOption(RID rid) => rid switch
{
RID.None => "",
RID.Win_x64 => "-r win-x64",
_ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID))
};
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="PublishMode"/>.
/// </summary>
/// <param name="publishMode">The input <see cref="PublishMode"/> value.</param>
/// <returns>A text representation for <paramref name="publishMode"/>.</returns>
private static string ToOption(PublishMode publishMode) => publishMode switch
{
PublishMode.FrameworkDependent => "--self-contained false",
PublishMode.SelfContained => "--self-contained true",
_ => throw new InvalidEnumArgumentException(nameof(publishMode), (int)publishMode, typeof(PublishMode))
};
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="DeploymentMode"/>.
/// </summary>
/// <param name="deploymentMode">The input <see cref="DeploymentMode"/> value.</param>
/// <returns>A text representation for <paramref name="deploymentMode"/>.</returns>
private static string ToOption(DeploymentMode deploymentMode) => deploymentMode switch
{
DeploymentMode.Multiassembly => "/p:PublishSingleFile=false",
DeploymentMode.SingleFile => "/p:PublishSingleFile=true",
_ => throw new InvalidEnumArgumentException(nameof(deploymentMode), (int)deploymentMode, typeof(DeploymentMode))
};
/// <summary>
/// Gets a text representation of the command line argument for the given <see cref="NativeLibrariesDeploymentMode"/>.
/// </summary>
/// <param name="deploymentMode">The input <see cref="NativeLibrariesDeploymentMode"/> value.</param>
/// <returns>A text representation for <paramref name="deploymentMode"/>.</returns>
private static string ToOption(NativeLibrariesDeploymentMode deploymentMode) => deploymentMode switch
{
NativeLibrariesDeploymentMode.NotApplicable => "",
NativeLibrariesDeploymentMode.CopyToApplicationDirectory => "/p:IncludeNativeLibrariesForSelfExtract=false",
NativeLibrariesDeploymentMode.ExtractToTemporaryDirectory => "/p:IncludeNativeLibrariesForSelfExtract=true",
_ => throw new InvalidEnumArgumentException(nameof(deploymentMode), (int)deploymentMode, typeof(NativeLibrariesDeploymentMode))
};
/// <summary>
/// Gets a text representation of the build folder for the given <see cref="RID"/>.
/// </summary>
/// <param name="rid">The input <see cref="RID"/> value.</param>
/// <returns>A text representation for <paramref name="rid"/>.</returns>
private static string ToDirectory(RID rid) => rid switch
{
RID.None => "",
RID.Win_x64 => "win-x64",
_ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID))
};
/// <summary>
/// A build configuration.
/// </summary>
public enum Configuration
{
Debug,
Release
}
/// <summary>
/// A runtime identifier.
/// </summary>
public enum RID
{
None,
Win_x64
}
/// <summary>
/// Indicates how should the application carry the framework with itself.
/// </summary>
public enum PublishMode
{
FrameworkDependent,
SelfContained
}
/// <summary>
/// Indicates how should the application be packaged. Notably, these tests employ .NET 6 style SingleFile,
/// aka SuperHost. It does not affect native libraries packaging in .NET 6, but may in the future.
/// </summary>
public enum DeploymentMode
{
Multiassembly,
SingleFile
}
/// <summary>
/// Indicates the deployment mode for application's native dependencies.
/// Not applicable to multiassembly deployment mode.
/// </summary>
public enum NativeLibrariesDeploymentMode
{
NotApplicable,
ExtractToTemporaryDirectory,
CopyToApplicationDirectory
}
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.Diagnostics;
using System.IO;
using ComputeSharp.Tests.NativeLibrariesResolver.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.NativeLibrariesResolver;
[TestClass]
public class PixNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
{
/// <inheritdoc/>
protected override string SampleProjectName => "ComputeSharp.Pix.NuGet";
/// <summary>
/// Performs static initialization for the assembly before any unit tests are run.
/// </summary>
/// <param name="_">The <see cref="TestContext"/> for the test runner instance in use.</param>
[ClassInitialize]
public static void InitializeDynamicDependencies(TestContext _)
{
string path = Path.GetDirectoryName(typeof(PixNativeLibrariesResolverTests).Assembly.Location)!;
while (Path.GetFileName(path) is not "ComputeSharp")
{
path = Path.GetDirectoryName(path)!;
}
string corePackagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.msbuildproj");
string packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj");
string pixPackagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Pix.Package", "ComputeSharp.Pix.Package.msbuildproj");
// Run dotnet pack and on the packaging projects, to ensure the local NuGet packages are available
Process.Start("dotnet", $"pack {corePackagingProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit();
Process.Start("dotnet", $"pack {pixPackagingProjectPath} -c Release").WaitForExit();
}
}
+3
ファイルの表示
@@ -0,0 +1,3 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
[assembly: DoNotParallelize]