diff --git a/.gitattributes b/.gitattributes index 13a72119..90afa28e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -20,3 +20,5 @@ # Explicitly declare resource files as binary *.pdb binary +*.png binary +*.spritefont binary diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index a2126d55..77eb78d6 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -31,7 +31,7 @@ These instructions define how GitHub Copilot should assist with this project. Th ## File Structure -```txt +```plaintext .azuredevops/ # Azure DevOps pipeline configuration and policy files. .github/ # GitHub Actions workflow files and linter configuration files. .nuget/ # NuGet package configuration files. @@ -42,6 +42,7 @@ Src/ # Implementation header and source files. Shaders/ # HLSL shader files. MakeSpriteFont/ # C# CLI tool for capturing sprite fonts. XWBTool/ # C++ CLI tool for creating XACT-style wave banks. +skills/ # Published CoPilot skills for use by developers. Tests/ # Tests are designed to be cloned from a separate repository at this location. wiki/ # Local clone of the GitHub wiki documentation repository. ``` @@ -320,30 +321,4 @@ When reviewing documentation, do the following: ## Release Process -1. Ensure all changes are merged into the `main` branch and that all tests pass. -2. Git pull the local repository to ensure it is up to date with the `main` branch. -3. Run the PowerShell script `build\preparerelease.ps1` which will generate a topic branch for the release, update the version number in `CMakeLists.txt`, the `README.md` file, the release notes in the nuspec files, and create a stub in the `CHANGELOG.md` file for the new release. -4. Edit the `CHANGELOG.md` file to update it with a summary of changes. -5. Submit the topic branch for review and merge into `main` once approved. Allow the GitHub Actions workflows and the Azure DevOps pipelines to complete successfully before proceeding. -6. Run the PowerShell script `build\completerelease.ps1` which will set a tag on the project repo and the test repo, and create a release on GitHub with the release notes from `CHANGELOG.md`. Ensure you have set up GPG signing for your GitHub account so that the tags will be verified. -7. Git pull the local repository to ensure it is up to date with the `main` branch. Be sure to include `--tags`. -8. Push the `main` branch to the MSCodeHub mirror repository. Be sure to include `--tags`. -9. Create a PR on MSCodeHub from the `main` branch to the `release` branch. -10. Merge the PR on MSCodeHub to update the release branch, which will trigger the Azure DevOps pipeline to build signed binaries and the NuGet packages. -11. Run the PowerShell script `build\downloadartifacts.ps1` to download the signed binaries from the Azure DevOps pipeline artifacts. -12. Edit the GitHub release and upload the signed binaries to the release assets. -13. Download the GitHub source .zip archive from the release. Unzip and compare to the local repo to ensure it matches — keep in mind there may be some CR/LF differences. Run minisign on the .zip to generate a signature file, and upload the signature file to the release assets. -14. Validate the NuGet packages with by pushing the NuGet packages to a local Packages Source folder, and refreshing the NuGet packages from that folder. Then build using BuildAllSolutions.targets. -15. Run the PowerShell script `build\promotenuget.ps1` with the `-Release` parameter to promote the version to the Release view on the project-scoped ADO feed. -16. Run the MSCodeHub pipeline to publish the NuGet packages to nuget.org. The pipeline will automatically push the most recent package promoted to the Release view to nuget.org. -17. Git pull a local repository of VCPKG to `d:\vcpkg` in sync with the `main` branch of the VCPKG repository. -18. Run the PowerShell script `build\updatevcpkg.ps1` to update the DirectXTK port in VCPKG with the new release version. This will edit the files in `ports\directxtk`. -19. Test the VCPKG port using all appropriate triplets and features. -20. Run `.\vcpkg --x-add-version directxtk` to update the VCPKG versioning history. -21. Submit a PR to the VCPKG repository to update the DirectXTK port back to the main GitHub repo. The PR will be reviewed and merged by the VCPKG maintainers. -22. If relevant changes were made to the `xwbtool` or `MakeSpriteFont` tools, update the winget manifests for those tools in the `winget` repository. -- Git pull a local repository to `D:\winget-pkgs` in sync with the `master` branch of the WinGet repository. -- Run the PowerShell script `build\updatewinget.ps1` to update the winget manifests for the tools with the new release version. -- Submit a PR to the `winget` repository to update the manifests for each tool — they must be done as distinct PRs. The PRs will be reviewed and merged by the winget maintainers. - -> When fully completed, be sure to update the GitHub release with links to the matching NuGet packages, the VCPKG port, and the winget manifests for the tools. +The release process is documented in the [release skill](.github/skills/release/SKILL.md). Invoke the `release` skill for step-by-step guidance when performing a release. diff --git a/.github/skills/release/SKILL.md b/.github/skills/release/SKILL.md new file mode 100644 index 00000000..f3c0e06c --- /dev/null +++ b/.github/skills/release/SKILL.md @@ -0,0 +1,83 @@ +--- +name: release +description: Guide for performing the DirectX Tool Kit for DirectX 11 release process. Use this skill when asked to help with releasing a new version, publishing packages, or updating ports. +--- + +# Release Process + +## Prerequisites + +- All changes merged into the `main` branch with all tests passing. +- GPG signing configured for your GitHub account (for verified tags). +- Access to the MSCodeHub mirror repository and Azure DevOps pipelines. +- Local repositories: + - VCPKG at `d:\vcpkg` (synced with `main` branch) + - WinGet at `D:\winget-pkgs` (synced with `master` branch, only if tool updates needed) +- PATs will be needed for scripts that access GitHub and ADO. + + +## Steps + +### Phase 1: Prepare Release + +1. Git pull the local repository to ensure it is up to date with the `main` branch. +2. Run the PowerShell script `build\preparerelease.ps1` which will generate a topic branch for the release, update the version number in `CMakeLists.txt`, the `README.md` file, the release notes in the nuspec files, and create a stub in the `CHANGELOG.md` file for the new release. +3. Edit the `CHANGELOG.md` file to update it with a summary of changes. +4. Submit the topic branch for review and merge into `main` once approved. Allow the GitHub Actions workflows and the Azure DevOps pipelines to complete successfully before proceeding. + +### Phase 2: Tag and Create GitHub Release + +5. Run the PowerShell script `build\completerelease.ps1` which will set a tag on the project repo and the test repo, and create a release on GitHub with the release notes from `CHANGELOG.md`. Ensure you have set up GPG signing for your GitHub account so that the tags will be verified. +6. Git pull the local repository to ensure it is up to date with the `main` branch. Be sure to include `--tags`. + +### Phase 3: MSCodeHub and Signed Binaries + +7. Push the `main` branch to the MSCodeHub mirror repository. Be sure to include `--tags`. +8. Create a PR on MSCodeHub from the `main` branch to the `release` branch. +9. Merge the PR on MSCodeHub to update the release branch, which will trigger the Azure DevOps pipeline to build signed binaries and the NuGet packages. +10. Run the PowerShell script `build\downloadbuild.ps1` to download the signed binaries from the Azure DevOps pipeline artifacts. +11. Edit the GitHub release and upload the signed binaries to the release assets. + +### Phase 4: Source Archive Signing + +12. Download the GitHub source .zip archive from the release. Unzip and compare to the local repo to ensure it matches — keep in mind there may be some CR/LF differences. +13. Run minisign on the .zip to generate a signature file, and upload the signature file to the release assets. + +### Phase 5: NuGet Validation and Publishing + +14. Validate the NuGet packages with by pushing the NuGet packages to a local Packages Source folder, and refreshing the NuGet packages from that folder. Then build using BuildAllSolutions.targets. +15. Run the PowerShell script `build\promotenuget.ps1 -Version -Release` to promote the version to the Release view on the project-scoped ADO feed. The `-Version` parameter is required and should match the NuGet package version (e.g., `2026.6.2.1`). +16. Run the MSCodeHub pipeline to publish the NuGet packages to nuget.org. The pipeline will automatically push the most recent package promoted to the Release view to nuget.org. + +### Phase 6: VCPKG Port Update + +17. Git pull a local repository of VCPKG to `d:\vcpkg` in sync with the `main` branch of the VCPKG repository. +18. Run the PowerShell script `build\updatevcpkg.ps1` to update the DirectXTK port in VCPKG with the new release version. This will edit the files in `ports\directxtk`. + If the port includes patches, review them to determine if they should be removed or updated for the new release (the `updatevcpkg.ps1` script will warn about this). +19. Test the VCPKG port using the script at `assets/vcpkgdxtk.cmd` (in this skill folder). Copy it to `d:\vcpkg` and run from there after bootstrapping VCPKG. +20. Run `.\vcpkg x-add-version directxtk` to update the VCPKG versioning history. +21. Submit a PR to the VCPKG repository to update the DirectXTK port back to the main GitHub repo. The PR will be reviewed and merged by the VCPKG maintainers. + +### Phase 7: WinGet Manifests (Conditional) + +If relevant changes were made to the `xwbtool` or `MakeSpriteFont` tools: + +22. Git pull a local repository to `D:\winget-pkgs` in sync with the `master` branch of the WinGet repository. +23. Run the PowerShell script `build\updatewinget.ps1` to update the winget manifests for the tools with the new release version. +24. Submit a PR to the `winget` repository to update the manifests for each tool — they must be done as distinct PRs. The PRs will be reviewed and merged by the winget maintainers. + +### Phase 8: Finalize + +When fully completed, be sure to update the GitHub release with links to the matching NuGet packages, the VCPKG port, and the winget manifests for the tools. + +## Key Scripts + +| Script | Purpose | +| --- | --- | +| `build\preparerelease.ps1` | Creates topic branch, updates version numbers and changelog stub | +| `build\completerelease.ps1` | Sets tags, creates GitHub release from changelog | +| `build\downloadbuild.ps1` | Downloads signed binaries from Azure DevOps | +| `build\promotenuget.ps1` | Promotes NuGet package to Release view on ADO feed | +| `build\updatevcpkg.ps1` | Updates DirectXTK VCPKG port files | +| `assets\vcpkgdxtk.cmd` | Tests VCPKG port across all triplets and features | +| `build\updatewinget.ps1` | Updates winget manifests for CLI tools | diff --git a/.github/skills/release/assets/vcpkgdxtk.cmd b/.github/skills/release/assets/vcpkgdxtk.cmd new file mode 100644 index 00000000..e2c59b37 --- /dev/null +++ b/.github/skills/release/assets/vcpkgdxtk.cmd @@ -0,0 +1,167 @@ +@set VCPKG_BINARY_SOURCES=clear +@set VCPKG_ROOT=%cd% +@if %1.==clang. goto clang +.\vcpkg install directxtk[core]:x86-windows +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x86-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2-8]:x86-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2-9]:x86-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[windows-gaming-input]:x86-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x86-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[spectre]:x86-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:x86-windows-static +@if errorlevel 1 goto error +.\vcpkg install directxtk:x86-windows-static-md +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x86-windows-static-md --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[core]:x64-windows +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2-8]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2-9]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[windows-gaming-input]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x64-windows-static-md --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[gameinput]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[gameinput]:x64-windows-static-md --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[spectre]:x64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:x64-windows-static +@if errorlevel 1 goto error +.\vcpkg install directxtk:x64-windows-static-md +@if errorlevel 1 goto error +.\vcpkg install directxtk[core]:arm64-windows +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:arm64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[windows-gaming-input]:arm64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:arm64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[spectre]:arm64-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64-windows-static +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64-windows-static-md +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:arm64-windows-static-md --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64ec-windows +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:arm64ec-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[spectre]:arm64ec-windows --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:x86-uwp +@if errorlevel 1 goto error +.\vcpkg install directxtk:x64-uwp +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64-uwp +@if errorlevel 1 goto error +@where /Q x86_64-w64-mingw32-g++.exe +@if errorlevel 1 goto skipgcc64 +.\vcpkg install directxtk:x64-mingw-dynamic +@if errorlevel 1 goto error +.\vcpkg install directxtk[core]:x64-mingw-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[gameinput]:x64-mingw-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x64-mingw-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x64-mingw-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[core]:x64-mingw-static +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x64-mingw-static --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[gameinput]:x64-mingw-static --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x64-mingw-static --recurse +@if errorlevel 1 goto error +:skipgcc64 +@where /Q i686-w64-mingw32-g++.exe +@if errorlevel 1 goto finish +.\vcpkg install directxtk:x86-mingw-dynamic +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x86-mingw-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x86-mingw-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:x86-mingw-static +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x86-mingw-static --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x86-mingw-static --recurse +@if errorlevel 1 goto error +@goto finish +:clang +.\vcpkg install directxtk:x64-clangcl-dynamic +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:x64-clangcl-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2-8]:x64-clangcl-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2-9]:x64-clangcl-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:x64-clangcl-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:x64-clangcl-static +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64-clangcl-dynamic +@if errorlevel 1 goto error +.\vcpkg install directxtk[tools]:arm64-clangcl-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk[xaudio2redist]:arm64-clangcl-dynamic --recurse +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64-clangcl-static +@if errorlevel 1 goto error +.\vcpkg install directxtk:x64-clangcl-uwp +@if errorlevel 1 goto error +.\vcpkg install directxtk:arm64-clangcl-uwp +@if errorlevel 1 goto error +:finish +@echo SUCCEEDED +@if %1.==clang. goto eof +@where /Q x86_64-w64-mingw32-g++.exe +@if NOT errorlevel 1 goto gcc64 +@echo . +@echo . Run for MinGW64 +@echo . .\vcpkg install directxtk:x64-mingw-dynamic +@echo . .\vcpkg install directxtk[gameinput]:x64-mingw-dynamic --recurse +@echo . .\vcpkg install directxtk[xaudio2redist]:x64-mingw-dynamic --recurse +@echo . .\vcpkg install directxtk[tools]:x64-mingw-dynamic --recurse +@echo . .\vcpkg install directxtk:x64-mingw-static +@echo . .\vcpkg install directxtk[gameinput]:x64-mingw-static --recurse +@echo . .\vcpkg install directxtk[xaudio2redist]:x64-mingw-static --recurse +@echo . .\vcpkg install directxtk[tools]:x64-mingw-static --recurse +:gcc64 +@where /Q i686-w64-mingw32-g++.exe +@if NOT errorlevel 1 goto gcc32 +@echo . +@echo . Run for MinGW32 +@echo . .\vcpkg install directxtk:x86-mingw-dynamic +@echo . .\vcpkg install directxtk[xaudio2redist]:x86-mingw-dynamic--recurse +@echo . .\vcpkg install directxtk[tools]:x86-mingw-dynamic --recurse +@echo . .\vcpkg install directxtk:x86-mingw-static +@echo . .\vcpkg install directxtk[xaudio2redist]:x86-mingw-static --recurse +@echo . .\vcpkg install directxtk[tools]:x86-mingw-static --recurse +:gcc32 +@goto eof +:error +@echo FAILED +:eof diff --git a/.gitignore b/.gitignore index 669de9af..e1e23fce 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,4 @@ packages /CMakeUserPresets.json /build/vcpkg_installed /build/*.exe +!**/skills/** diff --git a/README.md b/README.md index d1a8343d..4263394b 100644 --- a/README.md +++ b/README.md @@ -62,10 +62,26 @@ These components are designed to work without requiring any content from the leg * Contains miscellaneous build files and scripts. +* ``skills\`` + + * Contains published CoPilot skills for use by developers. + ## Documentation Documentation is available on the [GitHub wiki](https://github.com/Microsoft/DirectXTK/wiki). +## CoPilot Usage + +For CoPilot CLI assistance with using DirectX Tool Kit, try: + +```bash +winget install GitHub.Copilot +winget install GitHub.cli +gh skill install microsoft/directxtk +copilot +/skills list +``` + ## Notices All content and source code for this package are subject to the terms of the [MIT License](https://github.com/microsoft/DirectXTK/blob/main/LICENSE). diff --git a/skills/directxtk-tutorial/SKILL.md b/skills/directxtk-tutorial/SKILL.md new file mode 100644 index 00000000..a42d8dfb --- /dev/null +++ b/skills/directxtk-tutorial/SKILL.md @@ -0,0 +1,42 @@ +--- +name: directxtk-tutorial +description: >- + Walk through the DirectX Tool Kit for DirectX 11 Getting Started tutorial step by step. Use this skill when + asked to follow the tutorial, set up a new DirectX 11 project, or learn how to use DirectX Tool Kit from scratch. +license: MIT +metadata: + author: chuckw + version: "1.0" +--- + +# DirectX Tool Kit for DirectX 11 — Getting Started Tutorial + +This skill walks the user through the [Getting Started](https://github.com/microsoft/DirectXTK/wiki/Getting-Started) tutorial for DirectX Tool Kit step by step. + +Follow each step in order. Each step builds on the previous one. + +At the end of each step, **ask the user** if they would like to see the Technical Notes section (which provides a brief overview of the underlying Direct3D APIs and objects used by the toolkit in that step) or skip it and move on to the next step. + +## Tutorial Steps + +| Step | Title | Reference | +| ------ | ------- | ----------- | +| 0 | Prerequisites | [reference/step0.md](reference/step0.md) | +| 1 | Project Setup | [reference/step1.md](reference/step1.md) | +| 2 | Building the Project | [reference/step2.md](reference/step2.md) | +| 3 | Adding DirectX Tool Kit | [reference/step3.md](reference/step3.md) | +| 4 | Sprites and Textures | [reference/step4.md](reference/step4.md) | +| 5 | Drawing Text | [reference/step5.md](reference/step5.md) | +| 6 | Simple Rendering | [reference/step6.md](reference/step6.md) | +| 7 | 3D Shapes | [reference/step7.md](reference/step7.md) | + +## Assets + +The `assets/` folder contains files needed during the tutorial: + +- `cat.png` — sprite texture used in Step 4 +- `courier.spritefont` — pre-built sprite font used in Step 5 + +## Full Tutorial Sequence + +See [reference/tutorial-steps.md](reference/tutorial-steps.md) for the complete list of planned tutorial lessons beyond these initial seven steps. diff --git a/skills/directxtk-tutorial/assets/cat.png b/skills/directxtk-tutorial/assets/cat.png new file mode 100644 index 00000000..d6e0e60f Binary files /dev/null and b/skills/directxtk-tutorial/assets/cat.png differ diff --git a/skills/directxtk-tutorial/assets/courier.spritefont b/skills/directxtk-tutorial/assets/courier.spritefont new file mode 100644 index 00000000..986333eb Binary files /dev/null and b/skills/directxtk-tutorial/assets/courier.spritefont differ diff --git a/skills/directxtk-tutorial/reference/nextsteps.md b/skills/directxtk-tutorial/reference/nextsteps.md new file mode 100644 index 00000000..4112d590 --- /dev/null +++ b/skills/directxtk-tutorial/reference/nextsteps.md @@ -0,0 +1,61 @@ +# Next Steps + +## Graphics + +To explore more about DirectX Graphics functionality, continue with the tutorials at [Getting Started](https://github.com/microsoft/DirectXTK/wiki/Getting-Started) starting at [Rendering a model](https://github.com/microsoft/DirectXTK/wiki/Rendering-a-model). + +## Input + +To implement game input using GamePad, see [Game controller input](https://github.com/microsoft/DirectXTK/wiki/Game-controller-input) which for this tutorial's project will use the GameInput APIs. + +To implement game input using Mouse and Keyboard, see [Mouse and keyboard input](https://github.com/microsoft/DirectXTK/wiki/Mouse-and-keyboard-input). + +## Math + +For more on the SimpleMath library, which is a C++ wrapper for the DirectXMath SIMD library, see [Using the SimpleMath library](https://github.com/microsoft/DirectXTK/wiki/Using-the-SimpleMath-library). + +Alternatively, advanced users can use the **directxmath-usage** skill from [DirectXMath](https://github.com/microsoft/DirectXMath). + +## DirectX Tool Kit for Audio + +The audio functionality is built on XAudio2 which is a game audio API for Windows which provides real-time mixing and audio processing capabilities. + +To add *DirectX Tool Kit for Audio* to your project, update the `vcpkg.json` file: + +```json +{ + "name": "directxtk", + "default-features": false, + "features": [ + "gameinput", + "xaudio2-9" + ] +} +``` + +For example, the full `vcpkg.json` should look something like: + +```json +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "dependencies": [ + "directxmath", + { + "name": "directxtk", + "default-features": false, + "features": [ + "gameinput", + "xaudio2-9" + ] + } + ] +} +``` + +Then add to the pch.h: + +```cpp +#include +``` + +From there, pick up at [Adding audio to your project](https://github.com/microsoft/DirectXTK/wiki/Adding-audio-to-your-project). diff --git a/skills/directxtk-tutorial/reference/step0.md b/skills/directxtk-tutorial/reference/step0.md new file mode 100644 index 00000000..6b494a91 --- /dev/null +++ b/skills/directxtk-tutorial/reference/step0.md @@ -0,0 +1,82 @@ +# Step 0: Prerequisites + +Before starting the tutorial, verify the user has the necessary tools and environment set up. + +**Ask the user:** Have you already installed the tools below, or would you like help checking? + +## Required Software + +| Tool | Minimum Version | Purpose | +| ------ | ----------------- | --------- | +| **Visual Studio 2022** or **Visual Studio 2026** | 17.4+ / any | IDE and C++ compiler | +| **Desktop development with C++** workload | — | Includes MSVC toolset, Windows SDK, and CMake tools | +| **VCPKG component** (`Microsoft.VisualStudio.Component.Vcpkg`) | — | Package manager integration for dependencies | +| **Windows SDK** | 10.0.22000.0+ (Windows 11) | DirectX 11 headers and libraries | +| **Git** | any | Clone templates and manage source control | + +> Visual Studio Community edition is sufficient. The **VCPKG component** is included in the "Desktop development with C++" workload by default in VS 2022 17.7+ and VS 2026. + +## Optional but Recommended + +| Tool | Purpose | +| ------ | --------- | +| **CMake** (3.21+) | Required only if creating a CMake project instead of MSBuild | +| **Windows Terminal** | Better terminal experience for PowerShell commands | +| **Visual Studio Graphics Debugger** | GPU debugging | + +## Verification Steps + +Run the following checks in a PowerShell terminal to confirm the environment is ready: + +### Visual Studio + +```powershell +# Verify a VS 2022 or later install with the C++ Desktop workload +& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -version "[17.0," -requires Microsoft.VisualStudio.Workload.NativeDesktop -property installationPath +``` + +### Windows SDK + +```powershell +# Check for a Windows 11 SDK (10.0.22000.0 or later) +Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots" -ErrorAction SilentlyContinue | + Get-ItemProperty | Select-Object -ExpandProperty KitsRoot10 -ErrorAction SilentlyContinue +``` + +### VCPKG + +```powershell +# Verify the vcpkg component is present in the VS install +$vsPath = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -version "[17.0," -requires Microsoft.VisualStudio.Component.Vcpkg -property installationPath | Select-Object -First 1 +Test-Path "$vsPath\VC\vcpkg\vcpkg.exe" +``` + +### Git + +```powershell +git --version +``` + +## Troubleshooting + +- **Missing VCPKG component** — Open the Visual Studio Installer, click **Modify**, and ensure the "Desktop development with C++" workload is checked. In the Individual Components tab, confirm `Microsoft.VisualStudio.Component.Vcpkg` is selected. +- **Windows SDK not found** — Install a Windows 11 SDK (10.0.22000.0 or later) through the Visual Studio Installer under Individual Components. +- **Git not found** — Install Git from or via `winget install Git.Git`. + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +### Why vcpkg? + +The tutorial uses vcpkg in **manifest mode** to manage DirectX Tool Kit as a dependency. This approach: + +1. **Pins dependency versions** via `vcpkg.json` and `vcpkg-configuration.json`, ensuring reproducible builds. +2. **Avoids manual library setup** — no need to download, build, or configure include/library paths yourself. +3. **Supports multiple configurations** — vcpkg handles Debug/Release and x64/ARM64 builds through triplets. + +### DirectX 11 and Windows + +Direct3D 11 is available on Windows 10 and Windows 11 (all editions). The Windows SDK provides the `d3d11.h`, `dxgi1_2.h`, and related headers. No separate DirectX SDK download is required — the legacy standalone DirectX SDK (June 2010) is not needed for this tutorial. + +> For more background on the modern Windows SDK vs. the legacy DirectX SDK, see [this blog post](https://walbourn.github.io/where-is-the-directx-sdk-2024-edition/). diff --git a/skills/directxtk-tutorial/reference/step1.md b/skills/directxtk-tutorial/reference/step1.md new file mode 100644 index 00000000..b4256833 --- /dev/null +++ b/skills/directxtk-tutorial/reference/step1.md @@ -0,0 +1,124 @@ +# Step 1: Project Setup + +First, determine if the user needs a new project or already has one. + +**Ask the user:** Do you want to create a new project, or do you already have an existing Direct3D 11 project? + +## Creating a New Project + +If the user wants a new project, use the `d3d11game_vcpkg` template from . + +**Ask the user:** + +1. What project name would you like? (Default: `Direct3DGame`) +2. Do you want an MSBuild (.vcxproj) project or a CMake project (CMake recommended)? +3. Where should the project be created? (Default: `$Env:USERPROFILE\source`) + +Then download the templates from the latest GitHub release and run the appropriate script: + +```powershell +# Download and extract the templates repo from the latest release +$release = (Invoke-RestMethod -Uri "https://api.github.com/repos/walbourn/directx-vs-templates/releases/latest").tag_name +$templatesZip = "$env:TEMP\directx-vs-templates.zip" +$templatesDir = "$env:TEMP\directx-vs-templates" +Invoke-WebRequest -Uri "https://github.com/walbourn/directx-vs-templates/archive/refs/tags/$release.zip" -OutFile $templatesZip +Expand-Archive -Path $templatesZip -DestinationPath $templatesDir -Force +$repoRoot = Get-ChildItem -Path $templatesDir -Directory | Select-Object -First 1 +``` + +### MSBuild + +```powershell +& "$($repoRoot.FullName)\VSIX\createmsbuild.ps1" d3d11game_vcpkg +``` + +Parameters: +- `TemplateDir`: Use `d3d11game_vcpkg` for the DirectX 11 game template with vcpkg integration. +- `ProjectName`: The project name (default: `Direct3DGame`). Used for the `.vcxproj` filename and solution. +- `TargetDir`: Output directory (default: `$Env:USERPROFILE\source`). A subdirectory named `` is created here. +- `PlatformToolset`: VS platform toolset (default: `v143` for VS 2022, use `v144` for VS 2026). + +### CMake + +```powershell +& "$($repoRoot.FullName)\VSIX\createcmake.ps1" d3d11game_vcpkg +``` + +Parameters: +- `TemplateDir`: Use `d3d11game_vcpkg` for the DirectX 11 game template with vcpkg integration. +- `ProjectName`: The project name (default: `Direct3DGame`). Used for the CMake project name. +- `TargetDir`: Output directory (default: `$Env:USERPROFILE\source`). A subdirectory named `` is created here. + +### Cleanup + +After the project is created, clean up the temp files: + +```powershell +Remove-Item -Path $templatesZip -Force +Remove-Item -Path $templatesDir -Recurse -Force +``` + +### Note for git repositories + +If the project is being created in a git repository, then the `.gitignore` file at the root of the repository should be updated to exclude the vcpkg installed files and build artifacts. + +```plaintext +**/vcpkg_installed/ +``` + +## Using an Existing Project + +If the user already has a project, verify they have: + +1. A Direct3D 11 device and device context +2. A render loop with SwapChain and Present +3. DirectXTK integrated via vcpkg, NuGet, or project reference (see the **directxtk-usage** skill for integration guidance) + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +The `d3d11game_vcpkg` template creates a minimal Direct3D 11 application with the following architecture: + +### Overview + +The basics of a Win32 Direct3D 11 application include: + +1. **Win32 window creation** — A window is created using the Win32 API. +2. **Direct3D 11 device initialization** — The DXGI API is used to enumerate adapters, and then a ID3D11Device object is created which is used for creating resources. In addition to creating the device, a ID3D11DeviceContext object is created which is used for rendering operations and state management. +3. **Render loop** — For a game application, a loop is run to update the game state and render the scene each frame. Unlike in traditional applications, the game loop is real-time and continuous rather than waiting for user input. +4. **Swap chain management** — A IDXGISwapChain object is used to manage the presentation of rendered frames. If the application rendering gets too far ahead of the display, it will wait until more frames are fully processed. + +### Main.cpp — Application Entry Point + +- **Win32 window creation** — Registers a `WNDCLASSEX`, creates an `HWND` with `CreateWindowExW`, and runs a standard `PeekMessage` loop. When no messages are pending, `Game::Tick()` is called to drive the game loop. +- **Window message handling** — The `WndProc` handles resize (`WM_SIZE`), minimize/restore (suspend/resume), ALT+ENTER fullscreen toggle, display changes, and power management. +- **Hybrid GPU preference** — Exports `NvOptimusEnablement` and `AmdPowerXpressRequestHighPerformance` to prefer discrete GPUs on hybrid systems. +- **COM initialization** — Calls `CoInitializeEx` (multithreaded) which is required for WIC texture loading later. + +> For details on the fullscreen management, see [this blog post](https://walbourn.github.io/care-and-feeding-of-modern-swapchains/). + +### DeviceResources — Direct3D 11 Device Wrapper + +The `DeviceResources` class encapsulates all Direct3D device and swap chain management: + +- **`IDXGIFactory2`** — Created via `CreateDXGIFactory1`. Used to enumerate adapters, create the swap chain, and check feature support (tearing, HDR, flip model). +- **`ID3D11Device1`** — Created via `D3D11CreateDevice` with a preferred hardware adapter (falls back to WARP in debug builds). Requests the highest feature level available (up to 11.1). +- **`ID3D11DeviceContext1`** — The immediate context for issuing draw calls and state changes. Obtained alongside the device. +- **`IDXGISwapChain1`** — Created via `IDXGIFactory2::CreateSwapChainForHwnd`. Uses `DXGI_SWAP_EFFECT_FLIP_DISCARD` for modern flip-model presentation when supported. +- **`ID3D11RenderTargetView`** — View into the swap chain's back buffer (`GetBuffer(0)` → `CreateRenderTargetView`). +- **`ID3D11Texture2D`** (depth stencil) — Created with `D3D11_BIND_DEPTH_STENCIL` for depth testing. +- **`ID3D11DepthStencilView`** — View into the depth buffer for the output-merger stage. +- **`ID3DUserDefinedAnnotation`** — For PIX/graphics debugger event markers. +- **Debug layer** — In debug builds, enables `D3D11_CREATE_DEVICE_DEBUG` and configures `ID3D11InfoQueue` to break on errors/corruption. + +> Since we are going to ultimately be rendering a 3D scene in the tutorial, we are using the default values for the DeviceResources ctor. If we were only rendering 2D, we would pass ``DXGI_FORMAT_UNKNOWN`` for the *depthBufferFormat* parameter. + +### Game Loop + +The template's game loop follows a fixed pattern: + +1. `Game::Tick()` → calls `Update` (game logic with a step timer) then `Render` +2. `Render` → clears render target/depth stencil, draws, calls `DeviceResources::Present` +3. `Present` → calls `IDXGISwapChain1::Present1` (with tearing flag if supported) +4. Device lost handling — if `Present` returns `DXGI_ERROR_DEVICE_REMOVED`, calls `HandleDeviceLost` which recreates all resources and notifies the `Game` via `IDeviceNotify` diff --git a/skills/directxtk-tutorial/reference/step2.md b/skills/directxtk-tutorial/reference/step2.md new file mode 100644 index 00000000..f0061c5e --- /dev/null +++ b/skills/directxtk-tutorial/reference/step2.md @@ -0,0 +1,128 @@ +# Step 2: Building the Project + +**Ask the user:** Would you like to build the project now? + +Detect the local system architecture to determine the appropriate platform target: + +```powershell +$arch = $env:PROCESSOR_ARCHITECTURE # AMD64 or ARM64 +``` + +## MSBuild + +For x64 systems: + +```powershell +msbuild .vcxproj /p:Configuration=Debug /p:Platform=x64 +``` + +For ARM64 systems: + +```powershell +msbuild .vcxproj /p:Configuration=Debug /p:Platform=ARM64 +``` + +> The first build will take longer as vcpkg downloads and builds the dependencies. + +## CMake + +For x64 systems: + +```powershell +cmake --preset=x64-Debug +cmake --build out\build\x64-Debug +``` + +For ARM64 systems: + +```powershell +cmake --preset=arm64-Debug +cmake --build out\build\arm64-Debug +``` + +> The first configure will take longer as vcpkg downloads and builds the dependencies. + +## Verifying the Build + +Once the build succeeds, the user should have a working executable that displays a cornflower blue window. Confirm the build completed without errors before proceeding to the next tutorial step. + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +The project template used in this tutorial uses VCPKG manifest mode to handle dependency management. The `vcpkg.json` file defines the libraries needed by the application, and the `vcpkg-configuration.json` provides a commit id for the vcpkg registry on [GitHub](https://github.com/microsoft/vcpkg) which controls the initial version of the dependencies. + +For this tutorial, we are relying on the default vcpkg integration offered in Visual Studio 2022 or later via `Microsoft.VisualStudio.Component.Vcpkg`. + +### MSBuild integration + +The vcpkg integration is handled directly in the `.vcxproj` project file: + +```xml + + true + +``` + +```xml + + x64-windows + +``` + +```xml + + + + $(VCInstallDir)vcpkg\scripts\buildsystems\msbuild\vcpkg-general.xml + +``` + +```xml + + x64-windows-static-md + + + arm64-windows-static-md + + + x64-windows-static-md + + + arm64-windows-static-md + +``` + +```xml + + +``` + +```xml + + + This project requires the VCPKG integration support in Visual Studio. Add the Microsoft.VisualStudio.Component.Vcpkg component to your install. + + + +``` + +> In more complex MSBuild solutions with multiple projects, the vcpkg integration is typically handled in a `Directory.Build.props` and `Directory.Build.targets` file. + +### CMake integration + +The `CMakePresets.json` sets `CMAKE_TOOLCHAIN_FILE` to vcpkg's toolchain discovered via the `VCPKG_ROOT` environment variable, which hooks into `find_package()` to locate installed packages. + +### Triplets + +The vcpkg **triplet** describes the architecture, configuration, and other properties of the build environment. + +| Triplet | Description | +| --------- | ------------- | +| `x64-windows` | x64 architecture, Windows, dynamic linking for Multithreaded DLL CRT | +| `arm64-windows` | ARM64 architecture, Windows, dynamic linking for Multithreaded DLL CRT | +| `x64-windows-static-md` | x64 architecture, Windows, static linking for Multi-threaded CRT | +| `arm64-windows-static-md` | ARM64 architecture, Windows, static linking for Multi-threaded CRT | + +There are two triplets active in a given build: the **host triplet** and the **target triplet**. The host triplet describes the machine on which the build is running, while the target triplet describes the machine for which the code is being built. diff --git a/skills/directxtk-tutorial/reference/step3.md b/skills/directxtk-tutorial/reference/step3.md new file mode 100644 index 00000000..b4d5cba6 --- /dev/null +++ b/skills/directxtk-tutorial/reference/step3.md @@ -0,0 +1,105 @@ +# Step 3: Adding DirectX Tool Kit + +Now add DirectX Tool Kit to the project via vcpkg. Edit the `vcpkg.json` manifest in the project root to add the `directxtk` port with GameInput support. + +Add the following entry to the `"dependencies"` array in `vcpkg.json`: + +```json +{ + "name": "directxtk", + "default-features": false, + "features": [ + "gameinput" + ] +} +``` + +For example, the full `vcpkg.json` should look something like: + +```json +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "dependencies": [ + "directxmath", + { + "name": "directxtk", + "default-features": false, + "features": [ + "gameinput" + ] + } + ] +} +``` + +## CMake Projects + +For CMake projects, also add the following to `CMakeLists.txt`: + +```cmake +find_package(directxtk CONFIG REQUIRED) +find_package(gameinput CONFIG REQUIRED) +target_link_libraries(${PROJECT_NAME} PRIVATE Microsoft::DirectXTK) +``` + +## Build and Verify + +Build the project to verify everything works. Use the same commands from [Step 2](step2.md). + +### MSBuild + +For x64 systems: + +```powershell +msbuild .vcxproj /p:Configuration=Debug /p:Platform=x64 +``` + +For ARM64 systems: + +```powershell +msbuild .vcxproj /p:Configuration=Debug /p:Platform=ARM64 +``` + +### CMake + +For x64 systems: + +```powershell +cmake --preset=x64-Debug +cmake --build out\build\x64-Debug +``` + +For ARM64 systems: + +```powershell +cmake --preset=arm64-Debug +cmake --build out\build\arm64-Debug +``` + +> The first rebuild will take longer as vcpkg fetches and builds DirectXTK and its dependencies (including GameInput). + +## Verifying the Integration + +Once the build succeeds, verify that the DirectXTK headers are available by adding a test include to `pch.h`: + +```cpp +#include +``` + +> **Important:** Use `` include style (not `"SpriteBatch.h"`) for proper MSBuild+vcpkg integration. + +If the build still succeeds, DirectXTK is properly integrated. + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +- **Static linking** — The MSBuild template uses `-static-md` vcpkg triplets, so the DirectXTK library is statically linked. For CMake, the `DIRECTX_TOOLKIT_IMPORT` define is handled automatically by the CMake targets when using DLL triplets. + +- **Header location** — The DirectXTK headers are installed in the `include/directxtk` directory of the `vcpkg_installed` folder for the given host/target triplet combination. The VCPKG+MSBuild integration only adds the root 'include' folder to the search paths for the build, so we have to specify the subdirectory explicitly. For CMake, the CMake targets automatically handle the specific header location, but with the use of the directxmath vcpkg port it also has the root folder in the search paths. + +- **GameInput** — A modern input API that provides a unified interface for gamepads, keyboards, and mice. It replaces the older XInput and raw input APIs. The vcpkg `gameinput` feature links the GameInput redistributable library. + +> **Important:** You may need to run GameInputRedist.msi which is installed into a tools folder in `vcpkg_installed` as part of the build process. + +- **vcpkg features** — The `"default-features": false` disables the default XInput backend so that only GameInput is used for input handling. This avoids linking both input systems. It also disables DirectX Tool Kit for Audio which we can add back later. diff --git a/skills/directxtk-tutorial/reference/step4.md b/skills/directxtk-tutorial/reference/step4.md new file mode 100644 index 00000000..aa36288f --- /dev/null +++ b/skills/directxtk-tutorial/reference/step4.md @@ -0,0 +1,197 @@ +# Step 4: Sprites and Textures + +This step adds 2D sprite rendering using `SpriteBatch` and loads a texture with `WICTextureLoader`. See the wiki page: [Sprites and textures](https://github.com/microsoft/DirectXTK/wiki/Sprites-and-textures). + +## Setup + +Copy the `cat.png` file from this skill's `assets/` folder into the project's working directory (next to the executable, or in the project root for CMake builds): + +```powershell +Copy-Item "\assets\cat.png" -Destination "" +``` + +## Code Changes + +### pch.h + +Ensure the following includes are in `pch.h`: + +```cpp +#include +#include +#include +#include +``` + +### Game.h + +Add the following private member variables to the `Game` class: + +```cpp +std::unique_ptr m_states; +std::unique_ptr m_spriteBatch; +Microsoft::WRL::ComPtr m_texture; +DirectX::SimpleMath::Vector2 m_screenPos; +DirectX::SimpleMath::Vector2 m_origin; +``` + +### Game.cpp — CreateDeviceDependentResources + +In `CreateDeviceDependentResources`, create the `SpriteBatch`, load the texture, and compute its origin: + +```cpp +auto context = m_deviceResources->GetD3DDeviceContext(); +m_spriteBatch = std::make_unique(context); + +auto device = m_deviceResources->GetD3DDevice(); +m_states = std::make_unique(device); + +ComPtr resource; +DX::ThrowIfFailed( + DirectX::CreateWICTextureFromFile(device, L"cat.png", + resource.GetAddressOf(), + m_texture.ReleaseAndGetAddressOf())); + +ComPtr cat; +DX::ThrowIfFailed(resource.As(&cat)); + +CD3D11_TEXTURE2D_DESC catDesc; +cat->GetDesc(&catDesc); + +m_origin.x = float(catDesc.Width / 2); +m_origin.y = float(catDesc.Height / 2); +``` + +### Game.cpp — CreateWindowSizeDependentResources + +In `CreateWindowSizeDependentResources`, compute the screen center position: + +```cpp +auto size = m_deviceResources->GetOutputSize(); +m_screenPos.x = float(size.right) / 2.f; +m_screenPos.y = float(size.bottom) / 2.f; +``` + +### Game.cpp — Render + +In the `Render` method, after clearing the render target and before `Present`, draw the sprite: + +```cpp +m_spriteBatch->Begin(DirectX::SpriteSortMode_Deferred, m_states->NonPremultiplied()); + +m_spriteBatch->Draw(m_texture.Get(), m_screenPos, nullptr, + DirectX::Colors::White, 0.f, m_origin); + +m_spriteBatch->End(); +``` + +### Game.cpp — OnDeviceLost + +In `OnDeviceLost`, release the resources: + +```cpp +m_states.reset(); +m_spriteBatch.reset(); +m_texture.Reset(); +``` + +## Build and Verify + +Build the project using the commands from [Step 2](step2.md). To run the application, make sure the working directory is set to the project folder (where `cat.png` is located): + +```powershell +cd +``` + +For MSBuild, the executable will be in a subdirectory like `x64\Debug\.exe`. For CMake, it will be in `out\build\x64-Debug\.exe` (or the ARM64 equivalent). + +When you run the application, you should see the cat image rendered in the center of the window on top of the cornflower blue background. + +## Further Reading + +For more things you can do with sprites at this point: + +- [Sprites and textures](https://github.com/microsoft/DirectXTK/wiki/Sprites-and-textures) + - Using DDS files for textures + - Using pre-multiplied alpha + - Rotating a sprite + - Scaling a sprite + - Tinting a sprite + - Tiling a sprite + - Stretching a sprite + - Drawing a background image +- [More tricks with sprites](https://github.com/microsoft/DirectXTK/wiki/More-tricks-with-sprites) + - Animating sprites + - Creating a scrolling background + - More to explore + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +### SpriteBatch + +`SpriteBatch` is a high-performance batched 2D renderer. Under the hood it creates and manages: + +- **`ID3D11VertexShader`** and **`ID3D11PixelShader`** — Built-in HLSL shaders for textured quad rendering (compiled and embedded at build time). +- **`ID3D11InputLayout`** — Describes the per-vertex data layout (position, color, texture coordinates). +- **`ID3D11Buffer`** (dynamic vertex buffer) — Holds batched sprite quads. Uses `Map`/`Unmap` with `D3D11_MAP_WRITE_DISCARD` or `D3D11_MAP_WRITE_NO_OVERWRITE` for efficient streaming. +- **`ID3D11Buffer`** (index buffer) — Pre-generated indices for drawing quads as triangle lists. +- **`ID3D11Buffer`** (constant buffer) — Contains the orthographic projection matrix for screen-space rendering. + +When you call `Begin()`/`End()`, SpriteBatch sets the full pipeline state: blend state (`OMSetBlendState`), depth/stencil state (`OMSetDepthStencilState`), rasterizer state (`RSSetState`), sampler (`PSSetSamplers`), shaders, input layout, and buffers. It then issues `DrawIndexed` calls, batching sprites that share the same texture into a single draw call. + +### CommonStates + +`CommonStates` is a lazy cache of reusable fixed-function pipeline state objects: + +- **`ID3D11BlendState`** — `Opaque`, `AlphaBlend`, `Additive`, `NonPremultiplied`. The `NonPremultiplied` state used here applies standard alpha blending for textures with straight (non-premultiplied) alpha. +- **`ID3D11DepthStencilState`** — `DepthNone`, `DepthDefault`, `DepthRead`, etc. +- **`ID3D11RasterizerState`** — `CullNone`, `CullClockwise`, `CullCounterClockwise`, `Wireframe`. +- **`ID3D11SamplerState`** — `PointWrap`, `PointClamp`, `LinearWrap`, `LinearClamp`, `AnisotropicWrap`, `AnisotropicClamp`. + +Each state object is created on first access via `ID3D11Device::CreateBlendState` (or the corresponding `Create*State` method) and cached for reuse. + +### WICTextureLoader + +`CreateWICTextureFromFile` loads an image file using the Windows Imaging Component (WIC) and creates D3D11 resources: + +- Uses **Windows Imaging Component (WIC)** (`IWICImagingFactory`, `IWICBitmapFrameDecode`, `IWICFormatConverter`) to decode the image file and convert pixel formats. +- Creates an **`ID3D11Texture2D`** with `D3D11_USAGE_IMMUTABLE` (or `DEFAULT` if mipmaps are requested) via `ID3D11Device::CreateTexture2D`. +- Creates an **`ID3D11ShaderResourceView`** so the texture can be bound to pixel shader slots for sampling. +- For auto-generated mipmaps, uses `ID3D11DeviceContext::GenerateMips` after uploading the base level with `UpdateSubresource`. + +### Shaders + +The SpriteBatch shaders are built-in HLSL shader 'blobs'. They are compiled at build time using the `CompileShader` batch file, and then included as binary data into the C++ library directly. + +The shaders in this case are fairly trivial: + +***Vertex Shader*** + +```hlsl +cbuffer Parameters : register(b0) +{ + row_major float4x4 MatrixTransform; +}; + + +void SpriteVertexShader(inout float4 color : COLOR0, + inout float2 texCoord : TEXCOORD0, + inout float4 position : SV_Position) +{ + position = mul(position, MatrixTransform); +} +``` + +***Pixel Shader*** + +```hlsl +Texture2D Texture : register(t0); +SamplerState Sampler : register(s0); + +float4 SpritePixelShader(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : SV_Target +{ + return Texture.Sample(Sampler, texCoord) * color; +} +``` diff --git a/skills/directxtk-tutorial/reference/step5.md b/skills/directxtk-tutorial/reference/step5.md new file mode 100644 index 00000000..8b2e3b18 --- /dev/null +++ b/skills/directxtk-tutorial/reference/step5.md @@ -0,0 +1,100 @@ +# Step 5: Drawing Text + +This step adds text rendering using `SpriteFont` and `SpriteBatch`. See the wiki page: [Drawing text](https://github.com/microsoft/DirectXTK/wiki/Drawing-text). + +## Setup + +Copy the `courier.spritefont` file from this skill's `assets/` folder into the project's working directory: + +```powershell +Copy-Item "\assets\courier.spritefont" -Destination "" +``` + +> For details on how the sprite font is created, see the [MakeSpriteFont](https://github.com/microsoft/DirectXTK/wiki/MakeSpriteFont) wiki page. + +## Code Changes + +### pch.h + +Add the following include to `pch.h` (after the existing DirectXTK includes): + +```cpp +#include +``` + +### Game.h + +Add the following private member variable to the `Game` class: + +```cpp +std::unique_ptr m_font; +``` + +### Game.cpp — CreateDeviceDependentResources + +In `CreateDeviceDependentResources`, load the sprite font: + +```cpp +m_font = std::make_unique(device, L"courier.spritefont"); +``` + +### Game.cpp — Render + +In the `Render` method, inside the existing `SpriteBatch` Begin/End block (after the sprite draw), add text rendering: + +```cpp +m_spriteBatch->Begin(DirectX::SpriteSortMode_Deferred, m_states->NonPremultiplied()); + +m_spriteBatch->Draw(m_texture.Get(), m_screenPos, nullptr, + DirectX::Colors::White, 0.f, m_origin); + +m_font->DrawString(m_spriteBatch.get(), L"Hello, World!", + DirectX::XMFLOAT2(10.f, 10.f), DirectX::Colors::Yellow); + +m_spriteBatch->End(); +``` + +### Game.cpp — OnDeviceLost + +In `OnDeviceLost`, release the font: + +```cpp +m_font.reset(); +``` + +## Build and Verify + +Build the project using the commands from [Step 2](step2.md). Run the application from the project folder (where `courier.spritefont` is located). + +You should see "Hello, World!" rendered in yellow text in the top-left corner of the window, with the cat sprite still centered. + +## Further Reading + +- [Drawing text](https://github.com/microsoft/DirectXTK/wiki/Drawing-text) + - Creating a font + - Using std::wstring for text + - Using ASCII text + - Drop-shadow effect + - Outline effect + - More to explore + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +### SpriteFont + +`SpriteFont` is a text rendering class that works in conjunction with `SpriteBatch`. It manages: + +- **Font atlas** — A single **`ID3D11Texture2D`** (with `D3D11_USAGE_IMMUTABLE`) containing all pre-rendered glyphs packed into a texture atlas, plus an **`ID3D11ShaderResourceView`** for shader access. +- **Glyph data** — A sorted array of `Glyph` structs (loaded from the `.spritefont` binary format) containing character code, source rectangle in the atlas, and advance/offset metrics. + +**Text rendering pipeline:** + +1. `DrawString` iterates the input text character by character via an internal `ForEachGlyph` helper. +2. For each character, it performs a binary search to find the corresponding `Glyph` (falling back to a default character if not found). +3. It computes the destination position using the glyph offset, advance width, and any rotation/scale/origin transforms. +4. It calls `SpriteBatch::Draw` for each glyph, passing the font atlas SRV and the glyph's source rectangle. +5. `SpriteBatch` batches all glyph quads together (since they share the same atlas texture) and renders them in a single `DrawIndexed` call. + +The `.spritefont` binary format is produced by the **MakeSpriteFont** tool, which rasterizes a TrueType/OpenType font at a specific size and packs the glyphs into an atlas. diff --git a/skills/directxtk-tutorial/reference/step6.md b/skills/directxtk-tutorial/reference/step6.md new file mode 100644 index 00000000..719b69c2 --- /dev/null +++ b/skills/directxtk-tutorial/reference/step6.md @@ -0,0 +1,229 @@ +# Step 6: Simple Rendering + +This step introduces rendering custom geometry using `BasicEffect`, `PrimitiveBatch`, and `VertexPositionColor`. We draw a triangle with per-vertex colors (red, green, blue) that blend smoothly across the surface. See the wiki page: [Simple rendering](https://github.com/microsoft/DirectXTK/wiki/Simple-rendering). + +## Background + +To draw geometry with Direct3D 11, you need: + +- A **vertex buffer** containing the vertices to draw +- An **input layout** describing the memory layout of each vertex +- A **primitive topology** indicating how vertices form shapes (points, lines, triangles) +- A compiled **vertex shader** and **pixel shader** +- **State objects** for rasterizer, depth/stencil, and blend state + +DirectX Tool Kit simplifies this: + +| Requirement | DirectXTK Class | +| ------------- | ---------------- | +| Vertex buffer + topology | `PrimitiveBatch` | +| Input layout + shaders | `BasicEffect` + `CreateInputLayoutFromEffect` | +| State objects | `CommonStates` | +| Vertex format | `VertexPositionColor` | + +## Code Changes + +### Game.cpp — Render (comment out sprite drawing keeping the text) + +First, comment out or remove the sprite drawing code from Steps 4 in the `Render` method, since the triangle will cover the sprite: + +```cpp +// m_spriteBatch->Draw(m_texture.Get(), m_screenPos, nullptr, +// DirectX::Colors::White, 0.f, m_origin); +``` + +### pch.h + +Ensure the following includes are in `pch.h`: + +```cpp +#include +#include +#include +#include +#include +#include +``` + +### Game.h + +Add the following private member variables to the `Game` class: + +```cpp +using VertexType = DirectX::VertexPositionColor; + +std::unique_ptr m_effect; +std::unique_ptr> m_batch; +Microsoft::WRL::ComPtr m_inputLayout; +``` + +Add this as well if not already present: + +```cpp +std::unique_ptr m_states; +``` + +### Game.cpp — CreateDeviceDependentResources + +In `CreateDeviceDependentResources`, create the effect, input layout, and primitive batch: + +These both should be in the function already, but if it is missing add it: + +```cpp +auto device = m_deviceResources->GetD3DDevice(); +auto context = m_deviceResources->GetD3DDeviceContext(); +``` + +If CommonStates is not already created, create it: + +```cpp +m_states = std::make_unique(device); +``` + +Then add the effect, input layout, and primitive batch: + +```cpp +m_effect = std::make_unique(device); +m_effect->SetVertexColorEnabled(true); + +DX::ThrowIfFailed( + DirectX::CreateInputLayoutFromEffect(device, m_effect.get(), + m_inputLayout.ReleaseAndGetAddressOf()) +); + +m_batch = std::make_unique>(context); +``` + +> **Important:** Call `SetVertexColorEnabled(true)` *before* creating the input layout. This ensures `BasicEffect` selects the correct shader permutation that includes the `COLOR` vertex element. + +### Game.cpp — CreateWindowSizeDependentResources + +In `CreateWindowSizeDependentResources`, set up a projection matrix so we can use pixel coordinates (matching the SpriteBatch coordinate system): + +```cpp +auto size = m_deviceResources->GetOutputSize(); + +DirectX::SimpleMath::Matrix proj = DirectX::SimpleMath::Matrix::CreateOrthographicOffCenter( + 0.f, float(size.right), float(size.bottom), 0.f, 0.f, 1.f); +m_effect->SetProjection(proj); +``` + +### Game.cpp — Render + +In the `Render` method, after clearing the render target and before `Present`, draw the triangle: + +```cpp +context->OMSetBlendState(m_states->Opaque(), nullptr, 0xFFFFFFFF); +context->OMSetDepthStencilState(m_states->DepthNone(), 0); +context->RSSetState(m_states->CullNone()); + +m_effect->Apply(context); + +context->IASetInputLayout(m_inputLayout.Get()); + +m_batch->Begin(); + +VertexPositionColor v1(DirectX::SimpleMath::Vector3(400.f, 150.f, 0.f), DirectX::Colors::Red); +VertexPositionColor v2(DirectX::SimpleMath::Vector3(600.f, 450.f, 0.f), DirectX::Colors::Green); +VertexPositionColor v3(DirectX::SimpleMath::Vector3(200.f, 450.f, 0.f), DirectX::Colors::Blue); + +m_batch->DrawTriangle(v1, v2, v3); + +m_batch->End(); +``` + +### Game.cpp — OnDeviceLost + +In `OnDeviceLost`, release the resources: + +If `m_states` is not already in the function, reset it: + +```cpp +m_states.reset(); +``` + +Then add the reset for our new member variables: + +```cpp +m_effect.reset(); +m_batch.reset(); +m_inputLayout.Reset(); +``` + +## Build and Verify + +Build the project using the commands from [Step 2](step2.md). When you run the application, you should see a triangle with smoothly interpolated red, green, and blue colors — the classic "rainbow triangle" — rendered on the cornflower blue background. + +The per-vertex colors are interpolated by the GPU rasterizer across the triangle surface, producing a smooth gradient between the three corner colors. + +## Coordinate Systems + +The code above uses **pixel coordinates** (origin at top-left, y-axis pointing down) thanks to the orthographic projection matrix. The triangle vertices are specified in screen pixels, matching the coordinate system used by `SpriteBatch`. + +Without the projection matrix, `BasicEffect` uses **normalized device coordinates** (-1 to +1 in both axes, origin at center). You can use either approach depending on your needs. + +## More to explore + +- [Simple rendering](https://github.com/microsoft/DirectXTK/wiki/Simple-rendering) + - Drawing with normalized coordinates + - State objects and backface culling + - Drawing with textures + - Drawing with lighting and normal maps +- [Line drawing and anti-aliasing](https://github.com/microsoft/DirectXTK/wiki/Line-drawing-and-anti-aliasing) + - Drawing a grid + - Anti-aliasing + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +### BasicEffect + +`BasicEffect` is a versatile shader class that supports multiple rendering modes. Under the hood it manages: + +- **Multiple shader permutations** — Pre-compiled vertex and pixel shader blobs embedded in the library. The active permutation depends on which features are enabled (vertex color, texture, lighting, fog). +- **`ID3D11Buffer`** (constant buffer) — Contains the world/view/projection matrices, material colors, and light parameters. Updated via `Map`/`Unmap` when `Apply()` is called. +- **Shader selection** — `GetVertexShaderBytecode` returns the bytecode for the currently selected permutation, which is why you must configure the effect (e.g., `SetVertexColorEnabled`) before creating the input layout. + +When `SetVertexColorEnabled(true)` is set, the vertex shader passes through the per-vertex `COLOR` attribute, and the pixel shader multiplies the interpolated vertex color with the material's diffuse color. + +### PrimitiveBatch + +`PrimitiveBatch` is a lightweight immediate-mode geometry renderer, similar to the old D3D9 `DrawPrimitiveUP` API: + +- **`ID3D11Buffer`** (dynamic vertex buffer) — Created with `D3D11_USAGE_DYNAMIC` and `D3D11_CPU_ACCESS_WRITE`. Uses `Map`/`Unmap` with `D3D11_MAP_WRITE_DISCARD` or `D3D11_MAP_WRITE_NO_OVERWRITE` for efficient CPU-to-GPU streaming. +- **`ID3D11Buffer`** (dynamic index buffer) — Used when drawing indexed primitives (e.g., `DrawQuad`, `DrawIndexed`). +- **No shader management** — Unlike `SpriteBatch`, `PrimitiveBatch` does not set shaders, input layout, or state. You must set these yourself (typically via an `IEffect` and `CommonStates`). +- **Topology** — Each draw call specifies the primitive topology. `DrawTriangle` uses `D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST`, `DrawLine` uses `LINELIST`. + +### Input Layout + +The `ID3D11InputLayout` object is the bridge between vertex buffer data and the vertex shader: + +- Created via `ID3D11Device::CreateInputLayout`, which takes the vertex element descriptions (from `VertexPositionColor::InputElements`) and the compiled vertex shader bytecode (from `BasicEffect::GetVertexShaderBytecode`). +- `CreateInputLayoutFromEffect` is a helper template that combines `T::InputElements` with the effect's shader bytecode in a single call. +- `VertexPositionColor` declares two elements: `POSITION` (XMFLOAT3) and `COLOR` (XMFLOAT4). + +### The Rendering Pipeline + +When you call the render code above, here's what happens at the D3D11 level: + +1. `OMSetBlendState` / `OMSetDepthStencilState` / `RSSetState` — Configure the fixed-function output-merger and rasterizer stages. +2. `m_effect->Apply(context)` — Binds the vertex shader, pixel shader, and updates the constant buffer with the current matrices/colors. +3. `IASetInputLayout` — Tells the input assembler how to read vertex data. +4. `m_batch->Begin()` — Prepares the dynamic vertex buffer for writing. +5. `DrawTriangle` — Maps the vertex buffer, copies 3 vertices, sets the primitive topology to `TRIANGLELIST`, and issues a `Draw(3, ...)` call. +6. `m_batch->End()` — Flushes any remaining batched geometry. + +### Shaders + +The BasicEffect shaders are built-in HLSL shader 'blobs'. They are compiled at build time using the `CompileShader` batch file, and then included as binary data into the C++ library directly. They are built in many combinations to support different rendering options: + +- Rendering without textures +- Render with per-vertex colors +- Rendering with textures +- Rendering with 1 light +- Rendering with 3 lights +- Rendering with per-pixel lighting +- Rendering with fog +- Various combinations of these features diff --git a/skills/directxtk-tutorial/reference/step7.md b/skills/directxtk-tutorial/reference/step7.md new file mode 100644 index 00000000..e1475ee6 --- /dev/null +++ b/skills/directxtk-tutorial/reference/step7.md @@ -0,0 +1,183 @@ +# Step 7: 3D Shapes + +This step introduces rendering 3D geometry using `GeometricPrimitive`. We create and render the classic Utah teapot with default lighting and a simple rotation animation. See the wiki page: [3D shapes](https://github.com/microsoft/DirectXTK/wiki/3D-shapes). + +## Background + +In the previous step, we used `PrimitiveBatch` to draw geometry with manually specified vertices. `GeometricPrimitive` takes a different approach — it procedurally generates common 3D shapes (sphere, cube, torus, teapot, etc.) and stores them in efficient **static** vertex and index buffers on the GPU. + +Key differences from `PrimitiveBatch`: + +| | PrimitiveBatch | GeometricPrimitive | +| --- | --- | --- | +| Buffer type | Dynamic (CPU-writable each frame) | Static (GPU-only, created once) | +| Index buffer | Optional | Always used | +| Shader setup | Manual (you set effect + input layout) | Built-in default or custom effect | +| Use case | Immediate-mode debug/simple drawing | Efficient 3D shape rendering | + +## Code Changes + +### Game.cpp — Render (comment out previous step) + +Comment out or remove the triangle rendering code from Step 6: + +```cpp +// context->OMSetBlendState(m_states->Opaque(), nullptr, 0xFFFFFFFF); +// context->OMSetDepthStencilState(m_states->DepthNone(), 0); +// context->RSSetState(m_states->CullNone()); +// m_effect->Apply(context); +// context->IASetInputLayout(m_inputLayout.Get()); +// m_batch->Begin(); +// ... +// m_batch->End(); +``` + +### pch.h + +Ensure the following includes are in `pch.h`: + +```cpp +#include +#include +``` + +### Game.h + +Add the following private member variables to the `Game` class: + +```cpp +DirectX::SimpleMath::Matrix m_world; +DirectX::SimpleMath::Matrix m_view; +DirectX::SimpleMath::Matrix m_proj; + +std::unique_ptr m_shape; +``` + +### Game.cpp — CreateDeviceDependentResources + +In `CreateDeviceDependentResources`, create the teapot shape: + +```cpp +auto context = m_deviceResources->GetD3DDeviceContext(); +m_shape = DirectX::GeometricPrimitive::CreateTeapot(context); + +m_world = DirectX::SimpleMath::Matrix::Identity; +``` + +### Game.cpp — CreateWindowSizeDependentResources + +In `CreateWindowSizeDependentResources`, set up a 3D camera with a perspective projection: + +```cpp +auto size = m_deviceResources->GetOutputSize(); + +m_view = DirectX::SimpleMath::Matrix::CreateLookAt( + DirectX::SimpleMath::Vector3(2.f, 2.f, 2.f), + DirectX::SimpleMath::Vector3::Zero, + DirectX::SimpleMath::Vector3::UnitY); + +m_proj = DirectX::SimpleMath::Matrix::CreatePerspectiveFieldOfView( + DirectX::XM_PI / 4.f, + float(size.right) / float(size.bottom), + 0.1f, 10.f); +``` + +### Game.cpp — Update + +In `Update`, rotate the teapot over time: + +```cpp +auto time = static_cast(timer.GetTotalSeconds()); + +m_world = DirectX::SimpleMath::Matrix::CreateRotationZ(cosf(time) * 2.f); +``` + +### Game.cpp — Render + +In the `Render` method, after clearing the render target and before `Present`, draw the teapot: + +```cpp +m_shape->Draw(m_world, m_view, m_proj); +``` + +> That's it! `GeometricPrimitive::Draw` handles setting up a default `BasicEffect` with lighting, the input layout, render states, and issuing the indexed draw call — all in one line. + +### Game.cpp — OnDeviceLost + +In `OnDeviceLost`, release the shape: + +```cpp +m_shape.reset(); +``` + +## Build and Verify + +Build the project using the commands from [Step 2](step2.md). When you run the application, you should see a white, lit Utah teapot rotating on the cornflower blue background. + +The teapot is rendered with default lighting (three directional lights) and backface culling, giving it a solid 3D appearance. + +## Available Shapes + +`GeometricPrimitive` can create many shapes. Replace `CreateTeapot` with any of these: + +| Factory Method | Shape | +| --- | --- | +| `CreateSphere` | UV sphere | +| `CreateGeoSphere` | Geodesic sphere | +| `CreateCube` | Unit cube | +| `CreateBox` | Axis-aligned box with custom dimensions | +| `CreateCylinder` | Cylinder | +| `CreateCone` | Cone | +| `CreateTorus` | Torus (donut) | +| `CreateTetrahedron` | Tetrahedron (4 faces) | +| `CreateOctahedron` | Octahedron (8 faces) | +| `CreateDodecahedron` | Dodecahedron (12 faces) | +| `CreateIcosahedron` | Icosahedron (20 faces) | +| `CreateTeapot` | Utah teapot | + +## Next Steps + +See [Next Steps](nextsteps.md) for where to go from here. + +## Further Reading + +- [3D shapes](https://github.com/microsoft/DirectXTK/wiki/3D-shapes) + - Adding textures to shapes + - Using custom lighting and effects + - Custom vertex formats + - Custom geometry +- [Rendering a model](https://github.com/microsoft/DirectXTK/wiki/Rendering-a-model) + +## Technical Notes + +**Ask the user:** Would you like to see the Technical Notes for this step, or skip to the next step? + +### GeometricPrimitive + +`GeometricPrimitive` procedurally generates indexed triangle meshes and stores them in GPU buffers: + +- **`ID3D11Buffer`** (static vertex buffer) — Created with `D3D11_USAGE_IMMUTABLE` containing `VertexPositionNormalTexture` data (position, normal, and texture coordinates). Because it's immutable, it resides entirely in fast GPU memory. +- **`ID3D11Buffer`** (static index buffer) — Created with `D3D11_USAGE_IMMUTABLE` containing `uint16_t` indices. Indexed rendering reduces vertex count by sharing vertices between adjacent triangles. +- **Internal `BasicEffect`** — When using the simple `Draw(world, view, proj)` overload, `GeometricPrimitive` creates and manages its own `BasicEffect` with default lighting enabled. It also creates its own `ID3D11InputLayout` matching `VertexPositionNormalTexture`. + +### The 3D Camera + +This step introduces a proper 3D camera setup: + +- **View matrix** (`CreateLookAt`) — Defines where the camera is (eye position), what it's looking at (focus point), and which direction is "up". This transforms world-space coordinates into camera-space (view-space). +- **Projection matrix** (`CreatePerspectiveFieldOfView`) — Defines the camera's field of view, aspect ratio, and near/far clipping planes. This transforms view-space into clip-space, applying perspective foreshortening so distant objects appear smaller. + +Together, these matrices transform the teapot's local vertex positions through: **World → View → Projection → Clip Space** → (GPU viewport transform) → **Screen pixels**. + +### Static vs. Dynamic Buffers + +In Step 6, `PrimitiveBatch` used `D3D11_USAGE_DYNAMIC` buffers that the CPU writes to every frame. In this step, `GeometricPrimitive` uses `D3D11_USAGE_IMMUTABLE` buffers: + +- **Dynamic**: CPU writes vertex data each frame via `Map`/`Unmap`. Good for geometry that changes per-frame (debug lines, UI). +- **Immutable**: Created once with initial data, never modified. The GPU can optimize storage and access patterns. Much faster for fixed geometry. + +The transformation (rotation) is applied via the world matrix in the constant buffer — the vertex data itself never changes. + +### The Utah Teapot + +The [Utah teapot](https://en.wikipedia.org/wiki/Utah_teapot) is a classic test model in computer graphics, originally created by Martin Newell in 1975. DirectX Tool Kit generates it from Bézier patch data, tessellated to the specified level (default: 8). diff --git a/skills/directxtk-tutorial/reference/tutorial-steps.md b/skills/directxtk-tutorial/reference/tutorial-steps.md new file mode 100644 index 00000000..968f5eef --- /dev/null +++ b/skills/directxtk-tutorial/reference/tutorial-steps.md @@ -0,0 +1,18 @@ +# Tutorial Steps + +This document outlines the sequence of lessons in the DirectX Tool Kit Getting Started tutorial. + +Each lesson is documented on the [DirectXTK wiki](https://github.com/microsoft/DirectXTK/wiki/Getting-Started). + +## Lesson Sequence + +| # | Lesson | Wiki Page | Summary | +| --- | -------- | ----------- | --------- | +| 0 | Prerequisites | [Getting Started](https://github.com/microsoft/DirectXTK/wiki/Getting-Started) | Verify required tools: Visual Studio, Windows SDK, vcpkg, and Git | +| 1 | Project Setup | [Getting Started](https://github.com/microsoft/DirectXTK/wiki/Getting-Started) | Create a new Direct3D 11 project using the d3d11game_vcpkg template | +| 2 | Building the project | | Build the project and resolve any dependencies | +| 3 | Adding DirectXTK | [Adding the DirectX Tool Kit](https://github.com/microsoft/DirectXTK/wiki/Adding-the-DirectX-Tool-Kit) | Integrate DirectXTK into the project via vcpkg | +| 4 | Sprites and Textures | [Sprites and textures](https://github.com/microsoft/DirectXTK/wiki/Sprites-and-textures) | Render 2D sprites using SpriteBatch | +| 5 | Drawing Text | [Drawing text](https://github.com/microsoft/DirectXTK/wiki/Drawing-text) | Render text using SpriteFont | +| 6 | Simple Rendering | [Simple rendering](https://github.com/microsoft/DirectXTK/wiki/Simple-rendering) | Draw simple triangle primitives | +| 7 | 3D Shapes | [3D shapes](https://github.com/microsoft/DirectXTK/wiki/3D-shapes) | Use GeometricPrimitive for standard 3D shapes | diff --git a/skills/directxtk-usage/SKILL.md b/skills/directxtk-usage/SKILL.md new file mode 100644 index 00000000..2fdf4fe8 --- /dev/null +++ b/skills/directxtk-usage/SKILL.md @@ -0,0 +1,251 @@ +--- +name: directxtk-usage +description: >- + Guide for integrating DirectX Tool Kit for DirectX 11 into new projects and understanding the API surface. + Use this skill when asked about how to use DirectX Tool Kit, integrate it into a project, + or get an overview of its classes and functionality. +license: MIT +metadata: + author: chuckw + version: "1.0" +--- + +# DirectX Tool Kit for DirectX 11 — Usage Guide + +## Overview + +The *DirectX Tool Kit* (aka DirectXTK) is a collection of helper classes for writing DirectX 11.x code in C++. It is designed to be used as a shared source project, NuGet package, or vcpkg port integrated into your game or graphics application. + +- **Repository**: +- **Documentation**: +- **NuGet Packages**: `directxtk_desktop_win10`, `directxtk_uwp` +- **vcpkg Port**: `directxtk` + +## Integration Methods + +### vcpkg manifest-mode (Recommended) + +In your `vcpkg.json` file, add the following: + +```json +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "dependencies": [ + "directxmath", + "directxtk" + ] +} +``` + +If using GameInput for the game input functionality, add the following: + +```json +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "dependencies": [ + "directxmath", + { + "name": "directxtk", + "default-features": false, + "features": [ + "gameinput" + ] + } + ] +} +``` + +If using DirectX Tool Kit for Audio and GameInput, add the following: + +```json +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "dependencies": [ + "directxmath", + { + "name": "directxtk", + "default-features": false, + "features": [ + "gameinput", + "xaudio2-9" + ] + } + ] +} +``` + +### vcpkg (classic) + +```bash +vcpkg install directxtk +``` + +Features: `xaudio2-9` (DirectX Tool Kit for Audio using XAudio 2.9), `gameinput` (Using GameInput for gamepad, keyboard, and mouse), `tools` (command-line tools). Triplets: `x64-windows`, `arm64-windows`, etc. + +For DLL usage (`x64-windows` default triplet), define `DIRECTX_TOOLKIT_IMPORT` in your consuming project. For static library usage, use `-static-md` triplet variants. + +CMakeLists.txt: + +```cmake +find_package(directxtk CONFIG REQUIRED) +target_link_libraries(your_target PRIVATE Microsoft::DirectXTK) +``` + +See the [d3d11game_vcpkg](https://github.com/walbourn/directx-vs-templates/tree/main/d3d11game_vcpkg) template for a complete example. + +### NuGet + +Use `directxtk_desktop_win10` for Win32 desktop applications or `directxtk_uwp` for UWP apps. + +### Project Reference + +Add the appropriate `.vcxproj` from the `DirectXTK/` folder to your solution and add a project reference. Add the `DirectXTK\Inc` directory to your Additional Include Directories. + +## Minimum Setup + +Every DirectXTK application needs: + +1. A Direct3D 11 device +2. A Direct3D immediate device context +3. The application is responsible for the rendering, SwapChain management, and Present loop + +## API Reference + +The public API is defined in the header files in the `Inc/` directory. See the [reference overview](reference/overview.md) for a categorized summary of all classes and helpers. + +Full documentation for each class is available on the [GitHub wiki](https://github.com/microsoft/DirectXTK/wiki). + +API signatures are defined in the public headers under the `Inc/` directory. Always consult those headers for the authoritative function signatures, parameters, and SAL annotations. + +## Key Concepts + +### Resource Ownership + +DirectXTK classes follow RAII principles. Most objects are created with `std::make_unique` and destroyed automatically. COM resources are managed with `Microsoft::WRL::ComPtr`. + +### Device-Dependent vs Device-Independent + +Most DirectXTK objects are **device-dependent** — they are created with a `ID3D11Device*` and must be recreated if the device is lost. Plan your resource management accordingly. + +### Thread Safety + +DirectXTK rendering classes (SpriteBatch, Effects, PrimitiveBatch, etc.) are **not** thread-safe. Use one instance per thread, or synchronize access externally. Resource creation (texture loading, model loading) can be done from any thread. + +## Namespace + +All classes and functions reside in the `DirectX` namespace. Headers that contain Direct3D 11-specific types use `inline namespace DX11` to avoid conflicts when both DX11 and DX12 toolkits are linked together. + +```cpp +#include "SpriteBatch.h" + +// Usage: +auto spriteBatch = std::make_unique(context); +``` + +## Common Patterns + +### Drawing Sprites + +```cpp +#include "SpriteBatch.h" +#include "WICTextureLoader.h" + +// Create +auto spriteBatch = std::make_unique(context); +ComPtr texture; +DirectX::CreateWICTextureFromFile(device, L"cat.png", nullptr, texture.GetAddressOf()); + +// Draw +spriteBatch->Begin(); +spriteBatch->Draw(texture.Get(), DirectX::XMFLOAT2(100, 100)); +spriteBatch->End(); +``` + +### Loading and Drawing a 3D Model + +```cpp +#include "Model.h" +#include "CommonStates.h" +#include "Effects.h" + +// Create +auto states = std::make_unique(device); +auto fxFactory = std::make_unique(device); +auto model = DirectX::Model::CreateFromSDKMESH(device, L"ship.sdkmesh", *fxFactory); + +// Draw +model->Draw(context, *states, world, view, projection); +``` + +### Drawing Geometric Primitives + +```cpp +#include "GeometricPrimitive.h" + +auto sphere = DirectX::GeometricPrimitive::CreateSphere(context); +sphere->Draw(world, view, projection); +``` + +### Using Effects + +```cpp +#include "Effects.h" + +auto effect = std::make_unique(device); +effect->SetWorld(world); +effect->SetView(view); +effect->SetProjection(projection); +effect->SetTexture(textureSRV.Get()); +effect->Apply(context); +``` + +### Input Handling + +```cpp +#include "Keyboard.h" +#include "Mouse.h" +#include "GamePad.h" + +auto keyboard = std::make_unique(); +auto mouse = std::make_unique(); +auto gamePad = std::make_unique(); + +// In update loop +auto kb = keyboard->GetState(); +if (kb.Escape) + PostQuitMessage(0); + +auto pad = gamePad->GetState(0); +if (pad.IsConnected()) +{ + if (pad.IsAPressed()) + /* jump */; +} +``` + +### Audio + +```cpp +#include "Audio.h" + +// Create audio engine +auto audioEngine = std::make_unique(); + +// Load and play a sound +auto soundEffect = std::make_unique(audioEngine.get(), L"explosion.wav"); +soundEffect->Play(); + +// Per-frame update +audioEngine->Update(); +``` + +## Getting Started Tutorial + +For a full step-by-step walkthrough, see the [Getting Started](https://github.com/microsoft/DirectXTK/wiki/Getting-Started) tutorial on the wiki. + +## Further Reading + +- [DirectXTK Wiki](https://github.com/microsoft/DirectXTK/wiki) +- [DirectX Tool Kit for Audio](https://github.com/microsoft/DirectXTK/wiki/Audio) +- [SimpleMath documentation](https://github.com/Microsoft/DirectXTK/wiki/SimpleMath) +- [Project templates](https://github.com/walbourn/directx-vs-templates) diff --git a/skills/directxtk-usage/reference/overview.md b/skills/directxtk-usage/reference/overview.md new file mode 100644 index 00000000..0ace5aaf --- /dev/null +++ b/skills/directxtk-usage/reference/overview.md @@ -0,0 +1,125 @@ +# DirectX Tool Kit — API Reference Overview + +This document provides a categorized summary of all public classes and helpers in DirectX Tool Kit for DirectX 11. API signatures are defined in the public headers in the `Inc/` directory. + +For detailed documentation on each class, see the [DirectXTK Wiki](https://github.com/microsoft/DirectXTK/wiki). + +## Rendering + +| Header | Classes / Functions | Purpose | +| --- | --- | --- | +| `SpriteBatch.h` | `SpriteBatch` | Hardware-accelerated 2D sprite rendering with batching, rotation, and scaling. | +| `SpriteFont.h` | `SpriteFont` | Bitmap font rendering using SpriteBatch. Supports MakeSpriteFont and BMFont formats. | +| `PrimitiveBatch.h` | `PrimitiveBatch` | Low-level immediate-mode rendering of user-defined vertex types. | +| `GeometricPrimitive.h` | `GeometricPrimitive` | Factory for common 3D shapes (sphere, cube, cylinder, torus, teapot, etc.). | +| `Model.h` | `Model`, `ModelMesh`, `ModelMeshPart`, `ModelBone` | Loading and rendering of 3D models from CMO, SDKMESH and VBO file formats. | + +> Model requires RTTI (`/GR`) to be enabled. + +## Effects (Shaders) + +| Header | Classes | Purpose | +| --- | --- | --- | +| `Effects.h` | `BasicEffect` | Per-pixel lighting with texture, vertex color, and fog support. | +| | `AlphaTestEffect` | Alpha testing (clip pixels below a threshold). | +| | `DualTextureEffect` | Two-layer multitexture blending (e.g., lightmaps). | +| | `EnvironmentMapEffect` | Cubic environment map reflections. | +| | `SkinnedEffect` | Vertex skinning with up to 72 bones. | +| | `SkinnedNormalMapEffect` | Skinned rendering with normal maps. | +| | `NormalMapEffect` | Normal map and optional specular map rendering. | +| | `PBREffect` | Physically-based rendering (metalness/roughness workflow). | +| | `SkinnedPBREffect` | PBR with vertex skinning. | +| | `DebugEffect` | Diagnostic visualization (normals, tangents, texture coordinates). | +| | `IEffect`, `IEffectMatrices`, `IEffectLights`, `IEffectFog`, `IEffectSkinning` | Interfaces implemented by effects. | +| | `EffectFactory`, `PBREffectFactory` | Model-driven effect creation and caching. | + +## Textures + +| Header | Functions | Purpose | +| --- | --- | --- | +| `DDSTextureLoader.h` | `CreateDDSTextureFromFile`, `CreateDDSTextureFromMemory` | Load DDS textures (supports all D3D11 formats, mipmaps, cubemaps, arrays). | +| `WICTextureLoader.h` | `CreateWICTextureFromFile`, `CreateWICTextureFromMemory` | Load common image formats (PNG, JPEG, BMP, TIFF, GIF) via WIC. | +| `XboxDDSTextureLoader.h` | `CreateDDSTextureFromFile`, `CreateDDSTextureFromMemory` | Xbox-optimized DDS loader for tiled resources. | +| `ScreenGrab.h` | `SaveDDSTextureToFile`, `SaveWICTextureToFile` | Capture render targets to DDS or WIC image files. | + +## States and Helpers + +| Header | Classes / Functions | Purpose | +| --- | --- | --- | +| `CommonStates.h` | `CommonStates` | Pre-built blend, depth-stencil, rasterizer, and sampler state objects. | +| `DirectXHelpers.h` | `CreateInputLayoutFromEffect`, `SetDebugObjectName` | Utility functions for input layouts, debug naming, and resource manipulation. | +| | `MapGuard` | RAII-style guard for mapping/unmapping D3D11 buffers. | +| `BufferHelpers.h` | `CreateStaticBuffer`, `CreateConstantBuffer`, `CreateTextureFromMemory` | Helper functions for creating D3D11 buffers and textures. | +| `GraphicsMemory.h` | `GraphicsMemory` | Per-frame memory management for dynamic resources. Required only for the Xbox One platform. | +| `VertexTypes.h` | `VertexPosition`, `VertexPositionColor`, `VertexPositionTexture`, `VertexPositionNormal`, `VertexPositionNormalTexture`, `VertexPositionNormalColor`, `VertexPositionNormalColorTexture`, `VertexPositionNormalTangentColorTexture`, `VertexPositionNormalTangentColorTextureSkinning` | Pre-defined vertex structure types compatible with the built-in effects. | + +## Post-Processing + +| Header | Classes | Purpose | +| --- | --- | --- | +| `PostProcess.h` | `IPostProcess` | Base interface for post-processing effects. | +| | `BasicPostProcess` | Copy, monochrome, sepia, down-scale, bloom extract/blur. | +| | `DualPostProcess` | Merge/blend two textures (bloom combine, weighted average). | +| | `ToneMapPostProcess` | HDR tone mapping (Reinhard, ACESFilmic, etc.) and OETF curves. | + +## Input + +| Header | Classes | Purpose | +| --- | --- | --- | +| `Keyboard.h` | `Keyboard`, `Keyboard::State`, `Keyboard::KeyboardStateTracker` | Keyboard state polling and key-press/release tracking. | +| `Mouse.h` | `Mouse`, `Mouse::State`, `Mouse::ButtonStateTracker` | Mouse state polling with absolute and relative modes. | +| `GamePad.h` | `GamePad`, `GamePad::State`, `GamePad::ButtonStateTracker` | Gamepad state polling, vibration, and button tracking. Supports GameInput, XInput, and Windows.Gaming.Input backends. | + +See [DirectX Tool Kit wiki: GamePad](https://github.com/Microsoft/DirectXTK/wiki/GamePad), [DirectX Tool Kit wiki: Keyboard](https://github.com/Microsoft/DirectXTK/wiki/Keyboard), and [DirectX Tool Kit wiki: Mouse](https://github.com/Microsoft/DirectXTK/wiki/Mouse) for full documentation. + +## Audio + +| Header | Classes | Purpose | +| --- | --- | --- | +| `Audio.h` | `AudioEngine` | XAudio2-based audio engine with 3D audio, mastering voice, and device management. | +| | `SoundEffect` | Loads WAV files and XACT-style wave banks for playback. | +| | `SoundEffectInstance` | Controls playback of a sound (play, pause, stop, loop, volume, pitch, pan). | +| | `SoundStreamInstance` | Streaming playback from disk for large audio files. | +| | `WaveBank` | Loads XACT-style wave bank (.xwb) files containing multiple sounds. | +| | `DynamicSoundEffectInstance` | Programmatic audio generation via callback-driven buffer submission. | +| | `AudioListener`, `AudioEmitter` | 3D audio positioning for spatialized sound. | + +See the [DirectX Tool Kit for Audio wiki](https://github.com/Microsoft/DirectXTK/wiki/Audio) for full documentation. + +## Math + +| Header | Classes / Types | Purpose | +| --- | --- | --- | +| `SimpleMath.h` | `Vector2`, `Vector3`, `Vector4`, `Matrix`, `Quaternion`, `Plane`, `Color`, `Ray`, `Viewport`, `Rectangle` | Wrapper types around DirectXMath (XMFLOAT/XMVECTOR) providing operator overloads and convenience methods. | + +All types support standard arithmetic operators and implicit conversion to/from DirectXMath SIMD types (`XMVECTOR`, `XMMATRIX`). + +See the [SimpleMath wiki](https://github.com/Microsoft/DirectXTK/wiki/SimpleMath) for full documentation. + +## Header Inclusion + +All public headers are standalone — include only what you need: + +```cpp +#include "SpriteBatch.h" // For 2D sprite rendering +#include "Effects.h" // For shader effects +#include "Model.h" // For 3D model loading +#include "Audio.h" // For audio playback +#include "SimpleMath.h" // For math helper types +``` + +There is no single umbrella header. Each header declares its dependencies via forward declarations or includes as needed. + +### VCPKG Usage + +When using VCPKG+MSBuild integration (both classic and manifest mode), the public headers must be included with a `directxtk/` prefix. + +```cpp +#include "directxtk/SpriteBatch.h" +#include "directxtk/Effects.h" +#include "directxtk/Model.h" +#include "directxtk/Audio.h" +#include "directxtk/SimpleMath.h" +``` + +When using VCPKG with CMake integration via `find_package`, the include path is added directly so the prefix is not required, but will generally work as well.