Skip to content

Latest commit

 

History

History
354 lines (280 loc) · 24.2 KB

File metadata and controls

354 lines (280 loc) · 24.2 KB

GitHub Copilot Instructions

These instructions define how GitHub Copilot should assist with this project. The goal is to ensure consistent, high-quality code generation aligned with our conventions, stack, and best practices.

Context

  • Project Type: Graphics Library / DirectX / Direct3D 12 / Game Audio
  • Project Name: DirectX Tool Kit for DirectX 12
  • Language: C++
  • Framework / Libraries: STL / CMake / CTest
  • Architecture: Modular / RAII / OOP

Getting Started

  • See the tutorial at Getting Started.
  • The recommended way to integrate DirectX Tool Kit for DirectX 12 into your project is by using the vcpkg Package Manager. See d3d12game_vcpkg for a template which uses VCPKG.
  • You can make use of the nuget.org packages directxtk12_desktop_win10 or directxtk12_uwp.
  • You can also use the library source code directly in your project or as a git submodule.

If you are new to DirectX, you may want to start with DirectX Tool Kit for DirectX 11 to learn many important concepts for Direct3D programming, HLSL shaders, and the code patterns used in this project with a more 'newbie friendly' API.

General Guidelines

  • Code Style: The project uses an .editorconfig file to enforce coding standards. Follow the rules defined in .editorconfig for indentation, line endings, and other formatting. Additional information can be found on the wiki at Implementation. The library's public API requires C++11, and the project builds with C++17 (CMAKE_CXX_STANDARD 17). This code is designed to build with Visual Studio 2022, Visual Studio 2026, clang for Windows v12 or later, or MinGW 12.2.

Notable .editorconfig rules: C/C++ and HLSL files use 4-space indentation, crlf line endings, and latin1 charset — avoid non-ASCII characters in source files. HLSL files have separate indent/spacing rules defined in .editorconfig.

  • Documentation: The project provides documentation in the form of wiki pages available at Documentation. The audio, input, and math implementations are identical to the DirectX Tool Kit for DirectX 11.
  • Error Handling: Use C++ exceptions for error handling and use RAII smart pointers to ensure resources are properly managed. For some functions that return HRESULT error codes, they are marked noexcept, use std::nothrow for memory allocation, and should not throw exceptions.
  • Testing: Unit tests for this project are implemented in this repository Test Suite and can be run using CTest per the instructions at Test Documentation. See test copilot instructions for additional information on the tests.
  • Security: This project uses secure coding practices from the Microsoft Secure Coding Guidelines, and is subject to the SECURITY.md file in the root of the repository. Functions that read input from image files, geometry files, and audio files are subject to OneFuzz fuzz testing to ensure they are secure against malformed files.
  • Dependencies: The project uses CMake and VCPKG for managing dependencies, making optional use of DirectXMath, DirectX-Headers, DirectX 12 Agility SDK, GameInput, and XAudio2Redist. The project can be built without these dependencies, relying on the Windows SDK for core functionality. CMake build options include BUILD_GAMEINPUT, BUILD_WGI, and BUILD_XINPUT for alternative input backends. Additional CMake build options include BUILD_MIXED_DX11 for DX11 toolkit interop which removes shared code from the DX12 library as it will be present in the DX11 library to avoid link conflicts.
  • Continuous Integration: This project implements GitHub Actions for continuous integration, ensuring that all code changes are tested and validated before merging. This includes building the project for a number of configurations and toolsets, running a subset of unit tests, and static code analysis including GitHub super-linter, CodeQL, and MSVC Code Analysis.
  • Code of Conduct: The project adheres to the Microsoft Open Source Code of Conduct. All contributors are expected to follow this code of conduct in all interactions related to the project.

File Structure

.azuredevops/ # Azure DevOps pipeline configuration and policy files.
.github/      # GitHub Actions workflow files and linter configuration files.
.nuget/       # NuGet package configuration files.
build/        # Miscellaneous build files and scripts.
Audio/        # DirectX Tool Kit for Audio implementation files.
Inc/          # Public header files.
Src/          # Implementation header and source files.
  Shaders/    # HLSL shader files.
Tests/        # Tests are designed to be cloned from a separate repository at this location.
wiki/         # Local clone of the GitHub wiki documentation repository.

Note that DirectX Tool Kit for DirectX 12 utilizes the MakeSpriteFont C# tool and the XWBTool C++ Audio tool hosted in the DirectX Tool Kit for DirectX 11 repository. See MakeSpriteFont and XWBTool.

Patterns

Patterns to Follow

  • Use RAII for all resource ownership (memory, file handles, etc.).
  • Many classes utilize the pImpl idiom to hide implementation details, and to enable optimized memory alignment in the implementation.
  • Use std::unique_ptr for exclusive ownership and std::shared_ptr for shared ownership.
  • Use Microsoft::WRL::ComPtr for COM object management.
  • Make use of anonymous namespaces to limit scope of functions and variables.
  • Make use of assert for debugging checks, but be sure to validate input parameters in release builds.
  • Make use of the DebugTrace helper to log diagnostic messages, particularly at the point of throwing an exception.
  • Explicitly = delete copy constructors and copy-assignment operators on all classes that use the pImpl idiom.
  • Explicitly utilize = default or = delete for copy constructors, assignment operators, move constructors and move-assignment operators where appropriate.
  • Use 16-byte alignment (_aligned_malloc / _aligned_free) to support SIMD operations in the implementation, but do not expose this requirement in public APIs.
  • All implementation .cpp files include pch.h as their first include (precompiled header). MinGW builds skip precompiled headers.
  • Model and related classes require RTTI (/GR on MSVC, __GXX_RTTI on GCC/Clang). The CMake build enables /GR automatically; do not disable RTTI when using Model.
  • Many public headers use inline namespace DX12 inside namespace DirectX to disambiguate from DirectX Tool Kit for DirectX 11 types when both libraries are used together. This is usually indicated when parameters use the ID3D12Device type. Follow this pattern for new headers that have Direct3D 12-specific types in the public API.
  • Use static constexpr for class-scope constants (e.g., static constexpr int MaxDirectionalLights = 3;, static constexpr unsigned int InputElementCount = 1;). SimpleMath types use constexpr constructors for compile-time initialization.
  • Functions that load data from memory (texture loaders, Model) provide both const uint8_t* and const std::byte* overloads. When adding new memory-buffer APIs, provide both overload variants. The const std::byte * overloads are guarded by #ifdef __cpp_lib_byte to maintain compatibility with older C++ standards.
  • Each public header wraps the DIRECTX_TOOLKIT_API macro definition in #ifndef DIRECTX_TOOLKIT_API so it is only defined once. Follow this guard pattern when adding new headers.
  • Headers use #pragma comment(lib, ...) under _MSC_VER to auto-link platform libraries (e.g., gameinput.lib, xinput.lib, runtimeobject.lib). Follow this pattern for new platform library dependencies.

SAL Annotations

All public API functions must use SAL annotations on every parameter. Use _Use_decl_annotations_ at the top of each implementation that has SAL in the header declaration — never repeat the annotations in the .cpp or .inl file.

Common annotations:

Annotation Meaning
_In_ Input parameter
_Out_ Output parameter
_Inout_ Bidirectional parameter
_In_reads_bytes_(n) Input buffer with byte count
_In_reads_(n) Input array with element count
_In_z_ Null-terminated input string
_In_opt_ Optional input parameter (may be null)
_Out_opt_ Optional output parameter
_COM_Outptr_ Output COM interface

Example:

// Header (BufferHelpers.h)
DIRECTX_TOOLKIT_API
    HRESULT __cdecl CreateStaticBuffer(
        _In_ ID3D12Device* device,
        ResourceUploadBatch& resourceUpload,
        _In_reads_bytes_(count* stride) const void* ptr,
        size_t count,
        size_t stride,
        D3D12_RESOURCE_STATES afterState,
        _COM_Outptr_ ID3D12Resource** pBuffer,
        D3D12_RESOURCE_FLAGS resFlags = D3D12_RESOURCE_FLAG_NONE) noexcept;

// Implementation (.cpp)
_Use_decl_annotations_
HRESULT DirectX::CreateStaticBuffer(
    ID3D12Device* device,
    ResourceUploadBatch& resourceUpload,
    const void* ptr,
    size_t count,
    size_t stride,
    D3D12_RESOURCE_STATES afterState,
    ID3D12Resource** pBuffer,
    D3D12_RESOURCE_FLAGS resFlags) noexcept
{ ... }

Calling Convention and DLL Export

  • All public free functions use __cdecl explicitly for ABI stability.
  • Functions that take XMVECTOR, FXMVECTOR, or XMMATRIX parameters use XM_CALLCONV instead of __cdecl to enable efficient SIMD register passing. This is the DirectXMath calling convention and is used extensively in SpriteBatch, SpriteFont, Effects, Model, and VertexTypes.
  • All public function declarations are prefixed with DIRECTX_TOOLKIT_API, which wraps __declspec(dllexport) / __declspec(dllimport) or the GCC __attribute__ equivalent when using BUILD_SHARED_LIBS in CMake. The underlying macros are DIRECTX_TOOLKIT_EXPORT (for building the library) and DIRECTX_TOOLKIT_IMPORT (for consuming it).
  • For free functions, DIRECTX_TOOLKIT_API appears on the line above the return type. For inner classes and interfaces, the macro is placed inline: class DIRECTX_TOOLKIT_API ClassName.
  • When importing DLL classes under MSVC, headers suppress warnings C4251 and C4275 via #pragma warning(disable : 4251 4275) inside a #if defined(DIRECTX_TOOLKIT_IMPORT) && defined(_MSC_VER) guard.

noexcept Rules

  • All query and utility functions that cannot fail are marked noexcept.
  • All HRESULT-returning I/O and processing functions are also noexcept — errors are communicated via return code, never via exceptions.
  • Constructors and functions that perform heap allocation or utilize Standard C++ containers that may throw are marked noexcept(false).

Enum Flags Pattern

Flags enums follow this pattern — a uint32_t-based unscoped enum with a _DEFAULT = 0 base case, followed by a call to DEFINE_ENUM_FLAG_OPERATORS to enable |, &, and ~ operators:

enum DDS_LOADER_FLAGS : uint32_t
{
    DDS_LOADER_DEFAULT = 0,
    DDS_LOADER_FORCE_SRGB = 0x1,
    DDS_LOADER_IGNORE_SRGB = 0x2,
    DDS_LOADER_MIP_AUTOGEN = 0x8,
    DDS_LOADER_MIP_RESERVE = 0x10,
    DDS_LOADER_IGNORE_MIPS = 0x20,
};

DEFINE_ENUM_FLAG_OPERATORS(DDS_LOADER_FLAGS);

See this blog post for more information on this pattern.

Clang Diagnostic Pragmas

Headers that trigger Clang warnings use paired #pragma clang diagnostic push/pop blocks under #ifdef __clang__ to suppress specific diagnostics. Common suppressions include -Wunsafe-buffer-usage, -Wfloat-equal, and -Wunknown-warning-option. Follow this pattern when adding code that legitimately triggers Clang-specific warnings:

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"
#endif

// ... code ...

#ifdef __clang__
#pragma clang diagnostic pop
#endif

Patterns to Avoid

  • Don’t use raw pointers for ownership.
  • Avoid macros for constants—prefer constexpr or inline const.
  • Don’t put implementation logic in header files unless using templates, although the SimpleMath library does use an .inl file for performance.
  • Avoid using using namespace in header files to prevent polluting the global namespace.
  • Don't use [[deprecated]] or __declspec(deprecated) attributes. Feature retirement is communicated via CHANGELOG.md notes, not in-source deprecation markers.

Naming Conventions

Element Convention Example
Classes / structs PascalCase VertexPosition
Public functions PascalCase + __cdecl or XM_CALLCONV ComputeDisplayArea
Private data members m_ prefix m_count
Static constexpr members c_ prefix (camelCase) or PascalCase c_MostRecent, MaxDirectionalLights
Enum type names UPPER_SNAKE_CASE DDS_LOADER_FLAGS
Enum values UPPER_SNAKE_CASE DDS_LOADER_DEFAULT
Files PascalCase ScreenGrab.h, SpriteEffect.fx

File Header Convention

Every source file (.cpp, .h, .hlsl, .fx, etc.) must begin with this block:

//--------------------------------------------------------------------------------------
// File: {FileName}
//
// {One-line description}
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// https://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------

Section separators within files use:

  • //--------------------------------------------------------------------------------------

The project does not use Doxygen. API documentation is maintained exclusively on the GitHub wiki.

HLSL Shader Compilation

Shaders in Src/Shaders/ are compiled to embedded C++ header files (.inc):

  • Use CompileShaders.cmd in Src/Shaders/ to regenerate the .inc files.
  • By default (BUILD_DXIL_SHADERS=ON), shaders are compiled with DXC targeting Shader Model 6.0.
  • Set BUILD_DXIL_SHADERS=OFF to compile with legacy FXC targeting Shader Model 5.1 instead.
  • The CMake option USE_PREBUILT_SHADERS=ON skips shader compilation and uses pre-built .inc files; requires COMPILED_SHADERS variable to be set.

References

No speculation

When creating documentation:

Document Only What Exists

  • Only document features, patterns, and decisions that are explicitly present in the source code.
  • Only include configurations and requirements that are clearly specified.
  • Do not make assumptions about implementation details.

Handle Missing Information

  • Ask the user questions to gather missing information.
  • Document gaps in current implementation or specifications.
  • List open questions that need to be addressed.

Source Material

  • Always cite the specific source file and line numbers for documented features.
  • Link directly to relevant source code when possible.
  • Indicate when information comes from requirements vs. implementation.

Verification Process

  • Review each documented item against source code whenever related to the task.
  • Remove any speculative content.
  • Ensure all documentation is verifiable against the current state of the codebase.

Cross-platform Support Notes

  • The code targets Win32 desktop applications for Windows 10 or later, Xbox One, Xbox Series X|S, and Universal Windows Platform (UWP) apps for Windows 10 and Windows 11.
  • Portability and conformance of the code is validated by building with Visual C++, clang/LLVM for Windows, and MinGW.
  • For PC development using the Microsoft GDK, the project provides MSBuild solution DirectXTK_GDKW_2022.sln for the x64 or ARM64 architectures.
  • The MSBuild solution DirectXTK_GDK_2022.sln is for Microsoft GDK with Xbox Extensions development for both PC using the legacy Gaming.Desktop.x64 custom platform as well as Xbox using Gaming.Xbox.*.x64 platforms.
  • For Xbox development, the project provides MSBuild solution DirectXTK_GDKX_2022.sln or DirectXTK_GDKX_2026.slnx for the Microsoft GDK with Xbox Extensions using Gaming.Xbox.*.x64 platforms.
  • The project ships MSBuild projects for Visual Studio 2022 (.sln / .vcxproj) and Visual Studio 2026 (.slnx / .vcxproj). VS 2019 projects have been retired.
  • The CMake build supports Xbox Series X|S (scarlett) and Xbox One (xboxone) via the XBOX_CONSOLE_TARGET variable.
  • The CMake build supports legacy Xbox One XDK via the XBOX_CONSOLE_TARGET variable (durango).

Platform and Compiler #ifdef Guards

Use these established guards — do not invent new ones:

Guard Purpose
_WIN32 Windows platform (desktop, UWP, Xbox)
_GAMING_XBOX Xbox platform (GDK - covers both Xbox One and Xbox Series X|S)
_GAMING_XBOX_SCARLETT Xbox Series X|S (GDK with Xbox Extensions)
_GAMING_XBOX_XBOXONE Xbox One (GDK with Xbox Extensions)
_GAMING_DESKTOP Gaming desktop platform (GDK); used for GRDK edition version checks
_XBOX_ONE && _TITLE Xbox One XDK (legacy)
_MSC_VER MSVC-specific (and MSVC-like clang-cl) pragmas and warning suppression
__clang__ Clang/LLVM diagnostic suppressions
__MINGW32__ MinGW compatibility headers
__GNUC__ MinGW/GCC DLL attribute equivalents
_M_ARM64 / _M_X64 / _M_IX86 Architecture-specific code paths for MSVC (#ifdef)
_M_ARM64EC ARM64EC ABI (ARM64 code with x64 interop) for MSVC
__aarch64__ / __x86_64__ / __i386__ Additional architecture-specific symbols for MinGW/GNUC (#if)
USING_DIRECTX_HEADERS External DirectX-Headers package in use
USING_GAMEINPUT GameInput API for GamePad, Keyboard, Mouse
USING_WINDOWS_GAMING_INPUT Windows.Gaming.Input API for GamePad
USING_XINPUT XInput API for GamePad
USING_COREWINDOW CoreWindow-based input (UWP) for Keyboard, Mouse
GAMEINPUT_API_VERSION GameInput SDK version detection for API-level feature checks
USING_PIX_CUSTOM_MEMORY_EVENTS PIX custom memory event integration in GraphicsMemory

_M_ARM / __arm__ is legacy 32-bit ARM which is deprecated.

Code Review Instructions

When reviewing code, focus on the following aspects:

  • Adherence to coding standards defined in .editorconfig and on the wiki.
  • Make coding recommendations based on the C++ Core Guidelines.
  • Proper use of RAII and smart pointers.
  • Correct error handling practices and C++ Exception safety.
  • Clarity and maintainability of the code.
  • Adequate comments where necessary.
  • Public interfaces located in Inc\*.h should be clearly defined and documented on the GitHub wiki.
  • Compliance with the project's architecture and design patterns.
  • Ensure that all public functions and classes are covered by unit tests located on GitHub where applicable. Report any gaps in test coverage.
  • Check for performance implications, especially in geometry processing algorithms.
  • Provide brutally honest feedback on code quality, design, and potential improvements as needed.

Documentation Review Instructions

When reviewing documentation, do the following:

  • Read the code located in this git repository in the main branch.
  • Review the public interface defined in the Inc folder.
  • Read the documentation on the wiki located in this git repository.
  • Report any specific gaps in the documentation compared to the public interface.

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 the NuGet packages.
  11. Edit the GitHub release and upload the signed binaries from the matching DirectXTK release to the release assets.
  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. Run minisign on the .zip to generate a signature file, and upload the signature file to the release assets.
  13. Validate the NuGet packages with https://github.com/walbourn/directxtk-tutorials by pushing the NuGet packages to a local Packages Source folder, and refreshing the NuGet packages from that folder. Then build using BuildAllSolutions.targets.
  14. 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.
  15. 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.
  16. Git pull a local repository of VCPKG to d:\vcpkg in sync with the main branch of the VCPKG repository.
  17. Run the PowerShell script build\updatevcpkg.ps1 to update the DirectXTK12 port in VCPKG with the new release version. This will edit the files in ports\directxtk12.
  18. Test the VCPKG port using all appropriate triplets and features.
  19. Run .\vcpkg --x-add-version directxtk12 to update the VCPKG versioning history.
  20. Submit a PR to the VCPKG repository to update the DirectXTK12 port back to the main GitHub repo. The PR will be reviewed and merged by the VCPKG 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.