Quantcast
Channel: directxtk Wiki Rss Feed
Viewing all 874 articles
Browse latest View live

Updated Wiki: PrimitiveBatch

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for easily and efficiently drawing dynamically generated geometry using Direct3D 11 such as lines or trianges. It fills the same role as the legacy Direct3D 9 APIs DrawPrimitiveUP and DrawIndexedPrimitiveUP. Dynamic submission is a highly effective pattern for drawing procedural geometry, and convenient for debug rendering, but is not nearly as efficient as static buffers which is more suited to traditional meshes where the VBs and IBs do not change every frame. Excessive dynamic submission is a common source of performance problems in apps. Therefore, you should prefer to use Model, GeometricPrimitive, or your own VB/IB over PrimitiveBatch unless you really need the flexibility to regenerate the topology every frame.

PrimitiveBatch manages the vertex and index buffers for you, using DISCARD and NO_OVERWRITE hints to avoid stalling the GPU pipeline. It automatically merges adjacent draw requests, so if you call DrawLine 100 times in a row, only a single GPU draw call will be generated.

PrimitiveBatch is responsible for setting the vertex buffer, index buffer, and primitive topology, then issuing the final draw call. Unlike the higher level SpriteBatch helper, it does not provide shaders, set the input layout, or set any state objects. PrimitiveBatch is often used in conjunction with BasicEffect and the structures from VertexTypes, but it can work with any other shader or vertex formats of your own.

Related tutorial:Simple rendering

Header

#include <PrimitiveBatch.h>

Initialization

Initialize a PrimitiveBatch for drawing VertexPositionColor data

std::unique_ptr<PrimitiveBatch<VertexPositionColor>> primitiveBatch(
    new PrimitiveBatch<VertexPositionColor>(deviceContext));

For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr or std::shared_ptr

The default values assume that your maximum batch size is 2048 vertices arranged in triangles. If you want to use larger batches, you need to provide the additional constructor parameters (be sure to review the Feature Level limitations below).

PrimitiveBatch<T>( ID3D11DeviceContext* deviceContext, size_t maxIndices = DefaultBatchSize * 3, size_t maxVertices = DefaultBatchSize)

Effect and Input Layout

Setting up a suitable BasicEffect and input layout:

std::unique_ptr<BasicEffect> basicEffect(new BasicEffect(device));

basicEffect->SetProjection(XMMatrixOrthographicOffCenterRH(0, screenHeight, screenWidth, 0, 0, 1));
basicEffect->SetVertexColorEnabled(true);

voidconst* shaderByteCode;
size_t byteCodeLength;

basicEffect->GetVertexShaderBytecode(&shaderByteCode, &byteCodeLength);

ComPtr<ID3D11InputLayout> inputLayout;

device->CreateInputLayout(VertexPositionColor::InputElements,
                          VertexPositionColor::InputElementCount,
                          shaderByteCode, byteCodeLength,
                          inputLayout.GetAddressOf() );

Drawing

CommonStates states( device );
deviceContext->OMSetBlendState( states.Opaque(), nullptr, 0xFFFFFFFF );
deviceContext->OMSetDepthStencilState( states.DepthNone(), 0 );
deviceContext->RSSetState( states.CullCounterClockwise() );

basicEffect->Apply(deviceContext);
deviceContext->IASetInputLayout(inputLayout.Get());

primitiveBatch->Begin();
primitiveBatch->DrawLine(VertexPositionColor(...), VertexPositionColor(...));
primitiveBatch->End();
PrimitiveBatch provides five drawing methods:
  • DrawLine(v1, v2)): Draws a single-pixel line between two vertices
  • DrawTriangle(v1, v2, v3): Draws a triangle between three vertices
  • DrawQuad(v1, v2, v3, v4): draws a quad from four corner vertices (submitted as two triangles)
  • Draw(topology, vertices, vertexCount): Draws an array of vertices with the given topology
  • DrawIndexed(topology, indices, indexCount, vertices, vertexCount): Draws an indexed array of vertices with a given topology.

Optimization

For best performance, draw as much as possible inside the fewest separate Begin/End blocks. This will reduce overhead and maximize potential for batching.

Ideally submit draws of the same topology to avoid flushing, and preferably use D3D_PRIMITIVE_TOPOLOGY_POINTLIST, D3D_PRIMITIVE_TOPOLOGY_LINELIST, or D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.

The PrimitiveBatch constructor allows you to specify what size index and vertex buffers to allocate. You may want to tweak these values to fit your workload, or if you only intend to draw non-indexed geometry, specify maxIndices = 0 to entirely skip creating the index buffer.

Feature Level Notes

In order to support all feature levels, PrimitiveBatch only supports 16-bit indices (DXGI_FORMAT_R16_UINT) which limits to a maximum of 65535 addressable vertices. This does not apply to non-indexed drawing when the PrimitiveBatch constructor is called with a maxIndices of 0.

Keep in mind there is a feature-level based limit on the maximum number of primitives in a single draw call, so the overall batch size needs to be under this limit. To support all feature levels, this should be 65535 or less lines or triangles in a single 'draw batch'.

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx

http://blogs.msdn.com/b/chuckw/archive/2012/06/20/direct3d-feature-levels.aspx

Threading model

Each PrimitiveBatch instance only supports drawing from one thread at a time, but you can simultaneously submit primitives on multiple threads if you create a separate PrimitiveBatch instance per Direct3D 11 deferred context.
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476892.aspx

Further Reading

http://blogs.msdn.com/b/shawnhar/archive/2012/10/12/directxtk-primitivebatch-helper-makes-it-easy-to-draw-user-primitives-with-d3d11.aspx

http://msdn.microsoft.com/en-us/library/windows/desktop/dn508285.aspx

Updated Wiki: ScreenGrab

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

A Direct3D 11 2D texture save routine for generating a "screenshot" from a render target texture. There is a function that will dump the 2D texture to a .DDS file, and another that will write using WIC (BMP, JPEG, PNG, TIFF, GIF, JPEG-XR / HD Photo, or other WIC supported file container).

These writers do not support array textures, 1D textures, 3D volume textures, or cubemaps. Mipmaps are also ignored. For those scenarios, use the DirectXTex library functionality. The ScreenGrab module is really designed to make a quick and light-weight solution for capturing screenshots at runtime.

MSAA textures are resolved before being written.

Also part of DirectXTex http://go.microsoft.com/fwlink/?LinkId=248926

The module assumes that the client code will have already called CoInitialize, CoInitializeEx, or Windows::Foundation::Initialize as needed by the application before calling the WIC save routines

Header

#include <ScreenGrab.h>

Functions

SaveDDSTextureToFile
Saves a texture to a DDS file on disk. It performs no format conversions, but will try to favor writing legacy .DDS files when possible for improved tool support.

HRESULT SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext,
    _In_ ID3D11Resource* pSource,
    _In_z_ LPCWSTR fileName );

SaveWICTextureToFile
Saves a texture to a WIC-supported bitmap file on disk. The caller provides the desired WIC container format via guidContainerFormat and can optionally specify a desired WIC pixel format via targetFormat (which will result in E_FAIL if the requested pixel format is not supported by the WIC codec). If no WIC pixel format GUID is provided as the targetFormat parameter, it will default to a non-alpha format since 'screenshots' usually ignore the alpha channel in render targets.

HRESULT SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext,
    _In_ ID3D11Resource* pSource,
    _In_ REFGUID guidContainerFormat, 
    _In_z_ LPCWSTR fileName,
    _In_opt_ const GUID* targetFormat = nullptr,
    _In_opt_ std::function<void(IPropertyBag2*)> setCustomProps = nullptr );

NOTE: SaveWICTextureToFile is not supported on Windows Phone 8.0, because WIC is not available on that platform

Examples

This example saves a JPEG screenshot given a ID3D11DeviceContext immContext and IDXGISwapChain swapChain.

usingnamespace DirectX;
usingnamespace Microsoft::WRL;

ComPtr<ID3D11Texture2D> backBuffer;
HRESULT hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ),
   reinterpret_cast<LPVOID*>( backBuffer.GetAddressOf() ) );
if ( SUCCEEDED(hr) )
{
    hr = SaveWICTextureToFile( immContext.Get(), backBuffer.Get(),
                GUID_ContainerFormatJpeg, L"SCREENSHOT.JPG" );
}
DX::ThrowIfFailed(hr);

Here is an example of explicitly writing a screenshot as a 16-bit (5:6:5) BMP.

usingnamespace DirectX;
usingnamespace Microsoft::WRL;

ComPtr<ID3D11Texture2D> backBuffer;
HRESULT hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ),
   reinterpret_cast<LPVOID*>( backBuffer.GetAddressOf() ) );
if ( SUCCEEDED(hr) )
{
    hr = SaveWICTextureToFile( immContext.Get(), backBuffer.Get(),
                GUID_ContainerFormatBmp, L"SCREENSHOT.BMP",
                &GUID_WICPixelFormat16bppBGR565 );
}
DX::ThrowIfFailed(hr);

When writing WIC files, you can also provide a callback for setting specific encoding options.

usingnamespace DirectX;
usingnamespace Microsoft::WRL;

ComPtr<ID3D11Texture2D> backBuffer;
HRESULT hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ),
   reinterpret_cast<LPVOID*>( backBuffer.GetAddressOf() ) );
if ( SUCCEEDED(hr) )
{
    hr = SaveWICTextureToFile( immContext.Get(), backBuffer.Get(),
                GUID_ContainerFormatTiff, L"SCREENSHOT.TIF", nullptr,
                [&](IPropertyBag2* props)
                {
                    PROPBAG2 options[2] = { 0, 0 };
                    options[0].pstrName = L"CompressionQuality";
                    options[1].pstrName = L"TiffCompressionMethod";

                    VARIANT varValues[2];
                    varValues[0].vt = VT_R4;
                    varValues[0].fltVal = 0.75f;

                    varValues[1].vt = VT_UI1;
                    varValues[1].bVal = WICTiffCompressionNone;

                    (void)props->Write( 2, options, varValues ); 
                });
}
DX::ThrowIfFailed(hr);

Release Notes

  • If built with #define DXGI_1_2_FORMATS the DDS writer supports BGRA 4:4:4:4 files.
  • JPEG-XR / HD Photo supports nearly all WIC pixel formats including floating-point for both encoding and decoding.
  • TIFF can contain floating-point data (128bpp or 96bpp), but the WIC built-in codec can only decode such images. It always converts floating-point data to unorm when encoding.
  • Paletted WIC formats are not supported for writing by the SaveWICTextureToFile function.

WIC2

WIC2 is available on Windows 8 and on Windows 7 Service Pack 1 with KB 2670838 installed.
  • If WIC2 is supported, then this function can make use of the new WIC pixel format GUID_WICPixelFormat96bppRGBFloat.
http://support.microsoft.com/kb/2670838

Windows Store apps

For Save*TextureToFile to succeed, the application must have write access to the destination path. For Windows Store apps, the file access permissions are rather restricted so you'll need to make sure you use a fully qualified path to a valid write folder. A good location to use is the app data folder:

auto folder = Windows::Storage::ApplicationData::Current->LocalFolder;
// use folder->Path->Data() as the path base

If you are going to immediately copy it to another location via StorageFolder::MoveAndReplaceAsync, then use the app's temporary folder:

#include <ppltasks.h>
usingnamespace concurrency;

using Windows::Storage;
using Windows::Storage::Pickers;

auto folder = Windows::Storage::ApplicationData::Current->TemporaryFolder;

WCHAR fname[ _MAX_PATH ];
wcscpy_s( fname, folder->Path->Data() );
wcscat_s( fname, L"\\screenshot.jpg" );

// note that context use is not thread-safe
HRESULT hr = SaveWICTextureToFile( immContext.Get(), backBuffer.Get(),
    GUID_ContainerFormatJpeg, fname  );

DX::ThrowIfFailed(hr);

create_task(savePicker->PickSaveFileAsync()).then([](StorageFile^ file)
{
    if ( file )
    {
        auto folder = Windows::Storage::ApplicationData::Current->TemporaryFolder;
        auto task = create_task( folder->GetFileAsync("screenshot.jpg") );
        task.then([file](StorageFile^ tempFile) ->IAsyncAction^
        {
            return tempFile->MoveAndReplaceAsync( file );
        });
    }
});

https://msdn.microsoft.com/en-us/library/windows/apps/hh967755.aspx
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.storage.applicationdata.temporaryfolder.aspx

Updated Wiki: SimpleMath

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

SimpleMath.h wraps the DirectXMath SIMD vector/matrix math API with an easier to use C++ interface. It provides the following types, with similar names, methods, and operator overloads to the XNA Game Studio math API:
  • Vector2
  • Vector3
  • Vector4
  • Matrix
  • Quaternion
  • Plane
  • Ray
  • Color

Related tutorials:Using the SimpleMath library, Basic game math, Collision detection, Mixing SimpleMath and DirectXMath

Header

#include "SimpleMath.h"usingnamespace DirectX::SimpleMath;

Why wrap DirectXMath?

DirectXMath provides highly optimized vector and matrix math functions, which take advantage of SSE SIMD intrinsics when compiled for x86/x64, or the ARM NEON instruction set when compiled for an ARM platform such as Windows RT or Windows Phone. The downside of being designed for efficient SIMD usage is that DirectXMath can be somewhat complicated to work with. Developers must be aware of correct type usage (understanding the difference between SIMD register types such as XMVECTOR vs. memory storage types such as XMFLOAT4), must take care to maintain correct alignment for SIMD heap allocations, and must carefully structure their code to avoid accessing individual components from a SIMD register. This complexity is necessary for optimal SIMD performance, but sometimes you just want to get stuff working without so much hassle!

Enter SimpleMath...

These types derive from the equivalent DirectXMath memory storage types (for instance Vector3 is derived from XMFLOAT3), so they can be stored in arbitrary locations without worrying about SIMD alignment, and individual components can be accessed without bothering to call SIMD accessor functions. But unlike XMFLOAT3, the Vector3 type defines a rich set of methods and overloaded operators, so it can be directly manipulated without having to first load its value into an XMVECTOR. Vector3 also defines an operator for automatic conversion to XMVECTOR, so it can be passed directly to methods that were written to use the lower level DirectXMath types.

If that sounds horribly confusing, the short version is that the SimpleMath types pretty much "Just Work" the way you would expect them to.

By now you must be wondering, where is the catch? And of course there is one. SimpleMath hides the complexities of SIMD programming by automatically converting back and forth between memory and SIMD register types, which tends to generate additional load and store instructions. This can add significant overhead compared to the lower level DirectXMath approach, where SIMD loads and stores are under explicit control of the programmer.

You should use SimpleMath if you are:
  • Looking for a C++ math library with similar API to the C# XNA types
  • Porting existing XNA code from C# to C++
  • Wanting to optimize for programmer efficiency (simplicity, readability, development speed) at the expense of runtime efficiency

You should go straight to the underlying DirectXMath API if you:
  • Want to create the fastest possible code
  • Enjoy the lateral thinking needed to express algorithms in raw SIMD

This need not be a global either/or decision. The SimpleMath types know how to convert themselves to and from the corresponding DirectXMath types, so it is easy to mix and match. You can use SimpleMath for the parts of your program where readability and development time matter most, then drop down to DirectXMath for performance hotspots where runtime efficiency is more important.

Collision types

The SimpleMath wrapper does not include classes for bounding volumes because they are already implemented in the DirectXMath library, and are included by the "SimpleMath.h" header.

This includes:
  • BoundingSphere class
  • BoundingBox class
  • BoundingOrientedBox class
  • BoundingFrustum class
  • TriangleTests namespace
These were designed to already be similar to the XNA Game Studio math API bounding types.

Note: Currently the BoundingFrustum class is not compatible with Right-Handed coordinates.

Coordinate Systems

Because SimpleMath Is intended to look a lot like like XNA Game Studio's math library, it uses right-handed coordinates by convention for the following Matrix methods:
  • CreatePerspectiveFieldOfView
  • CreatePerspective
  • CreatePerspectiveOffCenter
  • CreateOrthographic
  • CreateOrthographicOffCenter
  • CreateLookAt
If you want to use left-handed coordinates, use the DirectXMath methods directly. For example

// Here's a RH example
Vector3 eye, target, up;
...
Matrix mView = Matrix::CreateLookAt( eye, target, up );

// Here' is a LH example of same thing which relies on// Vector3 and Matrix conversion operators
Vector3 eye, target, up;
...
Matrix mView = XMMatrixLookAtLH( eye, target, up ); 

With the methods Matrix::CreateBillboard and Matrix::CreateConstrainedBillboard the handedness is inherent in the default vectors for cameraForward, and objectForward which are right-handed. You can make them behave left-handed by providing appropriate vectors.

Vector3 objectPosition, cameraPosition, rotateAxis;

Matrix mView = Matrix::CreateBillboard( objectPosition, cameraPosition, Vector3::Up, Vector3::Backward );

Matrix mView = Matrix::CreateConstrainedBillboard( objectPosition, cameraPosition, rotateAxis, Vector3::Backward, Vector3::Backward );

Windows Store apps

A number of Windows Store samples include a "BasicMath.h" header that includes some very simplistic math types:
  • Vector2
  • Vector3
  • Vector4
  • Matrix4x4
It is fairly easy to use SimpleMath in place of BasicMath, but keep in mind that the BasicMath.h header types are actually templates so they are typically used as "Vector2<float>". SimpleMath types are always single-precision float numbers so do not make use of template syntax.

BasicMath.h also includes typedef aliases for these types to make them use the same naming as HLSL vector types, although the usage syntax and operations are quite different:
  • float2
  • float3
  • float4
  • float4x4
If you like the HLSL-like type names, you could use SimpleMath in place of BasicMath.h by adding some simple typedefs.

#include "SimpleMath.h"typedef DirectX::SimpleMath::Vector2 float2;
typedef DirectX::SimpleMath::Vector3 float3;
typedef DirectX::SimpleMath::Vector4 float4;
typedef DirectX::SimpleMath::Matrix float4x4;

Note: The actual operations would look different than the way they would using BasicMath.

XMVECTOR and XMMATRIX

The DirectXMath library is intended as a light-weight wrapper over the underlying SIMD instructions supported by modern CPUs. SIMD stands for 'Single-Instruction-Multiple-Data' and is a specific form of parallelism. The idea is pretty straight-forward: the registers X and Y contain more than one element (commonly 4 32-bit floating point values) in each. You then do an instruction, such as X * Y, and the output is more than one result (commonly 4 values from X are multiplied with 4 values from Y resulting in 4 values in the result).

DirectXMath is by design a 'leaky abstraction' in that it exposes the architectural restrictions to the developer. The 'work-horse' types that essentially every DirectXMath function takes as input parameters and produces as results is either XMVECTOR (4 32-bit floating-point values) or XMMATRIX (a 4x4 matrix of 32-bit floating-point values). These types have a strict requirement of being aligned to 16-byte boundaries in memory. If this restriction is not met, the program will crash with a mis-alignment exception at runtime.

Using XMVECTOR or XMMATRIX as local variables on the stack or as a global or static variable in memory will automatically respect the alignment requirements, but this is not necessarily true of memory allocated from the 'heap' (i.e. new for C++ programs or malloc for C programs). It happens that x64 native (64-bit) applications use 16-byte alignment for the heap by default, but this is not true of x86 (32-bit) or ARM applications. As such, using XMVECTOR or XMMATRIX directly in a struct or class allocated on the heap can be dangerous or at least less trivial than it first appears. There are ways to ensure that heap-allocated memory is always aligned, but generally it's more trouble than it's really worth in practice. There are also subtle ways that C++ constructs can misalign structures that you thought were properly aligned.

As such, DirectXMath includes a number of memory analogs for XMVECTOR and XMMATRIX, and explicit load & store operations for moving the data into and out of them. This is actually quite efficient, particularly if you are able to move them from memory into an XMVECTOR or XMMATRIX, then perform a long chain of operations on that data before storing the result back to memory.

One of SimpleMath's primary functions is to hide the existence of XMVECTOR and XMMATRIX. Instead, you can use Vector3 or Matrix without any alignment requirements, and the C++ compiler will automatically call the required load and store functions. This makes working with DirectXMath much more forgiving, at the potential cost of extra load and stores taking place 'invisible' to the programmer.

Since this is implemented using C++ conversion operators, you can at any point use a SimpleMath type directly with a DirectXMath function that takes XMVECTOR and/or XMMATRIX. They are also completely equivalent to a standard memory type in the DirectXMath library:
  • Vector2 <-> XMFLOAT2, XMVECTOR
  • Vector3 <-> XMFLOAT3, XMVECTOR
  • Vector4 <-> XMFLOAT4, XMVECTOR
  • Quaternion <-> XMFLOAT4, XMVECTOR
  • Color <-> XMFLOAT4, XMVECTOR
  • Plane <-> XMFLOAT4, XMVECTOR
  • Matrix <-> XMFLOAT4X4, XMMATRIX
You can therefore freely mix SimpleMath types with DirectXMath functions at any point.

Further Reading

http://blogs.msdn.com/b/chuckw/archive/2012/03/27/introducing-directxmath.aspx
http://blogs.msdn.com/b/chuckw/archive/2012/09/11/directxmath-sse-sse2-and-arm-neon.aspx
http://blogs.msdn.com/b/chuckw/archive/2013/03/06/known-issues-directxmath-3-03.aspx
http://blogs.msdn.com/b/chuckw/archive/2014/12/12/known-issues-directxmath-3-06.aspx
http://blogs.msdn.com/b/shawnhar/archive/2013/01/08/simplemath-a-simplified-wrapper-for-directxmath.aspx

Updated Wiki: SpriteBatch

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a native Direct3D 11 implementation of the SpriteBatch helper from XNA Game Studio, providing identical functionality and API.

SpriteBatchExample.jpg

Related tutorials:Sprites and textures, More tricks with sprites

Header

#include <SpriteBatch.h>

Initialization

The SpriteBatch class requires a Direct3D 11 device context for drawing.

std::unique_ptr<SpriteBatch> spriteBatch(new SpriteBatch(deviceContext));
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr or std::shared_ptr

Simple drawing

spriteBatch->Begin();
spriteBatch->Draw(texture, XMFLOAT2(x, y));
spriteBatch->End();
The Draw method has many overloads with parameters controlling:
  • Specify screen position as XMFLOAT2, XMVECTOR or RECT
  • Optional source rectangle for drawing just part of a sprite sheet
  • Tint color
  • Rotation (in radians)
  • Origin point (position, scaling and rotation are relative to this)
  • Scale
  • SpriteEffects enum (for horizontal or vertical mirroring)
  • Layer depth (for sorting)

Sorting

The first parameter to SpriteBatch::Begin is a SpriteSortMode enum. For most efficient rendering, use SpriteSortMode_Deferred (which batches up sprites, then submits them all to the GPU during the End call), and manually draw everything in texture order. If it is not possible to draw in texture order, the second most efficient approach is to use SpriteSortMode_Texture, which will automatically sort on your behalf.

When drawing scenes with multiple depth layers, SpriteSortMode_BackToFront or SpriteSortMode_FrontToBack will sort by the layerDepth parameter specified to each Draw call.

SpriteSortMode_Immediate disables all batching, submitting a separate Direct3D draw call for each sprite. This is expensive, but convenient in rare cases when you need to set shader constants differently per sprite.

Multiple SpriteBatch instances are lightweight. It is reasonable to create several, Begin them at the same time with different sort modes, submit sprites to different batches in arbitrary orders as you traverse a scene, then End the batches in whatever order you want these groups of sprites to be drawn.

http://blogs.msdn.com/b/shawnhar/archive/2006/12/13/spritebatch-and-spritesortmode.aspx
http://blogs.msdn.com/b/shawnhar/archive/2006/12/14/spritebatch-sorting-part-2.aspx
http://blogs.msdn.com/b/shawnhar/archive/2006/12/14/return-of-the-spritebatch-sorting-part-3.aspx
http://blogs.msdn.com/b/shawnhar/archive/2010/04/05/spritesortmode-immediate-in-xna-game-studio-4-0.aspx

Alpha blending

Alpha blending defaults to using premultiplied alpha. To make use of 'straight' alpha textures, provide a blend state object to Begin.

CommonStates states(device);

spriteBatch->Begin(SpriteSortMode_Deferred, states.NonPremultiplied() );

Note: If you need to provide custom blend factors or sample mask, use the setCustomShaders callback to call the device context's OMSetBlendState directly instead.

Custom render states

By default SpriteBatch uses premultiplied alpha blending, no depth buffer, counter clockwise culling, and linear filtering with clamp texture addressing. You can change this by passing custom state objects to SpriteBatch::Begin. Pass null for any parameters that should use their default value.

spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, nullptr, [=]
{
    deviceContext->...
});

Custom pixel shaders

To use SpriteBatch with a custom pixel shader (handy for 2D postprocessing effects such as bloom or blur), use the setCustomShaders parameter to specify a state setting callback function:

spriteBatch->Begin(SpriteSortMode_Immediate, nullptr, nullptr, nullptr, nullptr, [=]
{
    deviceContext->PSSetShader(...);
    deviceContext->PSSetConstantBuffers(...);
    deviceContext->PSSetShaderResources(...);
});

SpriteBatch automatically sets pixel shader resource #0 and sampler slot 0 for the texture specified by each Draw call, so you only need to call PSSetResources for any additional textures required by your shader.

To write a custom sprite batch pixel shader in HLSL, make sure it matches the following signature

Texture2D<float4> Texture : register(t0);
sampler TextureSampler : register(s0);

float4 MySpritePixelShader(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : SV_Target0
{
    // TODO
}

Custom vertex shaders

To use a custom vertex shader with SpriteBatch, you'll need to create an input layout for your shader that uses VertexPositionColorTexture.
  • The vertex position x, y coordinates are generated from position, rotation, origin, and scale SpriteBatch::Draw parameters.
  • The vertex position z coordinate is the layerDepth SpriteBatch::Draw parameter, which defaults to 0.
  • The vertex u, v coordinates are generated.
  • The vertex color is the tint color SpriteBatch::Draw parameter, which defaults to White (1,1,1,1).
Here's an example using Effects.

voidconst* shaderByteCode;
size_t byteCodeLength;

effect->GetVertexShaderBytecode(&shaderByteCode, &byteCodeLength);

device->CreateInputLayout(VertexPositionColorTexture::InputElements,
                          VertexPositionColorTexture::InputElementCount,
                          shaderByteCode, byteCodeLength,
                          pInputLayout);

spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, nullptr, [=]
{
    effect->Apply( deviceContext );
    deviceContext->IASetInputLayout( pInputLayout );
});

Remember that the pixel shader input signature must match the vertex shader output signature, so it's easiest to provide both if you are going to override the standard sprite vertex shader.

Custom transform

SpriteBatch::Begin also has a transformMatrix parameter, which can be used for global transforms such as scaling or translation of an entire scene. It otherwise defaults to matrix identity.

XMMATRIX matrix = ...;
spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, nullptr, nullptr, matrix );

This transformation parameter only works if you are using the standard sprite batch vertex shader.

The full transformation depends on the orientation setting and/or the viewport setting for the device. The viewport is obtained from the SpriteBatch::SetViewport method or by calling RSGetViewports on the current context, and then used to construct a view matrix based on the setting provided by theSpriteBatch::SetRotation method.

// DXGI_MODE_ROTATION_ROTATE90
finalMatrix =
    matrix * XMMATRIX(0, -yScale, 0, 0, -xScale, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);

// DXGI_MODE_ROTATION_ROTATE270
finalMatrix =
    matrix * XMMATRIX(0, yScale, 0, 0, xScale, 0, 0, 0, 0, 0, 1, 0, -1, -1, 0, 1);

//DXGI_MODE_ROTATION_ROTATE180
finalMatrix =
    matrix * XMMATRIX(-xScale, 0, 0, 0, 0, yScale, 0, 0, 0, 0, 1, 0, 1, -1, 0, 1);

// DXGI_MODE_ROTATION_IDENTITY (the default)
finalMatrix =
    matrix * XMMATRIX(xScale, 0, 0, 0, 0, -yScale, 0, 0, 0, 0, 1, 0, -1, 1, 0, 1);

// DXGI_MODE_ROTATION_UNSPECIFIED
finalMatrix = matrix;

Custom clipping

If custom clipping of the sprites is desired (such as clipping font strings), you can achieve this by first creating a custom raster state with scissor rectangle culling enabled:

ID3D11RasterizerState* scissorState;
CD3D11_RASTERIZER_DESC rsDesc(D3D11_FILL_SOLID, D3D11_CULL_BACK, FALSE, 0, 0.f, 0.f, TRUE, TRUE, TRUE, FALSE);
if (FAILED(device->CreateRasterizerState(&rsDesc, &scissorState)))
    // error

Then when you call Begin() provide a custom callback to set the scissor rectangle:

spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, scissorState,
    [&]()
    {
        CD3D11_RECT r( /* pixel rectangle coordinates here */);
        context->RSSetScissorRects(1, &r);
    });

Applications

The same set of techniques that were used with XNA Game Studio's SpriteBatch can be adapted to the DirectXTK implementation.

http://msdn.microsoft.com/en-us/library/ff634505.aspx

Animated sprites

The AnimatedTexture class demonstrates drawing an animated sprite as discussed in this C# tutorial. http://msdn.microsoft.com/en-us/library/bb203866.aspx

Scrolling background

The ScrollingBackground class demonstrates drawing a scrolling background as discussed in this C# tutorial.
http://msdn.microsoft.com/en-us/library/bb203868.aspx

Sprite Sheet

The SpriteSheet class demonstrates drawing sprites from a sprite sheet (aka "texture atlas") to more efficiently use texture memory.

Post processing effects

The techniques described here for XNA Game Studio will work with the C++ SpriteBatch.

http://blogs.msdn.com/b/shawnhar/archive/2012/01/19/bloom-on-windows-phone.aspx
http://www.catalinzima.com/2012/10/postprocessing-effects-on-wp7-part-i/
http://www.catalinzima.com/2012/10/postprocessing-effects-on-wp7-part-ii/
http://www.catalinzima.com/2012/10/postprocessing-effects-on-wp7-part-iii/

Normal-mapped sprites

The techniques described here for XNA Game Studio also work with the C++ SpriteBatch.

http://xbox.create.msdn.com/en-US/education/catalog/sample/sprite_effects

Feature Level Notes

The implementation in SpriteBatch uses dynamic vertex buffers with 4 vertices per sprite, which works on all feature levels. The submission maximum batch size (2048) is within the limits of Feature Level 9.1's requirement to use 16-bit indices (DXGI_FORMAT_R16_UINT) and the maximum primitives per batch limit of 65535. This is robust and works well for the typical scale of usage for sprite batch.

For more extreme usage scenarios (large particle systems, star fields, etc.), writing a custom sprite implementation is likely the better solution over using SpriteBatch. With Feature Level 9.3, you can make use of instancing, and on Feature Level 10.0+ you can make use of the geometry shader to implement point-sprites.
http://code.msdn.microsoft.com/Direct3D-sprite-sample-2db07382

Threading model

Creation is fully asynchronous, so you can instantiate multiple SpriteBatch instances at the same time on different threads. Each SpriteBatch instance only supports drawing from one thread at a time, but you can simultaneously submit sprites on multiple threads if you create a separate SpriteBatch instance per Direct3D 11 deferred context.
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476892.aspx

Orientation

For phones, laptops, and tablets the orientation of the display can be changed by the user. For Windows Store apps, DirectX applications are encouraged to handle the rotation internally rather than relying on DXGI's auto-rotation handling.

In older versions of DirectXTK, you had to handle orientation changes via the custom transform matrix on Begin(). In the latest version of DirectXTK, you can handle it via a rotation setting (which is applied after any custom transformation).

Windows Store apps for Windows 8

Using the DirectX starting template, you will want to add to your CreateWindowSizeDependentResources() method:

DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
switch (m_orientation)
{
case DisplayOrientations::Landscape: rotation = DXGI_MODE_ROTATION_IDENTITY;  break;
case DisplayOrientations::Portrait: rotation = DXGI_MODE_ROTATION_ROTATE270; break;
case DisplayOrientations::LandscapeFlipped: rotation = DXGI_MODE_ROTATION_ROTATE180; break;
case DisplayOrientations::PortraitFlipped: rotation = DXGI_MODE_ROTATION_ROTATE90; break;
}
spriteBatch->SetRotation( rotation );

Windows phone 8

For Windows phone 8.0 applications, you do something very similar to Windows Store apps for Windows 8, although you will need to add the support to the DirectX template as described in this post
http://www.catalinzima.com/2012/12/handling-orientation-in-a-windows-phone-8-game/

DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
switch (m_orientation)
{
case DisplayOrientations::Portrait: rotation = DXGI_MODE_ROTATION_IDENTITY;  break;
case DisplayOrientations::Landscape: rotation = DXGI_MODE_ROTATION_ROTATE90; break;
case DisplayOrientations::PortraitFlipped: rotation = DXGI_MODE_ROTATION_ROTATE180; break;
case DisplayOrientations::LandscapeFlipped: rotation = DXGI_MODE_ROTATION_ROTATE270; break;
}
spriteBatch->SetRotation( rotation );

Windows Store apps for Windows 8.1

Using the DirectX starting template, you will want to add to your CreateWindowSizeDependentResources() method:

spriteBatch->SetRotation( m_deviceResources->ComputeDisplayRotation() );

In Common\DeviceResources.h, you need to make ComputeDisplayRotation() a public function instead of being private.

Further reading

http://www.shawnhargreaves.com/blogindex.html#spritebatch
http://blogs.msdn.com/b/shawnhar/archive/2010/06/18/spritebatch-and-renderstates-in-xna-game-studio-4-0.aspx
http://www.shawnhargreaves.com/blogindex.html#premultipliedalpha
https://directxtk.codeplex.com/wikipage?action=Edit&title=SpriteBatch&referringTitle=Sprites%20and%20textures

Updated Wiki: SpriteFont

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a native Direct3D 11 implementation of a bitmap font renderer, similar to the SpriteFont type from XNA Game Studio, plus a command line tool (MakeSpriteFont) for building fonts into bitmap format. It is less fully featured than Direct2D and DirectWrite, but may be useful for those who want something simpler and lighter weight.

SpriteFont is particularly useful for the Windows phone 8.0 and Xbox One XDK platforms that lack support for Direct2D and DirectWrite

SpriteFontExample.jpg

Related tutorial:Drawing text

Header

#include <SpriteFont.h>

Initialization

The SpriteFont class requires a SpriteBatch instance and a .spritefont bitmap file.

std::unique_ptr<SpriteBatch> spriteBatch(new SpriteBatch(deviceContext));
std::unique_ptr<SpriteFont> spriteFont(new SpriteFont(device, L"myfile.spritefont"));
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr or std::shared_ptr

Simple drawing

spriteBatch->Begin();
spriteFont->DrawString(spriteBatch.get(), L"Hello, world!", XMFLOAT2(x, y));
spriteBatch->End();
The DrawString method has several overloads with parameters controlling color, rotation, origin point, scaling, horizontal or vertical mirroring, and layer depth. These work the same way as the equivalent SpriteBatch::Draw parameters.

Constructors

SpriteFont has three constructors:
  • Pass a filename string to read a binary file created by MakeSpriteFont
  • Pass a buffer containing a MakeSpriteFont binary that was already loaded some other way
  • Pass an array of Glyph structs if you prefer to entirely bypass MakeSpriteFont

Helpers

In addition to DrawString with various overloads, SpriteFont includes the following helpers:
  • MeasureString which returns the size of the given string in pixels.
Note: The string size is computed from the origin to the rightmost pixel rendered by any character glyph. This has the effect of ignoring 'trailing spaces'. See work item 674 for more details. https://directxtk.codeplex.com/workitem/674.
  • ContainsCharacter tests to see if a given character is defined in the font
  • FindGlyph can be used to obtain size and other metadata for a character in the font. Note if the character is not defined in the font and there is no default character, this function will throw a C++ exception.
  • GetSpriteSheet returns a reference to the texture used for the sprite font for custom rendering.

Default character

If you try to draw or call MeasureString with a character that is not included in the font, by default you will get an exception. Use SetDefaultCharacter to specify some other character that will be automatically substituted in place of any that are missing. You can also use GetDefaultCharacter to obtain the current default which is also defined as part of the font.

Special characters

SpriteFont will respect new line characters (\n - ASCII character 10), and ignores carriage returns (\r - ASCII character 13). The distance moved for a new line is defined in the font and can be accessed with GetLineSpacing / SetLineSpacing.

There is no special handling for the bell character (\a - ASCII character 7), backspace (\b - ASCII character 8), horizontal tab (\t - ASCII character 9), vertical tab (ASCII character 11), form feed (\f - ASCII character 12), or escape (ASCII character 27). These are all treated as standard characters and if it is missing from the .spritefont, they will all render as the default character or generate an exception if there is no default character defined

Localization

This implementation supports sparse fonts, so if you are localizing into languages such as Chinese, Japanese, or Korean, you can build a spritefont including only the specific characters needed by your program. This is usually a good idea for CJK languages, as a complete CJK character set is too large to fit in a Direct3D texture! If you need full CJK support, DrectWrite would be a better choice if available on your target platform. SpriteFont does not support combining characters or right-to-left (RTL) layout, so it will not work for languages with complex layout requirements such as Arabic or Thai.

ASCII

The default character region for MakeSpriteFont from 32 to 127 covers the standard 7-bit range. For example, here is a C++ Unicode string for the printable characters (this would be an ASCII string if you remove the L prefix).

L" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmn
opqrstuvwxyz{|}~"

http://ascii-table.com/ascii.php

Extended ASCII

If you are wanting to render an 'extended ASCII' string with SpriteFont, you need to capture the full set of characters which are not contiguous in Unicode (see MakeSpriteFont for details). You then need to convert your 'extended ASCII' string to Unicode using Code page 437 before calling DrawString.

char ascii[...];
wchar_t unicode[...];
if (!MultiByteToWideChar(437, MB_PRECOMPOSED,
    ascii, length-of-ascii-string,
    unicode, length-of-unicode-string))
{
    // Error
}
spriteFont->DrawString(spriteBatch.get(), unicode, ...)

For example, here is a C++ Unicode string with the full extended ASCII IBM PC character set from 128 to 255:

L"\x00C7\x00FC\x00E9\x00E2\x00E4\x00E0\x00E5\x00E7\x00EA
\x00EB\x00E8\x00EF\x00EE\x00EC\x00C4\x00C5\x00C9\x00E6\x00C6\x00F4\x00F6\x00F2\x
00FB\x00F9\x00FF\x00D6\x00DC\x00A2\x00A3\x00A5\x20A7\x0192\x00E1\x00ED\x00F3\x00
FA\x00F1\x00D1\x00AA\x00BA\x00BF\x2310\x00AC\x00BD\x00BC\x00A1\x00AB\x00BB\x2591
\x2592\x2593\x2502\x2524\x2561\x2562\x2556\x2555\x2563\x2551\x2557\x255D\x255C\x
255B\x2510\x2514\x2534\x252C\x251C\x2500\x253C\x255E\x255F\x255A\x2554\x2569\x25
66\x2560\x2550\x256C\x2567\x2568\x2564\x2565\x2559\x2558\x2552\x2553\x256B\x256A
\x2518\x250C\x2588\x2584\x258C\x2590\x2580\x03B1\x00DF\x0393\x03C0\x03A3\x03C3\x
00B5\x03C4\x03A6\x0398\x03A9\x03B4\x221E\x03C6\x03B5\x2229\x2261\x00B1\x2265\x22
64\x2320\x2321\x00F7\x2248\x00B0\x2219\x00B7\x221A\x207F\x00B2\x25A0\x00A0"

http://ascii-table.com/ascii-extended-pc-list.php
http://en.wikipedia.org/wiki/Code_page_437

Xbox One exclusive apps MultiByteToWideChar does not support codepage 437.

Feature Levels

The Sprite Font implementation is compatible with all feature levels. The primary limitation is on the size of the sprite sheet texture which should fit into the limits for known feature levels (i.e. to support all feature levels, it should be no larger than 2048 x 2048).

Further reading

http://blogs.msdn.com/b/shawnhar/archive/2007/04/26/bitmap-fonts-in-xna.aspx
http://blogs.msdn.com/b/shawnhar/archive/2011/01/12/spritebatch-billboards-in-a-3d-world.aspx

Updated Wiki: VertexTypes

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

The VertexTypes.h header defines these commonly used vertex data structures:
  • VertexPositionColor
  • VertexPositionTexture
  • VertexPositionNormal
  • VertexPositionColorTexture
  • VertexPositionNormalColor
  • VertexPositionNormalTexture
  • VertexPositionNormalColorTexture
  • VertexPositionNormalTangentColorTexture
  • VertexPositionNormalTangentColorTextureSkinning

Header

#include <VertexTypes.h>

Input Layout

Each type also provides a D3D11_INPUT_ELEMENT_DESC array which can be used to create a matching input layout, for example:

device->CreateInputLayout(VertexPositionColorTexture::InputElements,
                          VertexPositionColorTexture::InputElementCount,
                          vertexShaderCode, vertexShaderCodeSize,
                          &inputLayout);

Usage

Position (which uses the semantic "SV_Position") is required for all rendering. This is XMFLOAT3 (DXGI_FORMAT_R32G32B32_FLOAT).

Normal is required for any effect that supports lighting computations. This is XMFLOAT3 (DXGI_FORMAT_R32G32B32_FLOAT).

Color is for per-vertex coloring used by some effects. Color is typically XMFLOAT4(DXGI_FORMAT_R32G32B32A32_FLOAT).

Texture coordinates (which uses the semantic "TEXCOORD0") are XMFLOAT2 (DXGI_FORMAT_R32G32_FLOAT).

Visual Studio content pipeline

VertexPositionNormalTangentColorTexture contains the vertex elements needed for using Visual Studio Shader Designer (DGSL) shaders via DGSLEffect (which requires position, normal, tangent, color, and texture coordinates) and is used when loading .CMO file models. It defines Color as a uint32_t (DXGI_FORMAT_R8G8B8A8_UNORM)

VertexPositionNormalTangentColorTextureSkinning extends VertexPositionNormalTangentColorTexture with blend weights and indices for skinning using Visual Studio Shader Designer (DGSL) shaders via DGSLEffect and is used when loading .CMO file skinned models. It defines the blend indices as uint32_t (DXGI_FORMAT_R8G8B8A8_UINT) and the blend weights as uint32_t (DXGI_FORMAT_R8G8B8A8_UNORM).

DirectX SDK SDKMESH

The SDKMESH format describes input layouts as Direct3D 9 style vertex decls. There is therefore no specific vertex structure for SDKMESH data and such input layouts are built on-the-fly.

Updated Wiki: WICTextureLoader

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

A Direct3D 11 2D texture loader that uses WIC to load a bitmap (BMP, JPEG, PNG, TIFF, GIF, HD Photo, or other WIC supported file container), resize if needed based on the current feature level (or by explicit parameter), format convert to a standard DXGI format if required, and then create a 2D texture. Furthermore, if a Direct3D 11 device context is provided and the current device supports it for the given pixel format, it will auto-generate mipmaps.

This loader does not support array textures, 1D textures, 3D volume textures, or cubemaps. For these scenarios, use the .DDS file format and DDSTextureLoader instead.

NOTE: WICTextureLoader is not supported on Windows Phone 8.0, because WIC is not available on that platform

DDSTextureLoader is recommended for fully "precooked" textures for maximum performance and image quality, but this loader can be useful for creating simple 2D texture from standard image files at runtime.

Also part of DirectXTex http://go.microsoft.com/fwlink/?LinkId=248926

The module assumes that the client code will have already called CoInitialize, CoInitializeEx, or Windows::Foundation::Initialize as needed by the application before calling the WIC loader routines

Related tutorial:Sprites and textures

Header

#include <WICTextureLoader.h>

Functions

CreateWICTextureFromMemory
Loads a WIC-supported bitmap file from a memory buffer. It creates a Direct3D 11 resource from it, and optionally a Direct3D 11 shader resource view.

HRESULT CreateWICTextureFromMemory( _In_ ID3D11Device* d3dDevice,
   _In_reads_bytes_(wicDataSize) const uint8_t* wicData, _In_ size_t wicDataSize,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView,
   _In_ size_t maxsize = 0 );

HRESULT CreateWICTextureFromMemory( _In_ ID3D11Device* d3dDevice,
   _In_opt_ ID3D11DeviceContext* d3dContext,
   _In_reads_bytes_(wicDataSize) const uint8_t* wicData, _In_ size_t wicDataSize,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView,
   _In_ size_t maxsize = 0 );

CreateWICTextureFromFile
Loads a WIC-supported bitmap file from disk, creates a Direct3D 11 resource from it, and optionally a Direct3D 11 shader resource view.

HRESULT CreateWICTextureFromFile( _In_ ID3D11Device* d3dDevice,
   _In_z_ constwchar_t* szFileName,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView,
   _In_ size_t maxsize = 0 );

HRESULT CreateWICTextureFromFile( _In_ ID3D11Device* d3dDevice,
   _In_opt_ ID3D11DeviceContext* d3dContext,
   _In_z_ constwchar_t* szFileName,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView,
   _In_ size_t maxsize = 0 );

CreateWICTextureFromMemoryEx
CreateWICTextureFromFileEx
These versions provide explicit control over the created resource's usage, binding flags, CPU access flags, and miscellaneous flags for advanced / expert scenarios. The standard routines default to D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, and 0 respectively. For auto-gen mipmaps, the default binding flags are D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET and miscellaneous flags is set to D3D11_RESOURCE_MISC_GENERATE_MIPS. There is also a 'forceSRGB' option for working around gamma issues with content that is in the sRGB or similar color space but is not encoded explicitly as an SRGB format.

HRESULT CreateWICTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
   _In_reads_bytes_(wicDataSize) const uint8_t* wicData, _In_ size_t wicDataSize,
   _In_ size_t maxsize,
   _In_ D3D11_USAGE usage, _In_ unsignedint bindFlags,
   _In_ unsignedint cpuAccessFlags, _In_ unsignedint miscFlags,
   _In_ bool forceSRGB,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView );

HRESULT CreateWICTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
   _In_opt_ ID3D11DeviceContext* d3dContext,
   _In_reads_bytes_(wicDataSize) const uint8_t* wicData, _In_ size_t wicDataSize,
   _In_ size_t maxsize,
   _In_ D3D11_USAGE usage, _In_ unsignedint bindFlags,
   _In_ unsignedint cpuAccessFlags, _In_ unsignedint miscFlags,
   _In_ bool forceSRGB,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView );

HRESULT CreateWICTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
   _In_z_ constwchar_t* szFileName,
   _In_ size_t maxsize,
   _In_ D3D11_USAGE usage, _In_ unsignedint bindFlags,
   _In_ unsignedint cpuAccessFlags, _In_ unsignedint miscFlags,
   _In_ bool forceSRGB,
   _Out_opt_ ID3D11Resource** texture, _Out_opt_ ID3D11ShaderResourceView** textureView );

HRESULT CreateWICTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
   _In_opt_ ID3D11DeviceContext* d3dContext,
   _In_z_ constwchar_t* szFileName,
   _In_ size_t maxsize,
   _In_ D3D11_USAGE usage, _In_ unsignedint bindFlags,
   _In_ unsignedint cpuAccessFlags, _In_ unsignedint miscFlags,
   _In_ bool forceSRGB,
   _Out_opt_ ID3D11Resource** texture,
   _Out_opt_ ID3D11ShaderResourceView** textureView );

Parameters

For all these functions above, the maxsize parameter provides an upper limit on the size of the resulting texture. If given a 0, the functions assume a maximum size determined from the device's current feature level. If the bitmap file contains a larger image, it will be resized using WIC at load-time to provide scaling.

If a d3dContext is given to these functions, they will attempt to use the auto-generation of mipmaps features in the Direct3D 11 API if supported for the pixel format. Note the quality of auto-gen mipmaps is up to the driver, so can vary widely. Also if a context is passed, the function is not thread safe.

Example

This example creates a shader resource view on the ID3D11Device d3dDevice which can be used for rendering. It also makes use of the immediate ID3D11DeviceContext immContext to auto-gen mipmaps if supported.

usingnamespace DirectX;
usingnamespace Microsoft::WRL;

ComPtr<ID3D11ShaderResourceView> srv;
HRESULT hr = CreateWICTextureFromFile( d3dDevice.Get(), immContext.Get(), L"LOGO.BMP",
     nullptr, srv.GetAddressOf() );
DX::ThrowIfFailed(hr);

Release Notes

  • On a system with the DirectX 11.0 Runtime or lacking WDDM 1.2 drivers, 16bpp pixel formats will be converted to a RGBA 32-bit format.
  • WICTextureLoader cannot load .TGA files unless the system has a 3rd party WIC codec installed. You must use the DirectXTex library for TGA file format support without relying on an add-on WIC codec.
  • While there is no explicit 'sRGB' pixel format defined for WIC, the load function will check for known metadata tags and may return DXGI_FORMAT_*_SRGB formats if there are equivalents of the same size and channel configuration available.

Implementation Details

  • The conversion tables are designed so that they prefer to convert to RGB if a conversion is required as a general preferance for DXGI 1.0 supporting formats supported by WDDM 1.0 drivers. The majority of Direct3D 11 devices actually support BGR DXGI 1.1 formats so we use them when they are the best match. For example, GUID_WICPixelFormat32bppBGRA loads directly as DXGI_FORMAT_B8G8R8A8_UNORM, but GUID_WICPixelFormat32bppPBGRA converts to DXGI_FORMAT_R8G8B8A8_UNORM.
  • GUID_WICPixelFormatBlackWhite is always converted to a greyscale DXGI_FORMAT_R8_UNORM since DXGI_FORMAT_R1_UNORM is not supported by Direct3D 10.x/11.x.
  • GUID_WICPixelFormat32bppRGBE is an 8:8:8:8 format, which does not match DXGI_FORMAT_R9G9B9E5_SHAREDEXP. This WIC pixel format is therefore converted to GUID_WICPixelFormat128bppRGBAFloat and returns as DXGI_FORMAT_R32G32B32A32_FLOAT.

WIC2

WIC2 is available on Windows 8 and on Windows 7 Service Pack 1 with KB 2670838 installed.
  • If WIC2 is supported, then it will load the new WIC pixel format GUID_WICPixelFormat96bppRGBFloat directly as DXGI_FORMAT_R32G32B32_FLOAT. Otherwise the module converts this to DXGI_FORMAT_R32G32B32A32_FLOAT.
  • If WIC2 is supported, then it will include conversions cases for the new WIC pixel formats GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat64bppRGB, and GUID_WICPixelFormat64bppPRGBAHalf.
  • If WIC2 is supported, then it will convert the WIC pixel format GUID_WICPixelFormat96bppRGBFixedPoint to DXGI_FORMAT_R32G32B32_FLOAT. There is special-case handling so that if auto-gen mips fails for this format (this is optional support for Feature Level 10.0 or later devices), it will use DXGI_FORMAT_R32G32B32A32_FLOAT instead (which has required support for Feature Level 10.0 or later devices).
http://support.microsoft.com/kb/2670838

Windows Store apps

The texture loader function is typically used to load texture files from the application's install folder as they were included with the AppX package. If you wish to create a texture from a file that is specified by the user from a WinRT picker, you will need to copy the file locally to a temporary location before you can use WICTextureLoader on it. This is because you either won't have file access rights to the user's file location, or the StorageFile is actually not a local file system path (i.e. it's a URL).

#include <ppltasks.h>
usingnamespace concurrency;

using Windows::Storage;
using Windows::Storage::Pickers;

create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
    if (file)
    {
        auto tempFolder = Windows::Storage::ApplicationData::Current->TemporaryFolder;
        create_task(file->CopyAsync( tempFolder, file->Name, NameCollisionOption::GenerateUniqueName )).then([this](StorageFile^ tempFile)
        {
            if ( tempFile )
            {
                HRESULT hr = CreateWICTextureFromFile( ..., tempFile->Path->Data(), ... );
                DX::ThrowIfFailed(hr);
            }
        });
    });

https://msdn.microsoft.com/en-us/library/windows/apps/hh967755.aspx

Further reading

http://filmicgames.com/archives/299
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch24.html

Updated Wiki: XboxDDSTextureLoader

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a version of DDSTextureLoader for use by Xbox One XDK developers. This loads pre-tiled texture resources for use with the CreatePlacement APIs available to Xbox One exclusive app developers.

These pre-tiled resources are stored in a variant of the .DDS file format marked with the "XBOX" FourCC pixel format. To generate these .DDS files, see the xtexconv sample on the Microsoft Game Developer Network site https://developer.xboxlive.com/en-us/platform/development/education/Pages/Samples.aspx.

To load traditional or FourCC "DX10" variant DDS files, use DDSTextureLoader

Header

#include <XboxDDSTextureLoader.h>

Functions

These are in the 'Xbox' namespace rather than 'DirectX'

CreateDDSTextureFromMemory
CreateDDSTextureFromFile
These are equivalent to the same functions in DDSTextureLoader, but also require a ID3DXboxPerformanceDevice interface and return a pointer to the video memory via grfxMemory which the caller is responsible for releasing with D3DFreeGraphicsMemory

HRESULT CreateDDSTextureFromMemory( _In_ ID3D11DeviceX* d3dDevice,
    _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, _In_ size_t ddsDataSize,
    _Outptr_opt_ ID3D11Resource** texture,
    _Outptr_opt_ ID3D11ShaderResourceView** textureView,
    _Outptr_ void** grfxMemory,
    _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, 
    _In_ bool forceSRGB = false );

HRESULT CreateDDSTextureFromFile( _In_ ID3D11DeviceX* d3dDevice,
    _In_z_ constwchar_t* szFileName,
    _Outptr_opt_ ID3D11Resource** texture,
    _Outptr_opt_ ID3D11ShaderResourceView** textureView,
    _Outptr_ void** grfxMemory,
    _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr,
    _In_ bool forceSRGB = false );

Example

usingnamespace Microsoft::WRL;

ComPtr<ID3D11ShaderResourceView> srv;

void *grfxMemory = nullptr;
HRESULT hr = Xbox::CreateDDSTextureFromFile( m_device.Get(),
    L"XboxTiledTexturedds", nullptr,
    srv.GetAddressOf(), &grfxMemory );
DX::ThrowIfFailed( hr );

DDS File Format

This function expects the DDS file to contain a pixel format with FourCC "XBOX" which signifies a specific variant of the file.

DWORD dwMagic
DDS_HEADER header
DDS_HEADER_XBOX
{
    DXGI_FORMAT dxgiFormat;
    uint32_t    resourceDimension;
    uint32_t    miscFlag; // see DDS_RESOURCE_MISC_FLAG
    uint32_t    arraySize;
    uint32_t    miscFlags2; // see DDS_MISC_FLAGS2
    uint32_t    tileMode; // see XG_TILE_MODE
    uint32_t    baseAlignment;
    uint32_t    dataSize;
    uint32_t    xdkVer; // matching _XDK_VER
} headerXbox
// Remainder of file is a tiled texture binary layout suitable for use with CreatePlacement APIs

Other DDS loaders and viewers will fail to recognize this pixel format, and other DDS creation tools do not support creating it. See the xtexconv sample for more information on creating this variant form of DDS files.

http://msdn.microsoft.com/en-us/library/windows/desktop/bb943990.aspx

Updated Wiki: MakeSpriteFont

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/MakeSpriteFont

The MakeSpriteFont tool can process any TrueType font that is installed on your system (using GDI+ to rasterize them into a bitmap) or it can import character glyphs from a specially formatted bitmap file. This latter option allows you to create multicolored fonts, drawing special effects such as gradients or drop shadows directly into your glyph textures.

See SpriteFont

Note: The command-line tools in the DirectXTK package are only built by the DirectXTK_Desktop_201x solutions since they are Win32 desktop applications. You can also obtain them as a pre-built binary from the download page as Other available downloads.

Related tutorial:Drawing text

TrueType

Open a Command Prompt, and change to the directory containing MakeSpriteFont.exe (i.e. ...\DirectXTK\MakeSpriteFont\bin\Release)
http://windows.microsoft.com/en-us/windows/command-prompt-faq

Enter the following command-line after changing to the appropriate directory:
MakeSpriteFont "Comic Sans" myfile.spritefont /FontSize:16

The file myfile.spritefont is generated from the installed TrueType font.

You can also use the Bitmap Font Maker tool to capture a TrueType font as a BMP, then edit the image before using it to create a spritefont via the Bitmap import procedure below
http://xbox.create.msdn.com/en-US/education/catalog/utility/bitmap_font_maker

Bitmap Import

For importing the font from a bitmap file, characters should be arranged in a grid ordered from top left to bottom right. Monochrome fonts should use white for solid areas and black for transparent areas. To include multicolored characters, add an alpha channel to the bitmap and use that to control which parts of each character are solid. The spaces between characters and around the edges of the grid should be filled with bright pink (red=255, green=0, blue=255). It doesn't matter if your grid includes lots of wasted space, because the converter will rearrange characters, packing everything as tightly as possible.

For example, this is the sprite font for the Xbox 360 Common Controller buttons.

xboxControllerSpriteFont.png

Open a Command Prompt, and change to the directory containing MakeSpriteFont.exe (i.e. ...\DirectXTK\MakeSpriteFont\bin\Release)
http://windows.microsoft.com/en-us/windows/command-prompt-faq

Enter the following command-line after changing to the appropriate directory
MakeSpriteFont xboxControllerSpriteFont.png xboxController.spritefont

The file xboxController.spritefont is generated from the xboxControllerSpriteFont.png image.

Note: The MakeSpriteFont tool only supports importing from .bmp, .png, or .gif images. If you are using a .tga source file, then you use should DirectXTex's texconv utility to convert it:
texconv -ft PNG originalSpriteFont.tga 

Commandline options

/CharacterRegion:<region>
Specifies which Unicode codepoints to include in the font. Can be repeated to include more than one region. If not specified, the default ASCII range (32 [space]-126 [~]) is used. Examples:
/CharacterRegion:a-z
/CharacterRegion:0x1200-0x1250
/CharacterRegion:0x1234
/DefaultCharacter:<value>
Fallback character substituted in place of codepoints that are not included in the font. If zero, missing characters throw exceptions.
/FontSize:<value>
/FontStyle:<value>
Size and style (bold or italic) for TrueType fonts. Ignored when converting a bitmap font.
/LineSpacing:<value>
/CharacterSpacing:<value>
Spacing overrides. Zero is default spacing, negative closer together, positive further apart.
/Sharp
Selects sharp antialiasing mode for TrueType rasterization. Otherwise a smoother looking (but more blurry) antialiasing mode is used.
/TextureFormat:<value>
What format should the output texture be? Options:
Auto - The default. Chooses between CompressedMono and Rgba32 depending on whether the font data is monochromatic or multicolored.
Rgba32 - High quality and supports multicolored fonts, but wastes space.
Bgra4444 - Good choice for color fonts on Windows Store apps and Windows Phone platforms, as this format requires the DirectX 11.1 Runtime and a WDDM 1.2 driver.
CompressedMono - The smallest format, and works on all D3D platforms, but it only supports monochromatic font data. This uses a special BC2 encoder: see comments in SpriteFontWriter.cs for details.
/NoPremultiply
By default, font textures use premultiplied alpha format. Pass this flag if you want interpolative/straight alpha instead.
/DebugOutputSpriteSheet:<filename>
Dumps the generated texture to a bitmap file (useful when debugging the MakeSpriteFont tool, not so much if you are just trying to use it).

Localization

Since all glyphs specified are captured into a texture, the SpriteFont solution is very effective for smaller character sets. For large character sets such as Chinese, Japanese, or Korean, capturing every possible glyph is extremely slow, and the resulting image is extremely large. For these large character sets, using DirectWrite to render glyphs on-the-fly is a better solution.

For cases where DirectWrite is not supported (such as Windows phone 8.0 and Xbox One exclusive apps) and/or when rendering a set of static localized text, another solution is to scan all your translated text and capture only those character regions actually used by your application's specific display strings.

Extended ASCII

If you are wanting to render an 'extended ASCII' string with SpriteFont, you need to capture the full set of characters which are not contiguous in Unicode.

MakeSpriteFont "Consolas" /characterregion:0x0-0xFF
/characterregion:0x192 /characterregion:0x393 /characterregion:0x398
/characterregion:0x3A3 /characterregion:0x3A6 /characterregion:0x3A9
/characterregion:0x3B1 /characterregion:0x3B4-0x3B5 /characterregion:0x3C0
/characterregion:0x3C3-0x3C6 /characterregion:0x207F /characterregion:0x20A7
/characterregion:0x2219 /characterregion:0x221A /characterregion:0x221E
/characterregion:0x2229 /characterregion:0x2248 /characterregion:0x2261
/characterregion:0x2264-0x2265 /characterregion:0x2310 /characterregion:0x2320
/characterregion:0x2321 /characterregion:0x2500 /characterregion:0x2502
/characterregion:0x250C /characterregion:0x2510 /characterregion:0x2514
/characterregion:0x2518 /characterregion:0x251C /characterregion:0x2524
/characterregion:0x252C /characterregion:0x2534 /characterregion:0x253C
/characterregion:0x2550-0x256C /characterregion:0x2580 /characterregion:0x2584
/characterregion:0x2588 /characterregion:0x258C /characterregion:0x2590-0x2593
/characterregion:0x25A0 consolas.spritefont

http://ascii-table.com/ascii-extended-pc-list.php

Feature Levels

The MakeSpriteFont tool will generate warnings if the resulting sprite sheet texture is too large for the texture sizes mandated for a known Direct3D feature level (i.e., 2048 x 2048 for 9.1 and 9.2; 4096 x 4096 for 9.3; 8192 x 8192 for 10.x; and 16384 x 16384 for 11.x).

Further reading

http://xbox.create.msdn.com/en-US/education/catalog/sample/localization
http://en.wikipedia.org/wiki/Knapsack_problem

Updated Wiki: XWBTool

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/XWBTool

The XWBTool is a command-line utility for for building XACT-style wave banks for use with the DirectXTK for Audio Wave Bank class.

See Audio, WaveBank

Note: The command-line tools in the DirectXTK package are only built by the DirectXTK_Desktop_201x solutions since they are Win32 desktop applications. You can also obtain them as a pre-built binary from the download page as Other available downloads.

Example usage

Open a Command Prompt, and change to the directory containing XWBTool.exe (i.e. ...\DirectXTK\XWBTool\bin\Release)
http://windows.microsoft.com/en-us/windows/command-prompt-faq

Enter the following command-line after changing to the appropriate directory:
xwbtool -o wavebank.xwb Sound.wav Explosion.wav Music.wav

The file wavebank.xwb is generated from the three input .wav files.

Options

-s
Creates as streaming wave bank, otherwise defaults to in-memory wave bank
-o <filename>
Sets output filename for .xwb file. Otherwise, it defaults to the same base name as the first input .wav file
-h <h-filename>
Generates a C/C++ header file with #defines for each of the sounds in the bank matched to their index
-n
Disables the default warning of overwriting an existing .xwb file
-c / -nc
Forces creation or prevents use of compact wave banks. By default, it will try to use a compact wave bank if possible.
-f
Includes entry friendly name strings in the wave bank for use with 'string' based versions of WaveBank::Play() and WaveBank::CreateInstance() rather than index-based versions.

Wave bank types

XACT-style wave banks come in two forms: in-memory and streaming. The in-memory form is intended to have the whole wave bank loaded into memory at once for use. This allows wave banks to be organized by use and efficiently loaded with minimal memory fragmentation. For use with SoundEffectInstance and as one-shots with WaveBank's Play method, use the in-memory form.

The streaming form is laid out such that each individual wave in the bank is aligned to 4K boundaries for use with async I/O. Only the metadata is loaded into memory, with all the wave data read on-demand from the remainder of the file. See the XAudio2AsyncStream sample code on MSDN Code Gallery for an example of using the streaming wave bank form. http://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933

Compact wave banks

XACT-style wave banks store meta-data in two forms: standard and compact. In the standard form, the wave-bank metadata is written using a 24-byte record per wave in the bank. In the compact form, they only requires 4-bytes per record. The Compact form requires that all waves in the bank have the same format, and the overall size of the bank's wave data must be less than 8,388,604 (~8 MB) for in-memory wave banks, or 268,433,408 bytes (~256 MBs) for streaming wave banks.

XWBTool will attempt to create a compact wave bank if the input .wav files allow, otherwise it will use the standard form. The -c and -nc commandline options override this behavior.

XACT3

The XACT3 GUI and/or the XACTBLD command-line tool in the legacy DirectX SDK (DirectX SDK) can be used to build .xwb wave banks that are compatible with DirectXTK for Audio if built for Windows (Little-endian) rather than Xbox 360 (Big-endian). XWBTool is just a simplified way to build them.

Endianness: DirectXTK for Audio does support loading Big-endian (aka Xbox 360) wave banks since those are the only kind that are generated when using the legacy tools with XMA compression when targeting the Xbox One XDK. This support is limited to XMA and 8-bit PCM data, however, as the wave data itself is not byte-swapped. XWBtool always builds Little-endian wave banks.

http://blogs.msdn.com/b/chuckw/archive/2011/12/09/known-issue-directx-sdk-june-2010-setup-and-the-s1023-error.aspx
http://support.microsoft.com/kb/2728613
http://msdn.microsoft.com/en-us/library/windows/desktop/ee663275.aspx
http://blogs.msdn.com/b/chuckw/archive/2012/03/22/where-is-the-directx-sdk.aspx
http://blogs.msdn.com/b/chuckw/archive/2013/07/01/where-is-the-directx-sdk-2013-edition.aspx

Compact wave banks: The legacy XACT3 ENGINE only supports 'streaming' compact wave banks not 'in-memory' compact wave banks. The XACT3 GUI / XACTBLD toolset will therefore only create 'standard' in-memory wave banks. There is also a known bug in the DirectX SDK (June 2010) version of the XACT3 GUI / XACTBLD toolsets that will not attempt to create a compact wave bank if the wave data size exceeds 2,097,151 (~2 MB).

Content support

XACT-style wave banks support 8-bit and 16-bit PCM (i.e. not 32-bit IEEE float PCM), ADPCM, xWMA, and XMA2 content.

To compress to ADPCM (a variant of MS-ADPCM) .wav files, use adpcmencode.exe from the Windows 8.x SDK, Xbox One ADK, Xbox One XDK, or legacy DirectX SDK.

To compress to xWMA .wav files, use xwmaencode.exe from the Xbox One ADK, Xbox One XDK, or legacy DirectX SDK.

To compress to XMA2 .wav files, use xma2encode.exe from the Xbox One XDK.

Note

This tool is also included in the XAudio2 Win32 desktop samples package.

http://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933

Updated Wiki: Mouse

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for simplified mouse tracking modeled after the XNA C# Mouse class.

Header

#include <Mouse.h>

Initialization

Mouse is a singleton.

std::unique_ptr<Mouse> mouse( new Mouse );
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr.

Integration

Windows desktop

The application needs to call SetWindow and make calls during the main WndProc message processing to ProcessMessage:

mouse->SetWindow(hWnd);

...

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_ACTIVATEAPP:
    case WM_INPUT:
    case WM_MOUSEMOVE:
    case WM_LBUTTONDOWN:
    case WM_LBUTTONUP:
    case WM_RBUTTONDOWN:
    case WM_RBUTTONUP:
    case WM_MBUTTONDOWN:
    case WM_MBUTTONUP:
    case WM_MOUSEWHEEL:
    case WM_XBUTTONDOWN:
    case WM_XBUTTONUP:
    case WM_MOUSEHOVER:
        Mouse::ProcessMessage(message, wParam, lParam);
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

Universal Windows apps, Windows Store apps

You need to call SetWindow and SetDpi in the appropriate places.

void App::SetWindow(CoreWindow^ window)
{
    mouse->SetWindow(window);
}

void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
{
    mouse->SetDpi(sender->LogicalDpi);
}

Basic use

GetState queries the current state of the mouse.

auto state = mouse->GetState();

if ( state.leftButton )
   // Left button is down

XMFLOAT2 mousePosInPixels( float(m.x), float(m.y) );
// This is the absolute position of the mouse relative// to the upper-left corner of the window

Button state tracker

A common pattern is to trigger an action when a mouse button is pressed or released, but you don't want to trigger the action every single frame if the button is held down for more than a single frame. This helper class simplifies this.

std::unique_ptr<Mouse::ButtonStateTracker> tracker( new Mouse::ButtonStateTracker );

...

auto state = mouse->GetState();
tracker->Update( state );

if ( tracker->rightButton == Mouse::ButtonStateTracker::PRESSED )
    // Take an action when Right mouse button is first pressed, but don't do// it again until the button is released and then pressed again

When resuming from a pause or suspend, be sure to call Reset on the tracker object to clear the state history.

Remark

The mouse scroll wheel value is accumulated. To reset the value to 0, use ResetScrollWheelValue.

Threading model

The Mouse class should be thread-safe with the exception of the ProcessMessage which should only be called in your windows message loop.

Platform notes

The Xbox One platform doesn't support pointer or mouse input devices.

For Windows Store, universal Windows apps, and Windows phone touch/pointer devices are captured as mouse movement.

Updated Wiki: Mouse

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for simplified mouse tracking modeled after the XNA C# Mouse class.

Header

#include <Mouse.h>

Initialization

Mouse is a singleton.

std::unique_ptr<Mouse> mouse( new Mouse );
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr.

Integration

Windows desktop

The application needs to call SetWindow and make calls during the main WndProc message processing to ProcessMessage:

mouse->SetWindow(hWnd);

...

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_ACTIVATEAPP:
    case WM_INPUT:
    case WM_MOUSEMOVE:
    case WM_LBUTTONDOWN:
    case WM_LBUTTONUP:
    case WM_RBUTTONDOWN:
    case WM_RBUTTONUP:
    case WM_MBUTTONDOWN:
    case WM_MBUTTONUP:
    case WM_MOUSEWHEEL:
    case WM_XBUTTONDOWN:
    case WM_XBUTTONUP:
    case WM_MOUSEHOVER:
        Mouse::ProcessMessage(message, wParam, lParam);
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

Universal Windows apps, Windows Store apps

You need to call SetWindow and SetDpi in the appropriate places.

void App::SetWindow(CoreWindow^ window)
{
    mouse->SetWindow(window);
}

void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
{
    mouse->SetDpi(sender->LogicalDpi);
}

Basic use

GetState queries the current state of the mouse.

auto state = mouse->GetState();

if ( state.leftButton )
   // Left button is down

XMFLOAT2 mousePosInPixels( float(m.x), float(m.y) );
// This is the absolute position of the mouse relative// to the upper-left corner of the window

Button state tracker

A common pattern is to trigger an action when a mouse button is pressed or released, but you don't want to trigger the action every single frame if the button is held down for more than a single frame. This helper class simplifies this.

std::unique_ptr<Mouse::ButtonStateTracker> tracker( new Mouse::ButtonStateTracker );

...

auto state = mouse->GetState();
tracker->Update( state );

if ( tracker->rightButton == Mouse::ButtonStateTracker::PRESSED )
    // Take an action when Right mouse button is first pressed, but don't do// it again until the button is released and then pressed again

When resuming from a pause or suspend, be sure to call Reset on the tracker object to clear the state history.

Absolute vs. Relative Mouse position

By default, the mouse state is returned as a absolute pixel location in the x and y values of State. For 'mouse-look' behavior in games, however, relative mouse movement is desired. While there are some older tricks for emulating this with absolute pixel locations and computing deltas, there are better options which are implemented by Mouse.

Control of the mode is set by SetMode passing either MODE_ABSOLUTE (the default) or MODE_RELATIVE. The current mode is returned in State in the positionMode value to inform your input code locally the mode of the x, y values.

Here, we are using relative movement whenever the left mouse button is held down:

auto state = g_mouse->GetState();
    if (state.positionMode == Mouse::MODE_RELATIVE)
    {
        // state.x and state.y are relative values; system cursor is not visible
    }
    else
    {
        // state.x and state.y are absolute pixel values; system cursor is visible
    }

    tracker.Update(state);

    if (tracker.leftButton == Mouse::ButtonStateTracker::ButtonState::PRESSED)
    {
        mouse->SetMode(Mouse::MODE_RELATIVE);
    }
    elseif (tracker.leftButton == Mouse::ButtonStateTracker::ButtonState::RELEASED)
    {
        mouse->SetMode(Mouse::MODE_ABSOLUTE);
    }

Note: When using MODERELATIVE, the system cursor is hidden so a user can't navigate away to another monitor or app or even exit. If your game makes use of 'mouse-look' controls, you should ensure that a simple key (like the ESC key) returns to the game's menu/pause screen and that needs to restore MODEABSOLUTE behavior.

Remark

The mouse scroll wheel value is accumulated. To reset the value to 0, use ResetScrollWheelValue.

Threading model

The Mouse class should be thread-safe with the exception of the ProcessMessage which should only be called in your windows message loop.

Platform notes

The Xbox One platform doesn't support pointer or mouse input devices.

For Windows Store, universal Windows apps, and Windows phone touch/pointer devices are captured as mouse movement. Touch/pointer devices do not, however, result in changes to button state. Relative mouse movement is captured per this MSDN article: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994925.aspx

For Windows desktop apps, relative mouse movement is captured using "raw input" per the MSDN article https://msdn.microsoft.com/en-us/library/windows/desktop/ee418864.aspx. Note that a consequence of this implementation is that relative mouse movement is not available when using the application through Remote Desktop.

Updated Wiki: Mouse

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for simplified mouse tracking modeled after the XNA C# Mouse class.

Header

#include <Mouse.h>

Initialization

Mouse is a singleton.

std::unique_ptr<Mouse> mouse( new Mouse );
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr.

Integration

Windows desktop

The application needs to call SetWindow and make calls during the main WndProc message processing to ProcessMessage:

mouse->SetWindow(hWnd);

...

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_ACTIVATEAPP:
    case WM_INPUT:
    case WM_MOUSEMOVE:
    case WM_LBUTTONDOWN:
    case WM_LBUTTONUP:
    case WM_RBUTTONDOWN:
    case WM_RBUTTONUP:
    case WM_MBUTTONDOWN:
    case WM_MBUTTONUP:
    case WM_MOUSEWHEEL:
    case WM_XBUTTONDOWN:
    case WM_XBUTTONUP:
    case WM_MOUSEHOVER:
        Mouse::ProcessMessage(message, wParam, lParam);
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

Universal Windows apps, Windows Store apps

You need to call SetWindow and SetDpi in the appropriate places.

void App::SetWindow(CoreWindow^ window)
{
    mouse->SetWindow(window);
}

void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
{
    mouse->SetDpi(sender->LogicalDpi);
}

Basic use

GetState queries the current state of the mouse.

auto state = mouse->GetState();

if ( state.leftButton )
   // Left button is down

XMFLOAT2 mousePosInPixels( float(m.x), float(m.y) );
// This is the absolute position of the mouse relative// to the upper-left corner of the window

Button state tracker

A common pattern is to trigger an action when a mouse button is pressed or released, but you don't want to trigger the action every single frame if the button is held down for more than a single frame. This helper class simplifies this.

std::unique_ptr<Mouse::ButtonStateTracker> tracker( new Mouse::ButtonStateTracker );

...

auto state = mouse->GetState();
tracker->Update( state );

if ( tracker->rightButton == Mouse::ButtonStateTracker::PRESSED )
    // Take an action when Right mouse button is first pressed, but don't do// it again until the button is released and then pressed again

When resuming from a pause or suspend, be sure to call Reset on the tracker object to clear the state history.

Absolute vs. Relative Mouse position

By default, the mouse state is returned as a absolute pixel location in the x and y values of State. For 'mouse-look' behavior in games, however, relative mouse movement is desired. While there are some older tricks for emulating this with absolute pixel locations and computing deltas, there are better options which are implemented by Mouse.

Control of the mode is set by SetMode passing either MODE_ABSOLUTE (the default) or MODE_RELATIVE. The current mode is returned in State in the positionMode value to inform your input code locally the mode of the x, y values.

Here, we are using relative movement whenever the left mouse button is held down:

auto state = g_mouse->GetState();
    if (state.positionMode == Mouse::MODE_RELATIVE)
    {
        // state.x and state.y are relative values; system cursor is not visible
    }
    else
    {
        // state.x and state.y are absolute pixel values; system cursor is visible
    }

    tracker.Update(state);

    if (tracker.leftButton == Mouse::ButtonStateTracker::ButtonState::PRESSED)
    {
        mouse->SetMode(Mouse::MODE_RELATIVE);
    }
    elseif (tracker.leftButton == Mouse::ButtonStateTracker::ButtonState::RELEASED)
    {
        mouse->SetMode(Mouse::MODE_ABSOLUTE);
    }

Note: When using MODE_RELATIVE, the system cursor is hidden so a user can't navigate away to another monitor or app or even exit. If your game makes use of 'mouse-look' controls, you should ensure that a simple key (like the ESC key) returns to the game's menu/pause screen and that needs to restore MODE_ABSOLUTE behavior.

Remark

The mouse scroll wheel value is accumulated. To reset the value to 0, use ResetScrollWheelValue.

Threading model

The Mouse class should be thread-safe with the exception of the ProcessMessage which should only be called in your windows message loop.

Platform notes

The Xbox One platform doesn't support pointer or mouse input devices.

For Windows Store, universal Windows apps, and Windows phone touch/pointer devices are captured as mouse movement. Touch/pointer devices do not, however, result in changes to button state. Relative mouse movement is captured per this MSDN article: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994925.aspx

For Windows desktop apps, relative mouse movement is captured using "raw input" per the MSDN article https://msdn.microsoft.com/en-us/library/windows/desktop/ee418864.aspx. Note that a consequence of this implementation is that relative mouse movement is not available when using the application through Remote Desktop.

Updated Wiki: GeometricPrimitive

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for drawing simple geometric shapes including texture coordinates and surface normals.
  • Cube (aka hexahedron)
  • Sphere
  • Geodesic Sphere
  • Cylinder
  • Cone
  • Torus
  • Tetrahedron
  • Octahedron
  • Dodecahedron
  • Icosahedron
  • Teapot

GeometricPrimitiveExample.jpg

Related tutorial:3D shapes

Header

#include <GeometricPrimitive.h>

Initialization

The GeometryPrimitive class must be created from a factory method which takes the Direct3D 11 device context.

std::unique_ptr<GeometricPrimitive> shape(
GeometricPrimitive::CreateTeapot(deviceContext) );
For exception safety, the factory functions return a std::unique_ptr.
  • CreateCube( deviceContext, float size = 1)
  • CreateBox( deviceContext, const XMFLOAT3& size)
  • CreateSphere( deviceContext, float diameter = 1, size_t tessellation = 16)
  • CreateGeoSphere( deviceContext, float diameter = 1, size_t tessellation = 3)
  • CreateCylinder( deviceContext, float height = 1, float diameter = 1, size_t tessellation = 32)
  • CreateCone( deviceContext, float diameter = 1, float height = 1, size_t tessellation = 32)
  • CreateTorus( deviceContext, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32)
  • CreateTetrahedron ( deviceContext, float size = 1)
  • CreateOctahedron ( deviceContext, float size = 1)
  • CreateDodecahedron ( deviceContext, float size = 1)
  • CreateIcosahedron ( deviceContext, float size = 1)
  • CreateTeapot( deviceContext, float size = 1, size_t tessellation = 8)

Simple drawing

Simple solid shape drawing:
shape->Draw(world, view, projection, Colors::CornflowerBlue);

Simple wireframe shape drawing:
shape->Draw(world, view, projection, Colors::Gray, nullptr, true);

Simple solid textured shape drawing:
shape->Draw(world, view, projection, Colors::Gray, cat);

The Draw method also accepts an optional callback function which can be used to override the default rendering state:
shape->Draw(world, view, projection, Colors::White, catTexture, false, [=]
{
    deviceContext->OMSetBlendState(...);
});
This makes use of a BasicEffect shared by all geometric primitives drawn on that device context.

Advanced drawing

This form of drawing makes use of a custom Effects instance. The caller is responsible for using an input layout that matches the effect.

IEffect* myeffect = ...

Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
shape->CreateInputLayout( myeffect, inputLayout.GetAddressOf() );

shape->Draw( myeffect, inputLayout.Get() );

This takes an optional parameter for enabling alpha-blending, wireframe, and a callback function which can be used to override the default rendering state.

The Draw operation will only set up a texture sampler in slot 0. If you are using an Effects instance with more than a single texture, you need to set additional samplers manually (perhaps via setCustomState callbacks). For example, if using EnvironmentMapEffect:

shape->Draw( myeffect, inputLayout.Get(), false, false, [=]
{
    ID3D11SamplerState* samplerState[2] = { states.LinearClamp(), states.LinearWrap() };
    deviceContext->PSSetSamplers(0, 2, &samplerState);
});

Note that GeometricPrimitive shapes define a single set of texture coordinates, so you can't use them with DualTextureEffect. They also do not include tangents or bi-normals, so they don't work with DGSLEffect.

Coordinate systems

These geometric primitives (based on the XNA Game Studio conventions) use right-handed coordinates. They can be used with left-handed coordinates by setting the rhcoords parameter on the factory methods to 'false' to reverse the winding ordering (the parameter defaults to 'true').

std::unique_ptr<GeometricPrimitive> shape(
GeometricPrimitive::CreateTeapot( deviceContext, 1.f, 8, false ) );

Note: Using the wrong value for rhcoords for your viewing setup will result in the objects looking 'inside out'.

Inside vs. Outside

These geometric primitives are intended for view from the 'outside' for efficient back-face culling. However, both spheres and boxes are commonly used to form 'skyboxes' for backgrounds. To support this, you set the rhcoords parameter backwards for your view coordinates, and then set invertn to true.

For a right-handed view system:

    std::unique_ptr<GeometricPrimitive> shape(
        GeometricPrimitive::CreateBox( deviceContext, XMFLOAT3(10,10,10), false, true);

For a left-handed view system:

    std::unique_ptr<GeometricPrimitive> shape(
        GeometricPrimitive::CreateBox( deviceContext, XMFLOAT3(10,10,10), true, true);

Alpha blending

Alpha blending defaults to using premultiplied alpha. To make use of 'straight' alpha textures, override the blending mode via the optional callback:

CommonStates states(device);

shape->Draw(world, view, projection, Colors::White, catTexture, false, [=]
{
    deviceContext->OMSetBlendState( states.NonPremultiplied(), nullptr, 0xFFFFFFFF);
});

Feature Level Notes

In order to support all feature levels, the GeometricPrimitive implementation make use of 16-bit indices (DXGI_FORMAT_R16_UINT) which limits to a maximum of 65535 vertices.

Feature Level 9.1 is also limited to a maximum of 65535 primitives in a single draw. This rule out using extremely large numbers for the tessellation factor, although the exact limit depends on the shape implementation.

Note that these shapes tend to duplicate rather than share vertices in order to provide the 'face-normal' lighting expected of sharp geometry.

Threading model

Each GeometricPrimitive instance only supports drawing from one thread at a time, but you can simultaneously submit primitives on multiple threads if you create a separate GeometricPrimitive instance per Direct3D 11 deferred context.
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476892.aspx

Remark

Tetrahedron, Cube/Hexahedron, Octahedron, Dodecahedron, and Icosahedron comprise the five "Platonic solids". The Utah Teapot is sometimes referred to as the "Sixth Platonic solid" due to its prevalence in rendering sample images.

Further Reading

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx

http://blogs.msdn.com/b/chuckw/archive/2012/06/20/direct3d-feature-levels.aspx

http://en.wikipedia.org/wiki/Cube
http://en.wikipedia.org/wiki/Hexahedron
http://en.wikipedia.org/wiki/Sphere
http://en.wikipedia.org/wiki/Cylinder_(geometry)
http://en.wikipedia.org/wiki/Cone
http://en.wikipedia.org/wiki/Torus
http://en.wikipedia.org/wiki/Tetrahedron
http://en.wikipedia.org/wiki/Octahedron
http://en.wikipedia.org/wiki/Dodecahedron
http://en.wikipedia.org/wiki/Icosahedron
http://en.wikipedia.org/wiki/Utah_teapot
https://en.wikipedia.org/wiki/Platonic_solid

Updated Wiki: GeometricPrimitive

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for drawing simple geometric shapes including texture coordinates and surface normals.
  • Cube (aka hexahedron)
  • Sphere
  • Geodesic Sphere
  • Cylinder
  • Cone
  • Torus
  • Tetrahedron
  • Octahedron
  • Dodecahedron
  • Icosahedron
  • Teapot

GeometricPrimitiveExample.jpg

Related tutorial:3D shapes

Header

#include <GeometricPrimitive.h>

Initialization

The GeometryPrimitive class must be created from a factory method which takes the Direct3D 11 device context.

std::unique_ptr<GeometricPrimitive> shape(
GeometricPrimitive::CreateTeapot(deviceContext) );
For exception safety, the factory functions return a std::unique_ptr.
  • CreateCube( deviceContext, float size = 1)
  • CreateBox( deviceContext, const XMFLOAT3& size)
  • CreateSphere( deviceContext, float diameter = 1, size_t tessellation = 16)
  • CreateGeoSphere( deviceContext, float diameter = 1, size_t tessellation = 3)
  • CreateCylinder( deviceContext, float height = 1, float diameter = 1, size_t tessellation = 32)
  • CreateCone( deviceContext, float diameter = 1, float height = 1, size_t tessellation = 32)
  • CreateTorus( deviceContext, float diameter = 1, float thickness = 0.333f, size_t tessellation = 32)
  • CreateTetrahedron ( deviceContext, float size = 1)
  • CreateOctahedron ( deviceContext, float size = 1)
  • CreateDodecahedron ( deviceContext, float size = 1)
  • CreateIcosahedron ( deviceContext, float size = 1)
  • CreateTeapot( deviceContext, float size = 1, size_t tessellation = 8)

Simple drawing

Simple solid shape drawing:
shape->Draw(world, view, projection, Colors::CornflowerBlue);

Simple wireframe shape drawing:
shape->Draw(world, view, projection, Colors::Gray, nullptr, true);

Simple solid textured shape drawing:
shape->Draw(world, view, projection, Colors::Gray, cat);

The Draw method also accepts an optional callback function which can be used to override the default rendering state:
shape->Draw(world, view, projection, Colors::White, catTexture, false, [=]
{
    deviceContext->OMSetBlendState(...);
});
This makes use of a BasicEffect shared by all geometric primitives drawn on that device context.

Advanced drawing

This form of drawing makes use of a custom Effects instance. The caller is responsible for using an input layout that matches the effect.

IEffect* myeffect = ...

Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
shape->CreateInputLayout( myeffect, inputLayout.GetAddressOf() );

shape->Draw( myeffect, inputLayout.Get() );

This takes an optional parameter for enabling alpha-blending, wireframe, and a callback function which can be used to override the default rendering state.

The Draw operation will only set up a texture sampler in slot 0. If you are using an Effects instance with more than a single texture, you need to set additional samplers manually (perhaps via setCustomState callbacks). For example, if using EnvironmentMapEffect:

shape->Draw( myeffect, inputLayout.Get(), false, false, [=]
{
    ID3D11SamplerState* samplerState[2] = { states.LinearClamp(), states.LinearWrap() };
    deviceContext->PSSetSamplers(0, 2, &samplerState);
});

Note that GeometricPrimitive shapes define a single set of texture coordinates, so you can't use them with DualTextureEffect. They also do not include tangents or bi-normals, so they don't work with DGSLEffect.

Coordinate systems

These geometric primitives (based on the XNA Game Studio conventions) use right-handed coordinates. They can be used with left-handed coordinates by setting the rhcoords parameter on the factory methods to 'false' to reverse the winding ordering (the parameter defaults to 'true').

std::unique_ptr<GeometricPrimitive> shape(
GeometricPrimitive::CreateTeapot( deviceContext, 1.f, 8, false ) );

Note: Using the wrong value for rhcoords for your viewing setup will result in the objects looking 'inside out'.

Inside vs. Outside

These geometric primitives are intended for view from the 'outside' for efficient back-face culling. However, both spheres and boxes are commonly used to form 'skyboxes' for backgrounds. To support this, you set the rhcoords parameter backwards for your view coordinates, and then set invertn to true.

For a right-handed view system:

    std::unique_ptr<GeometricPrimitive> sky(
        GeometricPrimitive::CreateBox( deviceContext, XMFLOAT3(10,10,10), false, true);

    std::unique_ptr<GeometricPrimitive> sky(
        GeometricPrimitive::CreateSphere( deviceContext, 100.f, false, true);

For a left-handed view system:

    std::unique_ptr<GeometricPrimitive> sky(
        GeometricPrimitive::CreateBox( deviceContext, XMFLOAT3(10,10,10), true, true);

    std::unique_ptr<GeometricPrimitive> sky(
        GeometricPrimitive::CreateSphere( deviceContext, 100.f, true, true);

Alpha blending

Alpha blending defaults to using premultiplied alpha. To make use of 'straight' alpha textures, override the blending mode via the optional callback:

CommonStates states(device);

shape->Draw(world, view, projection, Colors::White, catTexture, false, [=]
{
    deviceContext->OMSetBlendState( states.NonPremultiplied(), nullptr, 0xFFFFFFFF);
});

Feature Level Notes

In order to support all feature levels, the GeometricPrimitive implementation make use of 16-bit indices (DXGI_FORMAT_R16_UINT) which limits to a maximum of 65535 vertices.

Feature Level 9.1 is also limited to a maximum of 65535 primitives in a single draw. This rule out using extremely large numbers for the tessellation factor, although the exact limit depends on the shape implementation.

Note that these shapes tend to duplicate rather than share vertices in order to provide the 'face-normal' lighting expected of sharp geometry.

Threading model

Each GeometricPrimitive instance only supports drawing from one thread at a time, but you can simultaneously submit primitives on multiple threads if you create a separate GeometricPrimitive instance per Direct3D 11 deferred context.
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476892.aspx

Remark

Tetrahedron, Cube/Hexahedron, Octahedron, Dodecahedron, and Icosahedron comprise the five "Platonic solids". The Utah Teapot is sometimes referred to as the "Sixth Platonic solid" due to its prevalence in rendering sample images.

Further Reading

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx

http://blogs.msdn.com/b/chuckw/archive/2012/06/20/direct3d-feature-levels.aspx

http://en.wikipedia.org/wiki/Cube
http://en.wikipedia.org/wiki/Hexahedron
http://en.wikipedia.org/wiki/Sphere
http://en.wikipedia.org/wiki/Cylinder_(geometry)
http://en.wikipedia.org/wiki/Cone
http://en.wikipedia.org/wiki/Torus
http://en.wikipedia.org/wiki/Tetrahedron
http://en.wikipedia.org/wiki/Octahedron
http://en.wikipedia.org/wiki/Dodecahedron
http://en.wikipedia.org/wiki/Icosahedron
http://en.wikipedia.org/wiki/Utah_teapot
https://en.wikipedia.org/wiki/Platonic_solid

Updated Wiki: Mouse

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for simplified mouse tracking modeled after the XNA C# Mouse class.

sculptmobilemouse.jpg

Header

#include <Mouse.h>

Initialization

Mouse is a singleton.

std::unique_ptr<Mouse> mouse( new Mouse );
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr.

Integration

Windows desktop

The application needs to call SetWindow and make calls during the main WndProc message processing to ProcessMessage:

mouse->SetWindow(hWnd);

...

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_ACTIVATEAPP:
    case WM_INPUT:
    case WM_MOUSEMOVE:
    case WM_LBUTTONDOWN:
    case WM_LBUTTONUP:
    case WM_RBUTTONDOWN:
    case WM_RBUTTONUP:
    case WM_MBUTTONDOWN:
    case WM_MBUTTONUP:
    case WM_MOUSEWHEEL:
    case WM_XBUTTONDOWN:
    case WM_XBUTTONUP:
    case WM_MOUSEHOVER:
        Mouse::ProcessMessage(message, wParam, lParam);
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

Universal Windows apps, Windows Store apps

You need to call SetWindow and SetDpi in the appropriate places.

void App::SetWindow(CoreWindow^ window)
{
    mouse->SetWindow(window);
}

void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
{
    mouse->SetDpi(sender->LogicalDpi);
}

Basic use

GetState queries the current state of the mouse.

auto state = mouse->GetState();

if ( state.leftButton )
   // Left button is down

XMFLOAT2 mousePosInPixels( float(m.x), float(m.y) );
// This is the absolute position of the mouse relative// to the upper-left corner of the window

Button state tracker

A common pattern is to trigger an action when a mouse button is pressed or released, but you don't want to trigger the action every single frame if the button is held down for more than a single frame. This helper class simplifies this.

std::unique_ptr<Mouse::ButtonStateTracker> tracker( new Mouse::ButtonStateTracker );

...

auto state = mouse->GetState();
tracker->Update( state );

if ( tracker->rightButton == Mouse::ButtonStateTracker::PRESSED )
    // Take an action when Right mouse button is first pressed, but don't do// it again until the button is released and then pressed again

When resuming from a pause or suspend, be sure to call Reset on the tracker object to clear the state history.

Absolute vs. Relative Mouse position

By default, the mouse state is returned as a absolute pixel location in the x and y values of State. For 'mouse-look' behavior in games, however, relative mouse movement is desired. While there are some older tricks for emulating this with absolute pixel locations and computing deltas, there are better options which are implemented by Mouse.

Control of the mode is set by SetMode passing either MODE_ABSOLUTE (the default) or MODE_RELATIVE. The current mode is returned in State in the positionMode value to inform your input code locally the mode of the x, y values.

Here, we are using relative movement whenever the left mouse button is held down:

auto state = g_mouse->GetState();
    if (state.positionMode == Mouse::MODE_RELATIVE)
    {
        // state.x and state.y are relative values; system cursor is not visible
    }
    else
    {
        // state.x and state.y are absolute pixel values; system cursor is visible
    }

    tracker.Update(state);

    if (tracker.leftButton == Mouse::ButtonStateTracker::ButtonState::PRESSED)
    {
        mouse->SetMode(Mouse::MODE_RELATIVE);
    }
    elseif (tracker.leftButton == Mouse::ButtonStateTracker::ButtonState::RELEASED)
    {
        mouse->SetMode(Mouse::MODE_ABSOLUTE);
    }

Note: When using MODE_RELATIVE, the system cursor is hidden so a user can't navigate away to another monitor or app or even exit. If your game makes use of 'mouse-look' controls, you should ensure that a simple key (like the ESC key) returns to the game's menu/pause screen and that needs to restore MODE_ABSOLUTE behavior.

Remark

The mouse scroll wheel value is accumulated. To reset the value to 0, use ResetScrollWheelValue.

Threading model

The Mouse class should be thread-safe with the exception of the ProcessMessage which should only be called in your windows message loop.

Platform notes

The Xbox One platform doesn't support pointer or mouse input devices.

For Windows Store, universal Windows apps, and Windows phone touch/pointer devices are captured as mouse movement. Touch/pointer devices do not, however, result in changes to button state. Relative mouse movement is captured per this MSDN article: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994925.aspx

For Windows desktop apps, relative mouse movement is captured using "raw input" per the MSDN article https://msdn.microsoft.com/en-us/library/windows/desktop/ee418864.aspx. Note that a consequence of this implementation is that relative mouse movement is not available when using the application through Remote Desktop.

Updated Wiki: Keyboard

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/DirectXTK

This is a helper for simplified keyboard state tracking modeled after the XNA C# Keyboard class.

wirelesskeyboard.jpg

Header

#include <Keyboard.h>

Initialization

Keyboard is a singleton.

std::unique_ptr<Keyboard> keyboard( new Keyboard );
For exception safety, it is recommended you make use of the C++ RAII pattern and use a std::unique_ptr.

Integration

For Windows desktop applications, the application needs to make the appropriate calls during the main WndProc message processing:

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_ACTIVATEAPP:
        Keyboard::ProcessMessage(message, wParam, lParam);
        break;

    case WM_KEYDOWN:
    case WM_SYSKEYDOWN:
    case WM_KEYUP:
    case WM_SYSKEYUP:
        Keyboard::ProcessMessage(message, wParam, lParam);
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

For universal Windows apps or Windows Store apps, you need to call SetWindow in the appropriate place.

void App::SetWindow(CoreWindow^ window)
{
    keyboard->SetWindow(window);
}

Basic use

GetState queries the current state of the keyboard.

auto kb = keyboard->GetState();

if (kb.Back)
    // Backspace key is downif (kb.W)
    // W key is downif (kb.A)
    // A key is downif (kb.S)
    // S key is downif (kb.D)
    // D key is downif (kb.LeftShift)
    // Left shift key is downif (kb.RightShift)
    // Right shift key is downif ( kb.IsKeyDown( VK_RETURN ) )
    // Return key is down

Keyboard state tracker

A common pattern is to trigger an action when a key is pressed or released, but you don't want to trigger the action every single frame if the key is held down for more than a single frame. This helper class simplifies this.

std::unique_ptr<Keyboard::KeyboardStateTracker> tracker( new Keyboard::KeyboardStateTracker );

...

auto state = keyboard->GetState();
tracker->Update( state );

if ( tracker.pressed.Space )
    // Space was just pressed downif ( tracker.IsKeyReleased( VK_F1 ) )
    // F1 key was just released

When resuming from a pause or suspend, be sure to call Reset on the tracker object to clear the state history.

Threading model

The Keyboard class should be thread-safe with the exception of the ProcessMessage which should only be called in your windows message loop.

Remarks

This helper is intended for game controls tied to the keyboard. For chat input and editable text, you should use the platform-specific methods for text input.

Due to some quirks of the platform, If you press both Left & Right Shift keys at the same time, they will both appear down until both are released.

International layouts

Keep in mind when designing the keyboard controls for your game the different layouts of standard keyboards. In particularly, note the red keys which are in different locations for international keyboards than the traditional English QWERTY keyboard.

KeyboardInternational.png

The Keyboard class makes use of virtual keys and not scancodes so your code has to be aware of these layout differences.

https://en.wikipedia.org/wiki/QWERTY
https://en.wikipedia.org/wiki/QWERTZ
https://en.wikipedia.org/wiki/AZERTY
https://en.wikipedia.org/wiki/Keyboard_layout#QZERTY

Platform notes

For Windows phone and Xbox One, the Keyboard class exists in the library to avoid the need for conditional compilation, but tying the input to the virtual keyboard as that makes little sense as a controller for games.

Updated Wiki: Version History

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub.

July 29, 2015
  • Added CreateBox method to GeometricPrimitive
  • Added 'invertn' optional parameter to CreateSphere
  • Updates for Keyboard, Mouse class
  • Fixed bug when loading older SDKMESH models
  • Updated for VS 2015 and Windows 10 SDK RTM
  • Retired VS 2010 and Windows Store 8.0 projects1

July 1, 2015
  • Added Keyboard, Mouse class
  • Support for loading pre-lit models with SDKMESH
  • GamePad implemented using Windows.Gaming.Input for Windows 10
  • DirectXTK for Audio updates for xWMA support with XAudio 2.9
  • Added FindGlyph and GetSpriteSheet methods to SpriteFont

March 27, 2015
  • Added projects for Windows apps Technical Preview
  • GamePad temporarily uses 'null' device for universal Windows application platform

February 25, 2015 (NuGet version 2015.2.25.1)
  • DirectXTK for Audio updates
    • breaking change pitch now defined as -1 to 1 with 0 as the default
    • One-shot Play method with volume, pitch, and pan
    • GetMasterVolume/SetMasterVolume method for AudioEngine
    • Fix for compact wavebank validation
    • Improved voice cleanup and shutdown
  • Minor code cleanup and C++11 =default/=delete usage

January 26, 2015 (NuGet version 2015.1.26.1)
  • GamePad class: emulate XInputEnable behavior for XInput 9.1.0
  • DirectXTK for Audio fix for Stop followed by Play doing a proper restart
  • DirectXTK for Audio fix when using XAudio 2.7 on a system with no audio device
  • Updates for Xbox One platform support
  • Minor code cleanup and C99 printf string conformance

November 24, 2014 (NuGet version 2014.11.24.1, 2014.11.24.2)
  • SimpleMath fix for Matrix operator !=
  • DirectXTK for Audio workaround for XAudio 2.7 on Windows 7 problem
  • Updates for Windows phone 8.1 platform support
  • Updates for Visual Studio 2015 Technical Preview
  • Minor code cleanup

October 28, 2014
  • Model support for loading from VBO files
  • Model render now sets samplers on slots 0,1 by default for dual-texture effects
  • Updates for Xbox One platform support
  • Minor code cleanup

September 5, 2014
  • GamePad class: gamepad controller helper using XInput on Windows, IGamepad for Xbox One
  • SimpleMath updates; Matrix billboard methods; breaking change: Matrix::Identity() -> Matrix::Identity
  • SpriteBatch new optional SetViewport method
  • SpriteFont fix for white-space character rendering optimization
  • DDSTextureLoader fix for auto-gen mipmaps for volume textures
  • Explicit calling-convention annotation for public headers
  • Updates for Xbox One platform support
  • Minor code and project cleanup

July 15, 2014 (NuGet version 2014.7.15.1)
  • DirectXTK for Audio and XWBTool fixes
  • Updates to Xbox One platform support

April 3, 2014
  • Windows phone 8.1 platform support

February 24, 2014
  • DirectXHelper: new utility header with MapGuard and public version of SetDebugObjectName template
  • DDSTextureLoader: Optional support for auto-gen mipmaps
  • DDSTextureLoader/ScreenGrab: support for Direct3D 11 video formats including legacy "YUY2" DDS files
  • GeometricPrimtive: Handedness fix for tetrahedron, octahedron, dodecahedron, and icosahedron
  • SpriteBatch::SetRotation(DXGI_MODE_ROTATION_UNSPECIFIED) to disable viewport matrix
  • XboxDDSTextureLoader: optional forceSRGB parameter

January 24, 2014
  • DirectXTK for Audio updated with voice management and optional mastering volume limiter
  • Added orientation rotation support to SpriteBatch
  • Fixed a resource leak with GetDefaultTexture() used by some Effects
  • Code cleanup (removed DXGI_1_2_FORMATS control define; d2d1.h workaround not needed; ScopedObject typedef removed)

December 24, 2013
  • DirectXTK for Audio
  • Xbox One platform support
  • MakeSpriteFont tool updated with more progress feedback when capturing large fonts
  • Minor updates for .SDKMESH Model loader
  • Fixed bug in .CMO Model loader when handling multiple textures
  • Improved debugging output

October 28, 2013
  • Updated for Visual Studio 2013 and Windows 8.1 SDK RTM
  • Added DGSLEffect, DGSLEffectFactory, VertexPositionNormalTangentColorTexture, and VertexPositionNormalTangentColorTextureSkinning
  • Model loading and effect factories support loading skinned models
  • MakeSpriteFont now has a smooth vs. sharp antialiasing option: /sharp
  • Model loading from CMOs now handles UV transforms for texture coordinates
  • A number of small fixes for EffectFactory
  • Minor code and project cleanup
  • Added NO_D3D11_DEBUG_NAME compilation define to control population of Direct3D debug layer names for debug builds

July 1, 2013
  • VS 2013 Preview projects added and updates for DirectXMath 3.05 vectorcall
  • Added use of sRGB WIC metadata for JPEG, PNG, and TIFF
  • SaveToWIC functions updated with new optional setCustomProps parameter and error check with optional targetFormat

May 30, 2013
  • Added more GeometricPrimitives: Cone, Tetrahedron, Octahedron, Dodecahedron, Icosahedron
  • Updated to support loading new metadata from DDS files (if present)
  • Fixed bug with loading of WIC 32bpp RGBE format images
  • Fixed bug when skipping mipmaps in a 1D or 2D array texture DDS file

February 22, 2013 (NuGet version 2.22.13.23)
  • Added SimpleMath header
  • Fixed bug that prevented properly overriding EffectFactory::CreateTexture
  • Fixed forceSRGB logic in DDSTextureLoader and WICTextureLoader
  • Break circular reference chains when using SpriteBatch with a setCustomShaders lambda
  • Updated projects with /fp:fast for all configs, /arch:SSE2 for Win32 configs
  • Sensibly named .pdb output files
  • Added WIC_USE_FACTORY_PROXY build option (uses WindowsCodecs.dll entrypoint rather than CoCreateInstance)

January 25, 2013
  • GeometricPrimitive support for left-handed coordinates and drawing with custom effects
  • Model, ModelMesh, and ModelMeshPart added with loading of rigid non-animating models from .CMO and .SDKMESH files
  • EffectFactory helper class added

December 11, 2012
  • Ex versions of DDSTextureLoader and WICTextureLoader
  • Removed use of ATL's CComPtr in favor of WRL's ComPtr for all platforms to support VS Express editions
  • Updated VS 2010 project for official 'property sheet' integration for Windows 8.0 SDK
  • Minor fix to CommonStates for Feature Level 9.1
  • Tweaked AlphaTestEffect.cpp to work around ARM NEON compiler codegen bug
  • Added dxguid.lib as a default library for Debug builds to resolve GUID link issues

November 15, 2012
  • Added support for WIC2 when available on Windows 8 and Windows 7 with KB 2670838
  • Cleaned up warning level 4 warnings

October 30, 2012
  • Added project files for Windows phone 8

October 12, 2012
  • Added PrimitiveBatch for drawing user primitives
  • Debug object names for all D3D resources (for PIX and debug layer leak reporting)

October 2, 2012
  • Added ScreenGrab module
  • Added CreateGeoSphere for drawing a geodesic sphere
  • Put DDSTextureLoader and WICTextureLoader into the DirectX C++ namespace

September 7, 2012
  • Renamed project files for better naming consistency
  • Updated WICTextureLoader for Windows 8 96bpp floating-point formats
  • Win32 desktop projects updated to use Windows Vista (0x0600) rather than Windows 7 (0x0601) APIs
  • Tweaked SpriteBatch.cpp to workaround ARM NEON compiler codegen bug

May 31, 2012
  • Updated Metro project for Visual Studio 2012 Release Candidate changes
  • Cleaned up x64 Debug configuration warnings and switched to use "_DEBUG" instead of "DEBUG"
  • Minor fix for DDSTextureLoader's retry fallback that can happen with 10level9 feature levels

May 2, 2012
  • Added SpriteFont implementation and the MakeSpriteFont utility

March 29, 2012
  • WICTextureLoader updated with Windows 8 WIC native pixel formats

March 6, 2012
  • Fix for too much temp memory used by WICTextureLoader
  • Add separate Visual Studio 11 projects for Desktop vs. Metro builds

March 5, 2012
  • Bug fix for SpriteBatch with batches > 2048

February 24, 2012
  • Original release

Updated Wiki: Samples

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub. https://github.com/Microsoft/DirectXTK/wiki/Samples

Here is a list of various samples and articles for making use of DirectXTK.

Windows Store apps

Simple Sample for Windows 8
http://code.msdn.microsoft.com/DirectXTK-Simple-Sample-608bc274

Simple Sample for Windows 8.1
http://code.msdn.microsoft.com/DirectXTK-Simple-Sample-a0b6de36

DirectX Tool Kit – native “XNA” for Windows 8
http://www.tonicodes.net/blog/directx-tool-kit-native-xna-for-windows-8/

Windows Store DirectX C++ Sample Base
http://geekswithblogs.net/mikebmcl/archive/2013/01/31/windows-store-directx-c-sample-base.aspx

Bloom PostProcess in C++
http://geekswithblogs.net/mikebmcl/archive/2013/02/27/windows-store-c-directx-bloom-sample-released-and-other-samples.aspx

Per Pixel Collision Detection in C++
http://geekswithblogs.net/mikebmcl/archive/2013/02/14/c-pixel-perfect-collision-detection-sample-and-base-sample-updated.aspx

Windows desktop apps

Simple Sample (no audio)
http://code.msdn.microsoft.com/DirectXTK-Simple-Win32-23db418a

Simple Sample (Windows 8.x using XAudio 2.8)
http://code.msdn.microsoft.com/DirectXTK-for-Audio-Simple-9d6a7da2

Simple Sample (DirectX SDK using XAudio 2.7)
http://code.msdn.microsoft.com/DirectXTK-for-Audio-Simple-928e0700

DXUT+DirectXTK Simple Sample
http://code.msdn.microsoft.com/DXUTDirectXTK-Simple-Win32-9cf797e9

Windows phone 8

Simple Sample (Windows phone 8.0)
http://code.msdn.microsoft.com/DirectXTK-Simple-Windows-80e6b591

Marble Maze sample for Windows Phone 8
http://code.msdn.microsoft.com/Marble-Maze-sample-for-c9f3706b

Direct3D with XAML Marble Maze
http://code.msdn.microsoft.com/Direct3D-with-XAML-Marble-1d51a37b

Getting Started with Direct3D on Windows Phone 8
http://www.catalinzima.com/2012/11/getting-started-with-direct3d-on-windows-phone-8-for-2d-game-development/

DirectX on Windows Phone: 2D Game Example using DirectX Toolkit
http://www.developer.nokia.com/Community/Wiki/DirectX_on_Windows_Phone:_2D_Game_Example_using_DirectX_Toolkit

Xbox One

Simple Sample for the Xbox One XDK
https://developer.xboxlive.com/en-us/platform/development/education/Pages/Samples.aspx (login required)

Simple Sample for the Xbox One ADK
https://developer.xboxlive.com/en-us/platform/development/adk/Pages/ADKSamples.aspx (login required)

Updated Wiki: Version History

$
0
0
NEWS: This project is now hosted on GitHubhttps://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub.

August 18, 2015**
  • Xbox One platform updates

July 29, 2015
  • Added CreateBox method to GeometricPrimitive
  • Added 'invertn' optional parameter to CreateSphere
  • Updates for Keyboard, Mouse class
  • Fixed bug when loading older SDKMESH models
  • Updated for VS 2015 and Windows 10 SDK RTM
  • Retired VS 2010 and Windows Store 8.0 projects1

July 1, 2015
  • Added Keyboard, Mouse class
  • Support for loading pre-lit models with SDKMESH
  • GamePad implemented using Windows.Gaming.Input for Windows 10
  • DirectXTK for Audio updates for xWMA support with XAudio 2.9
  • Added FindGlyph and GetSpriteSheet methods to SpriteFont

March 27, 2015
  • Added projects for Windows apps Technical Preview
  • GamePad temporarily uses 'null' device for universal Windows application platform

February 25, 2015 (NuGet version 2015.2.25.1)
  • DirectXTK for Audio updates
    • breaking change pitch now defined as -1 to 1 with 0 as the default
    • One-shot Play method with volume, pitch, and pan
    • GetMasterVolume/SetMasterVolume method for AudioEngine
    • Fix for compact wavebank validation
    • Improved voice cleanup and shutdown
  • Minor code cleanup and C++11 =default/=delete usage

January 26, 2015 (NuGet version 2015.1.26.1)
  • GamePad class: emulate XInputEnable behavior for XInput 9.1.0
  • DirectXTK for Audio fix for Stop followed by Play doing a proper restart
  • DirectXTK for Audio fix when using XAudio 2.7 on a system with no audio device
  • Updates for Xbox One platform support
  • Minor code cleanup and C99 printf string conformance

November 24, 2014 (NuGet version 2014.11.24.1, 2014.11.24.2)
  • SimpleMath fix for Matrix operator !=
  • DirectXTK for Audio workaround for XAudio 2.7 on Windows 7 problem
  • Updates for Windows phone 8.1 platform support
  • Updates for Visual Studio 2015 Technical Preview
  • Minor code cleanup

October 28, 2014
  • Model support for loading from VBO files
  • Model render now sets samplers on slots 0,1 by default for dual-texture effects
  • Updates for Xbox One platform support
  • Minor code cleanup

September 5, 2014
  • GamePad class: gamepad controller helper using XInput on Windows, IGamepad for Xbox One
  • SimpleMath updates; Matrix billboard methods; breaking change: Matrix::Identity() -> Matrix::Identity
  • SpriteBatch new optional SetViewport method
  • SpriteFont fix for white-space character rendering optimization
  • DDSTextureLoader fix for auto-gen mipmaps for volume textures
  • Explicit calling-convention annotation for public headers
  • Updates for Xbox One platform support
  • Minor code and project cleanup

July 15, 2014 (NuGet version 2014.7.15.1)
  • DirectXTK for Audio and XWBTool fixes
  • Updates to Xbox One platform support

April 3, 2014
  • Windows phone 8.1 platform support

February 24, 2014
  • DirectXHelper: new utility header with MapGuard and public version of SetDebugObjectName template
  • DDSTextureLoader: Optional support for auto-gen mipmaps
  • DDSTextureLoader/ScreenGrab: support for Direct3D 11 video formats including legacy "YUY2" DDS files
  • GeometricPrimtive: Handedness fix for tetrahedron, octahedron, dodecahedron, and icosahedron
  • SpriteBatch::SetRotation(DXGI_MODE_ROTATION_UNSPECIFIED) to disable viewport matrix
  • XboxDDSTextureLoader: optional forceSRGB parameter

January 24, 2014
  • DirectXTK for Audio updated with voice management and optional mastering volume limiter
  • Added orientation rotation support to SpriteBatch
  • Fixed a resource leak with GetDefaultTexture() used by some Effects
  • Code cleanup (removed DXGI_1_2_FORMATS control define; d2d1.h workaround not needed; ScopedObject typedef removed)

December 24, 2013
  • DirectXTK for Audio
  • Xbox One platform support
  • MakeSpriteFont tool updated with more progress feedback when capturing large fonts
  • Minor updates for .SDKMESH Model loader
  • Fixed bug in .CMO Model loader when handling multiple textures
  • Improved debugging output

October 28, 2013
  • Updated for Visual Studio 2013 and Windows 8.1 SDK RTM
  • Added DGSLEffect, DGSLEffectFactory, VertexPositionNormalTangentColorTexture, and VertexPositionNormalTangentColorTextureSkinning
  • Model loading and effect factories support loading skinned models
  • MakeSpriteFont now has a smooth vs. sharp antialiasing option: /sharp
  • Model loading from CMOs now handles UV transforms for texture coordinates
  • A number of small fixes for EffectFactory
  • Minor code and project cleanup
  • Added NO_D3D11_DEBUG_NAME compilation define to control population of Direct3D debug layer names for debug builds

July 1, 2013
  • VS 2013 Preview projects added and updates for DirectXMath 3.05 vectorcall
  • Added use of sRGB WIC metadata for JPEG, PNG, and TIFF
  • SaveToWIC functions updated with new optional setCustomProps parameter and error check with optional targetFormat

May 30, 2013
  • Added more GeometricPrimitives: Cone, Tetrahedron, Octahedron, Dodecahedron, Icosahedron
  • Updated to support loading new metadata from DDS files (if present)
  • Fixed bug with loading of WIC 32bpp RGBE format images
  • Fixed bug when skipping mipmaps in a 1D or 2D array texture DDS file

February 22, 2013 (NuGet version 2.22.13.23)
  • Added SimpleMath header
  • Fixed bug that prevented properly overriding EffectFactory::CreateTexture
  • Fixed forceSRGB logic in DDSTextureLoader and WICTextureLoader
  • Break circular reference chains when using SpriteBatch with a setCustomShaders lambda
  • Updated projects with /fp:fast for all configs, /arch:SSE2 for Win32 configs
  • Sensibly named .pdb output files
  • Added WIC_USE_FACTORY_PROXY build option (uses WindowsCodecs.dll entrypoint rather than CoCreateInstance)

January 25, 2013
  • GeometricPrimitive support for left-handed coordinates and drawing with custom effects
  • Model, ModelMesh, and ModelMeshPart added with loading of rigid non-animating models from .CMO and .SDKMESH files
  • EffectFactory helper class added

December 11, 2012
  • Ex versions of DDSTextureLoader and WICTextureLoader
  • Removed use of ATL's CComPtr in favor of WRL's ComPtr for all platforms to support VS Express editions
  • Updated VS 2010 project for official 'property sheet' integration for Windows 8.0 SDK
  • Minor fix to CommonStates for Feature Level 9.1
  • Tweaked AlphaTestEffect.cpp to work around ARM NEON compiler codegen bug
  • Added dxguid.lib as a default library for Debug builds to resolve GUID link issues

November 15, 2012
  • Added support for WIC2 when available on Windows 8 and Windows 7 with KB 2670838
  • Cleaned up warning level 4 warnings

October 30, 2012
  • Added project files for Windows phone 8

October 12, 2012
  • Added PrimitiveBatch for drawing user primitives
  • Debug object names for all D3D resources (for PIX and debug layer leak reporting)

October 2, 2012
  • Added ScreenGrab module
  • Added CreateGeoSphere for drawing a geodesic sphere
  • Put DDSTextureLoader and WICTextureLoader into the DirectX C++ namespace

September 7, 2012
  • Renamed project files for better naming consistency
  • Updated WICTextureLoader for Windows 8 96bpp floating-point formats
  • Win32 desktop projects updated to use Windows Vista (0x0600) rather than Windows 7 (0x0601) APIs
  • Tweaked SpriteBatch.cpp to workaround ARM NEON compiler codegen bug

May 31, 2012
  • Updated Metro project for Visual Studio 2012 Release Candidate changes
  • Cleaned up x64 Debug configuration warnings and switched to use "_DEBUG" instead of "DEBUG"
  • Minor fix for DDSTextureLoader's retry fallback that can happen with 10level9 feature levels

May 2, 2012
  • Added SpriteFont implementation and the MakeSpriteFont utility

March 29, 2012
  • WICTextureLoader updated with Windows 8 WIC native pixel formats

March 6, 2012
  • Fix for too much temp memory used by WICTextureLoader
  • Add separate Visual Studio 11 projects for Desktop vs. Metro builds

March 5, 2012
  • Bug fix for SpriteBatch with batches > 2048

February 24, 2012
  • Original release
Viewing all 874 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>