Quantcast
Channel: GameDev.net
Viewing all 17560 articles
Browse latest View live

Direct2D/DirectWrite Text Resolution

$
0
0

Hey,

 

I've just been playing about with Direct2D this afternoon, and I've moved on to using DIrectWrite for outputting my text.

 

All easy enough, but I can't for the life of me figure out how to increase the resolution of the text. Anything I draw to the screen with Direct2D scales nicely, but text doesn't.

 

I have two screens, one at 1680x1050, the other at 3840x2160 and it is quite noticeable on the higher resolution screen.

 

D2D_Resolution.jpg

 

You can see the difference between the window title, and the sample text i've done with DirectWrite.

 

Anyone shed any light on this?

 

The code follows, i've removed the extraneous extra code to focus on the DirectWrite stuff.

 

Thanks.

#pragma once

#include <d2d1.h>
#include <dwrite.h>
#include <string.h>
#include <Windows.h>

    template<class Interface>
    inline void SafeRelease( Interface **ppInterfaceToRelease )
    {
        if ( *ppInterfaceToRelease != NULL )
        {
            ( *ppInterfaceToRelease )->Release( );

            ( *ppInterfaceToRelease ) = NULL;
        }
    }

class Application
{
    // ================================================================
    // --> FIELD
    // ================================================================

        private : FLOAT                  m_dpiX;
        private : FLOAT                  m_dpiY;
        private : HWND                   m_hWnd;
        private : ID2D1Factory*          m_pDirect2dFactory;
        private : ID2D1HwndRenderTarget* m_pRenderTarget;
        private : ID2D1SolidColorBrush*  m_pLightSlateGrayBrush;
        private : IDWriteFactory*        m_pDWriteFactory;
        private : IDWriteTextFormat*     m_pTextFormat;
        private : IDWriteTextLayout*     m_pTextLayout;
                  

    // ================================================================
    // --> CONSTRUCTOR
    // ================================================================

        public : Application( );

    // ================================================================
    // --> METHOD
    // ================================================================
 
        // METHOD -> CreateDeviceIndependentResources()
        private : HRESULT CreateDeviceIndependentResources( );

        // METHOD -> CreateDeviceDependentResources()
        private : HRESULT CreateDeviceDependentResources( );

        // METHOD -> DiscardDeviceDependentResources()
        private : void DiscardDeviceDependentResources( );

        // METHOD -> Initialise()
        public : HRESULT Initialise( HINSTANCE hInstance );

        // METHOD -> MessageLoop()
        public : void MessageLoop( );

        // METHOD -> OnRender()
        private : HRESULT OnRender( );

        // METHOD -> OnRender()
        private: void OnResize( UINT height, UINT width );

        // METHOD -> Procedure()
        private : static LRESULT CALLBACK Procedure( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );

    // ================================================================
    // --> DESTRUCTOR
    // ================================================================

        public : ~Application( );
};
#include "Application.h"

// ================================================================
// CONSTRUCTOR
// ================================================================

    // PUBLIC
    Application::Application( ) : m_hWnd( NULL ),
                                  m_pDirect2dFactory( NULL ),
                                  m_pRenderTarget( NULL ),
                                  m_pLightSlateGrayBrush( NULL ),
                                  m_pDWriteFactory( NULL ),
                                  m_pTextFormat( NULL )
    {

    }

// ================================================================
// METHOD -> CreateDeviceIndependentResources()
// ================================================================

    // PRIVATE
    HRESULT Application::CreateDeviceIndependentResources( )
    {
        HRESULT hr = S_OK;

        hr = D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pDirect2dFactory );

        if ( SUCCEEDED( hr ) )
        {
            hr = DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED,
                                      __uuidof( IDWriteFactory ),
                                      reinterpret_cast<IUnknown**>( &m_pDWriteFactory ) );
        }

        if ( SUCCEEDED( hr ) )
        {
            hr = m_pDWriteFactory->CreateTextFormat(
                L"Segoe UI",                // Font family name.
                NULL,                       // Font collection (NULL sets it to use the system font collection).
                DWRITE_FONT_WEIGHT_REGULAR,
                DWRITE_FONT_STYLE_NORMAL,
                DWRITE_FONT_STRETCH_NORMAL,
                12.0f,
                L"en-us",
                &m_pTextFormat
            );  
        }

        return hr;
    }

// ================================================================
// METHOD -> CreateDeviceDependentResources()
// ================================================================

    // PRIVATE
    HRESULT Application::CreateDeviceDependentResources()
    {
        HRESULT hr = S_OK;

        if ( !m_pRenderTarget )
        {
            RECT rc;

            GetClientRect( m_hWnd, &rc );

            D2D1_SIZE_U size = D2D1::SizeU( rc.right - rc.left, rc.bottom - rc.top );

            // Create a Direct2D render target.
            hr = m_pDirect2dFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties( ),
                                                             D2D1::HwndRenderTargetProperties( m_hWnd, size ),
                                                             &m_pRenderTarget );
           

            if ( SUCCEEDED( hr ) )
            {
                // Create a black brush.
                hr = m_pRenderTarget->CreateSolidColorBrush( D2D1::ColorF( D2D1::ColorF( 0.0F, 0.0F, 0.0F, 1.0F ) ),
                    &m_pLightSlateGrayBrush );
            }
        }

        return hr;
    }

// ================================================================
// METHOD -> DiscardDeviceDependentResources()
// ================================================================

    // PRIVATE
    void Application::DiscardDeviceDependentResources( )
    {
        SafeRelease( &m_pRenderTarget );
        SafeRelease( &m_pLightSlateGrayBrush );
        SafeRelease( &m_pDWriteFactory );
        SafeRelease( &m_pTextFormat );
        SafeRelease( &m_pTextLayout );
    }

// ================================================================
// METHOD -> Initialise()
// ================================================================

    // PUBLIC
    HRESULT Application::Initialise( HINSTANCE hInstance )
    {
        HRESULT hr;

        hr = CreateDeviceIndependentResources( );

        if ( SUCCEEDED( hr ) )
        {
            // Register the window class.
            WNDCLASSEX wcex = { sizeof( WNDCLASSEX ) };

            wcex.style = CS_HREDRAW | CS_VREDRAW;
            wcex.lpfnWndProc = Application::Procedure;
            wcex.cbClsExtra = 0;
            wcex.cbWndExtra = sizeof( LONG_PTR );
            wcex.hInstance = hInstance;
            wcex.hbrBackground = NULL;
            wcex.lpszMenuName = NULL;
            wcex.hCursor = LoadCursor( NULL, IDI_APPLICATION );
            wcex.lpszClassName = L"DirectX 12 Application";

            RegisterClassEx( &wcex );

            m_pDirect2dFactory->GetDesktopDpi( &m_dpiX, &m_dpiY );

            // Create the window.
            m_hWnd = CreateWindow( L"DirectX 12 Application",
                L"DirectX 12 Application",
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                1024,
                768,
                NULL,
                NULL,
                hInstance,
                this
            );

            hr = m_hWnd ? S_OK : E_FAIL;

            if ( SUCCEEDED( hr ) )
            {
                ShowWindow( m_hWnd, SW_SHOWNORMAL );
                UpdateWindow( m_hWnd );
            }
        }

        return hr;
    }

// ================================================================
// // METHOD -> MessageLoop()
// ================================================================

    // PUBLIC
    void Application::MessageLoop( )
    {
        MSG msg;

        while ( GetMessage( &msg, NULL, 0, 0 ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }

// ================================================================
// METHOD -> OnRender()
// ================================================================

    // PRIVATE
    HRESULT Application::OnRender( )
    {
        HRESULT hr = S_OK;

        hr = CreateDeviceDependentResources( );

        if ( SUCCEEDED( hr ) )
        {
            m_pRenderTarget->BeginDraw( );

            m_pRenderTarget->SetTransform( D2D1::Matrix3x2F::Identity( ) );

            m_pRenderTarget->Clear( D2D1::ColorF( D2D1::ColorF::White ) );

            D2D1_SIZE_F rtSize = m_pRenderTarget->GetSize( );

            // START : DIRECTWRITE

            // Create a text layout using the text format.
            if ( SUCCEEDED( hr ) )
            {


                D2D1_SIZE_F rtSize = m_pRenderTarget->GetSize( );

                // Align text to centre of layout box.
                m_pTextFormat->SetTextAlignment( DWRITE_TEXT_ALIGNMENT_CENTER );
                m_pTextFormat->SetParagraphAlignment( DWRITE_PARAGRAPH_ALIGNMENT_CENTER );

                const wchar_t* wszText_ = L"DirectX 12 Application";

                UINT32 cTextLength_ = ( UINT32 )wcslen( wszText_ );

                hr = m_pDWriteFactory->CreateTextLayout(
                    wszText_,       // The string to be laid out and formatted.
                    cTextLength_,   // The length of the string.
                    m_pTextFormat,  // The text format to apply to the string (contains font information, etc).
                    300.0F,         // The width of the layout box.
                    100.0F,         // The height of the layout box.
                    &m_pTextLayout  // The IDWriteTextLayout interface pointer.
                );
            }

            m_pRenderTarget->DrawTextLayout(
                D2D1_POINT_2F { ( ( rtSize.width / 2 ) - 150.0F ), ( ( rtSize.height / 2 ) - 50.0F ) },
                m_pTextLayout,
                m_pLightSlateGrayBrush,
                D2D1_DRAW_TEXT_OPTIONS_NONE
            );

            // END : DIRECTWRITE
            // ----------------------------------------------------------------

            hr = m_pRenderTarget->EndDraw( );
        }

        if ( hr == D2DERR_RECREATE_TARGET )
        {
            hr = S_OK;
            DiscardDeviceDependentResources( );
        }

        return hr;
    }

// ================================================================
// METHOD -> OnResize()
// ================================================================

    // PRIVATE
    void Application::OnResize( UINT height, UINT width )
    {
        if ( m_pRenderTarget )
        {
            m_pRenderTarget->Resize( D2D1::SizeU( width, height ) );
        }
    }

// ================================================================
// METHOD -> Procedure()
// ================================================================

    // PRIVATE, STATIC
    LRESULT CALLBACK Application::Procedure( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
    {
        LRESULT result = 0;

        if ( uMsg == WM_CREATE )
        {
            LPCREATESTRUCT pcs = ( LPCREATESTRUCT )lParam;

            Application *pApplication = ( Application * )pcs->lpCreateParams;

            ::SetWindowLongPtrW( hWnd,
                GWLP_USERDATA,
                PtrToUlong( pApplication )
            );

            result = 1;
        }
        else
        {
            Application *pApplication = reinterpret_cast< Application * >( static_cast< LONG_PTR >( ::GetWindowLongPtrW( hWnd, GWLP_USERDATA ) ) );

            bool wasHandled = false;

            if ( pApplication )
            {
                switch ( uMsg )
                {
                    case WM_DESTROY :
                        {
                            PostQuitMessage( 0 );
                        }

                        result = 1;

                        wasHandled = true;

                        break;

                    case WM_DISPLAYCHANGE :
                        {
                            InvalidateRect( hWnd, NULL, FALSE );
                        }

                        result = 0;

                        wasHandled = true;

                        break;

                    case WM_PAINT :
                        {
                            pApplication->OnRender( );

                            ValidateRect( hWnd, NULL );
                        }

                        result = 0;

                        wasHandled = true;

                        break;

                    case WM_SIZE :
                        {
                            UINT height = HIWORD( lParam );
                            UINT width = LOWORD( lParam );
                            
                            pApplication->OnResize( height, width );
                        }

                        result = 0;

                        wasHandled = true;

                        break;
                }
            }

            if ( !wasHandled )
            {
                result = DefWindowProc( hWnd, uMsg, wParam, lParam );
            }
        }

        return result;
    }

    // ================================================================
    // DESTRUCTOR
    // ================================================================

    // PUBLIC
    Application::~Application( )
    {
        SafeRelease( &m_pDirect2dFactory );
        SafeRelease( &m_pRenderTarget );
        SafeRelease( &m_pLightSlateGrayBrush );
        SafeRelease( &m_pDWriteFactory );
        SafeRelease( &m_pTextFormat );
        SafeRelease( &m_pTextLayout );
    }
#include "Application.h"

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int CmdShow )
{
    HeapSetInformation( NULL, HeapEnableTerminationOnCorruption, NULL, 0 );

    if ( SUCCEEDED( CoInitialize( NULL ) ) )
    {
        Application App;

        if ( SUCCEEDED( App.Initialise( hInstance ) ) )
        {
            App.MessageLoop( );
        }

        CoUninitialize( );
    }

    return 0;
}

Direct3D 11.3 and SM 5.1?

$
0
0
tldr; Shouldn't a ID3D11Device3 be able to load a vs_5_1 shader?
 
I'd like to make use of Dynamic Indexing which was made possible in SM5.1 - https://msdn.microsoft.com/en-gb/library/windows/desktop/mt186614(v=vs.85).aspx
 
As far as I can tell SM5.1 is available (at least partially?) in D3D11.3 - https://msdn.microsoft.com/en-us/library/windows/desktop/dn933277(v=vs.85).aspx
 
However if I 
  • write a simple vertex shader
  • compile it using fxc to a file (with /T vs_5_1)
  • then load that using ID3D11Device3::CreateVertexShader, it reports: D3D11 ERROR: ID3D11Device::CreateVertexShader: Shader must be vs_4_0, vs_4_1, or vs_5_0. Shader version provided: UNRECOGNIZED [ STATE_CREATION ERROR #167: CREATEVERTEXSHADER_INVALIDSHADERTYPE]
I'm using; Windows SDK 10.0.14393, d3dcompiler_47, fxc 10.1, D3D_FEATURE_LEVEL_11_1, 970GTX with driver 372.54, VC++ 14

Which Win 10 for Visual Studio / DirectX

$
0
0

I am going to buy a windows 10 system for use with visual c++ 2015 express.  The software is for 32 bit os but I here it works on 64 bit os?

 

The directX sdk can be obtained by getting windows sdk or downloading visula studio update three.  Does this sdk work on both windows 64 bit and windows 32 bit?

 

Which would you recommend buying the 32 bit or 64 bit Win10 with these two factors involved?

 

 

Thank you,

 

Josheir

C# DirectX 12 Samples

Bound but unused vertex buffers affecting the input layout?

$
0
0

I have a questions regarding vertex buffers and input layouts.

 

My mesh drawing code is essentially like this:

void DX11Mesh::Draw()
{
    mContext->IASetVertexBuffers(VertexBufferSlot::VERTEX_BUFFER_SLOT_POSITIONS, 1, &mVertexBuffer.p, &gPositionStride, &gStaticOffset);
    if (mNormalBuffer)
        mContext->IASetVertexBuffers(VertexBufferSlot::VERTEX_BUFFER_SLOT_NORMALS, 1, &mNormalBuffer.p, &gNormalStride, &gStaticOffset);
    if (mTexcoordBuffer)
        mContext->IASetVertexBuffers(VertexBufferSlot::VERTEX_BUFFER_SLOT_TEXCOORDS, 1, &mTexcoordBuffer.p, &gTexcoordStride, &gStaticOffset);
    if (mTangentBuffer)
        mContext->IASetVertexBuffers(VertexBufferSlot::VERTEX_BUFFER_SLOT_TANGENTS, 1, &mTangentBuffer.p, &gTangentStride, &gStaticOffset);
    if (mHasBones)
        mContext->IASetVertexBuffers(VertexBufferSlot::VERTEX_BUFFER_SLOT_BONE_WEIGHTS, 1, &mBoneWeightBuffer.p, &gBoneWeightStride, &gStaticOffset);

    mContext->IASetIndexBuffer(mIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
    mContext->DrawIndexed(mNumIndices, 0, 0);
}

Say the mesh has all the components (POSITIONS, NORMALS, TEXCOORDS, TANGENTS, BONE_WEIGHTS) but in some pass (like a shadowmap pass where the input layout only specifies the POSITIONS and BONE_WEIGHTS) the other vertex buffers (NORMALS, TEXCOORDS, TANGENTS) are still bound.

 

  1. Will each vertex still load those (unused) buffers, negatively impacting performance?
  2. Also does it make sense to "unbind" the vertex buffers after use? for example Mesh1 uses bones but Mesh2 dosn't, yet BONE_WEIGHTS will still be bound during Mesh2 pass.

SharpDXException while running samples

$
0
0

Hello everyone!

I'm working on a code samples from this github repository: https://github.com/Gitii/Direct3D-Rendering-Cookbook/tree/master/Ch02_01RenderingPrimitives

 

And when I'm running the code from the sample 'Ch02_01RenderingPrimitives', I'm getting the SharpDXException: Additional information: HRESULT: [0x887A002D], Module: [SharpDX.DXGI], ApiCode: [DXGI_ERROR_SDK_COMPONENT_MISSING/SdkComponentMissing].

 

I'm using Windows 10, with the Nvidia Geforce GTX 750TI. I have installed the Windows 10 SDK but it doesn't help.

Even my friend with Windows 10, but without this SDK can run those samples without any exceptions.

Can anyone help me? 

C# - Detect If Pre-Existing .DDS Contains Alpha Channel?

$
0
0

For the past wee while, I've been scouring the net to find a way to tell if a .dds file contains an alpha channel. And I've come up completely dry.

 

I've been working on a tool that sorts through all of the .dds file in a given directory, including it's sub-directories, and resizing all .dds images of a specified size to another. Pretty much just takes text from the gui, reads a couple bytes from the header of the .dds image, and then chucks it all to texconv.exe.

 

Thing is, I need to detect whether or not a .dds image uses transparency. If it does, include the -pmalpha argument when launching texconv.exe

 

How would I go about doing this? I've not much experience with C# (this program is my first foray into the language), and my sum total of programming experience is this and some Pascal for Tes5Edit, so I'll probably need to be explained to as if I'm 5 years old or somethin'.

 

I'm thinking that maybe SharpDX has some use for this? The documentation isn't, err, beginner friendly to say the least, sadly.

 

 

Anywho, if it helps at all, 'eres a couple links:

 

Current release of the program: http://www.nexusmods.com/fallout4/mods/17624/?

Current source code: https://github.com/MajinCry/Fallout-4-Texture-Resizer

[SOLVED]HLSL Syntax Clarification

$
0
0

Hi there! I hope I'm in the proper spot here. I've been trying for the life of me to try to figure out how a parallax shader works and have been trying to implement in the Source Engine. Needless to say I'm really held back by not having any math knowledge involving tangents, matrices, and whatnot.

 

But anyway, the question I'm asking is a little more simple than all that, and that's about the syntax of "const" in HLSL. There seem to be some shader header files that reference matrices and vectors that are labeled as const. Such as:

const HALF3 g_EyePos : register(c10);

I dunno if that's part of the HLSL language by default, I just know that in VS it says HALF3 is just a redefinition of float3. But why would something like g_EyePos, which clearly references eye position or camera position, be marked as const? Isn't that something that would be changing quite often? When I looked up the const syntax on Microsoft's website it says that it means it can't be changed in the shader.

 

Does it mean just that? That it can't be changed in the shader, but it's value may constantly be updated like in the C++ shader code through that c10 register? (I'm sorry, I don't know what you call it, so I'm calling it the c10 register, I know slightly more about GLSL than I do HLSL) Or does it mean it does not update at all?

 

Sorry for something that's probably a simple question, I just don't understand.


different results from VS debugger with debug device and normal device

$
0
0

Hi,

 

i have a serious problem with my engine, but i dont know where to locate the problem. The actual problem is that when I create a dx11 device context normally, my font rendering is messed up an looks ugly (see attached pictures) but when I run the vs graphic debugger with my engine, the engine is unnormal slow (in the past is was not so slow while debugging, now it's times 100 slower) but shows correct results (see attached pictures). So now i am a bit lost to find the reason for this behaviour, since the debug results look correct?! Does someone have hint where to look for this problem?

 

thx Moritz

 

worse.jpg

good.jpg

DirectX11 and using more than 1 shader

$
0
0

Hello everyone!

I'm learning DirectX for 2 weeks, and I know how to create primitives, add them to the scene and apply the Shader for the whole scene.

I can't find in any book or sample anything about applying the shader on a single Mesh (not on the every Mesh).

Can you tell me how can I apply a shader to a single Mesh ? I don't want to have just 1 pixel shader for every Mesh.

Texture array with mipmaps

$
0
0

Hello, a while ago i started to use texture arrays for multitexturing in terrain shader. I didn't know how to load image files for texture array, so i used ID3D11DeviceContext::CopySubresourceRegion to populate texture array with textures loaded with WICTextureLoader.

That looks like this:

	D3D11_TEXTURE2D_DESC textureDesc;
	D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
	ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc));
	ZeroMemory(&textureDesc, sizeof(textureDesc));

	textureDesc.Width = TEX_PIXEL_SIZE;
	textureDesc.Height = TEX_PIXEL_SIZE;
	textureDesc.MipLevels = 1;
	textureDesc.ArraySize = v_texFName.size() + 1;
	textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	textureDesc.SampleDesc.Count = 1;
	textureDesc.Usage = D3D11_USAGE_DEFAULT;
	textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
	textureDesc.CPUAccessFlags = 0;
	textureDesc.MiscFlags = 0;

	shaderResourceViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
	shaderResourceViewDesc.Texture2DArray.MostDetailedMip = 0;
	shaderResourceViewDesc.Texture2DArray.MipLevels = 1;
	shaderResourceViewDesc.Texture2DArray.ArraySize = v_texFName.size() + 1;
	shaderResourceViewDesc.Texture2DArray.FirstArraySlice = 0;

	HRESULT hr;
	hr = pd3dDevice->CreateTexture2D(&textureDesc, 0, &pTextureArray);
	if (FAILED(hr))
		debugMsg("FAIL pTextureArray: %d", hr);
	hr = pd3dDevice->CreateShaderResourceView(pTextureArray, &shaderResourceViewDesc, &pTextureSRV);
	if (FAILED(hr))
		debugMsg("FAIL pTextureSRV: %d", hr);

	WCHAR wcharstr[260];
	ID3D11Resource *pNewTexture;
	for (UINT i = 0; i < v_texFName.size(); i++)
	{
		MultiByteToWideChar(CP_ACP, 0, v_texFName[i]->text, -1, wcharstr, 260);
		CreateWICTextureFromFile(pd3dDevice, wcharstr, &pNewTexture, 0);
		DXUTGetD3D11DeviceContext()->CopySubresourceRegion(pTextureArray, i, 0, 0, 0, pNewTexture, 0, 0);
		SAFE_RELEASE(pNewTexture);
	}

Now after reading some articles i noticed that WICTextureLoader can automatically generate mipmaps.

CreateWICTextureFromFileEx(pd3dDevice, pDeviceContext, wcharstr, 0,
	D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, 0,
	D3D11_RESOURCE_MISC_GENERATE_MIPS, false, &pNewTexture, 0);

But now i don't know how to copy these mipmapped textures into texture array.

According to some articles it should work like this:

    textureDesc.MipLevels = 0;
    textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
    textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;

    shaderResourceViewDesc.Texture2DArray.MipLevels = -1;	

    // if texture has 9 mipmap levels
	for (UINT i = 0; i < v_texFName.size(); i++)
	{
		MultiByteToWideChar(CP_ACP, 0, v_texFName[i]->text, -1, wcharstr, 260);
		CreateWICTextureFromFileEx(pd3dDevice, DXUTGetD3D11DeviceContext(), wcharstr, 0,
			D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, 0,
			D3D11_RESOURCE_MISC_GENERATE_MIPS, false, &pNewTexture, 0);
		for (UINT j = 0; j < 9; j++)
			DXUTGetD3D11DeviceContext()->CopySubresourceRegion(pTextureArray, i * 9 + j, 0, 0, 0, pNewTexture, j, 0);
		SAFE_RELEASE(pNewTexture);
	}

But this doesn't seem to work. (it works only for the nearest mip level)

 

My questions are:

Why does a 256x256 px texture have 9 mip levels, and how do i get number of mip levels from a texture?

Why does the last code work only for the first mip level?

How do i populate a texture array with mipmapped textures?

DynamicSoundEffectInstance.BufferNeeded event not firing

$
0
0

When I start create my Speaker and feed it data it seems to only play the first buffer. The method that feeds in buffers first checks needbuffers flag and just returns and does nothing if it's false. My setneedbuffers event handler is never called (I set a break point in it) and needbuffers flag never gets set back to true.

 

If I pause execution and check the state of DynSoundInst it's still set to "playing". DynamicSoundEffectInstance is suposed to stop playback if its starved of data, but that's not the case here.

    public class Speaker_XNA : Speaker
    {
        DynamicSoundEffectInstance DynSoundInst;
        bool needbuffers = true;
        short bitspersample;

        public Speaker_XNA(short BitsPerSample, short Channels, int SamplesPerSecond)
        {
            FrameworkDispatcher.Update();
            DynSoundInst = new DynamicSoundEffectInstance(SamplesPerSecond, (AudioChannels)Channels);
            bitspersample = BitsPerSample;
            DynSoundInst.BufferNeeded += setneedbuffers;

        }
        private void setneedbuffers(object sender, EventArgs e)
        {
            needbuffers = true;
        }
...
}

Clarifications on sharing a 2d texture between D3D9Ex and D3D11

$
0
0

I'm trying to set up a shared texture (render target) such that it is created on a D3D11 device and subsequently opened and drawn to from a D3D9Ex device. Unfortunately I've found the information on how to actually go about this to be rather scarce and the debug layers don't seem to want to be more helpful than to tell me the "opened and created resources don't match". Therefore I thought I would ask and see if anybody around here would be able and willing to shed some more light on how resource sharing is supposed to be carried out?

 

So what I do is to first create a Texture2D from my IDirect3D11Device like so:

tex2DDesc.Width					= width;		// Tested with 256
tex2DDesc.Height				= height;		// Tested with 256
tex2DDesc.MipLevels				= 1;
tex2DDesc.ArraySize				= 1;
tex2DDesc.Format				= DXGI_FORMAT_A8G8B8R8_UNORM;
tex2DDesc.SampleDesc.Count			= 1;
tex2DDesc.SampleDesc.Quality		        = 0;
tex2DDesc.Usage					= D3D11_USAGE_DEFAULT;
tex2DDesc.BindFlags				= D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
tex2DDesc.CPUAccessFlags			= 0;
tex2DDesc.MiscFlags				= D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;

// Create render target
if(FAILED(gGlob.pDevice->CreateTexture2D(&tex2DDesc, nullptr, &pTexture2D)))
	Fail("Failed to create shared texture", "Could not create the shared texture!", 1);

// Create shader resource view
srvDesc.ViewDimension				= D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Format					= DXGI_FORMAT_A8G8B8R8_UNORM;
srvDesc.Texture2D.MipLevels			= 1;
srvDesc.Texture2D.MostDetailedMip	        = 0;
if(FAILED(gGlob.pDevice->CreateShaderResourceView(pTexture2D, &srvDesc, &pResourceView)))
        Fail("Failed to create shared texture", "Could not create SRV for shared texture!", 2);

// Obtain the keyed mutex interface
if(FAILED(pTexture2D->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&pMutex)))
	Fail("Failed to create shared texture", "Could not obtain resource locking interface!", 3);

// Obtain IDXGIResource interface for the texture; this is needed to get its shared handle
IDXGIResource *pResource = nullptr;
if(FAILED(pTexture2D->QueryInterface(__uuidof(IDXGIResource), (void**)&pResource)))
	Fail("Failed to create shared texture", "Could not obtain resource interface!", 4);
if(FAILED(pResource->GetSharedHandle(&hSharedResource)))
	Fail("Failed to create shared texture", "Could not obtain shared resource handle!", 5);
// Shouldn't need this open anymore; the handle should presumably be valid for as long as the 
// resource (the texture2d) remains in existance
SAFE_RELEASE(pResource);

After this, an attempt is made to access it from an IDirect3DDevice9Ex:

hr = m_pD3DEx->CreateTexture(iWidth, iHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pTexture, &hSharedResource);
// The above returns E_INVALIDARG

The D3D9 debug layer reports the following when invoking CreateTexture as per above:

Direct3D9: (ERROR) :Opened and created resources don't match, unable to open the shared resource.
Direct3D9: (ERROR) :Error during initialization of texture. CreateTexture failed.
Direct3D9: (ERROR) :Failure trying to create a texture

The D3D11 debug layer remains silent and all D3D11 calls above succeed.

 

From what I've been able to gather while searching for info on this, this seems to be how you are supposed to set it up. Most places that mention it seem to make a point of having D3D9Ex create the resource and then open it using ID3D11Device::OpenSharedResource however. But certainly this can't be a requirement? In my project it makes a whole lot better sense to have the D3D11 device create the shared textures than the other way around.

Furthermore there is the slightly ambigious route of getting the IDXGIResource interface from the IDXGITexture2d in order to obtain the shared handle. Could it be that you are in fact supposed to get this from somewhere else? The MSDN documentation seems prone to refer to surfaces when talking about resource sharing; is it in fact supposed to be so that you are supposed to be sharing the IDXGISurface view of the resource? But while D3D9 uses surfaces, what would the corresponding thing be in D3D11 if so, since it is apparently imperative that both resources be created / opened using the same type? (Furthermore it appears that texture resources should indeed be shareable out-of-the-box going by some mentions here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb219800(v=vs.85).aspx#Sharing_Resources).

 

 

Grateful for any pointers  :)

Visual Studio 2015 and Mesh Content Task

$
0
0

Hello!

This time I have a problem with working on Samples from Direct3D Rendering Cookbook (https://github.com/spazzarama/Direct3D-Rendering-Cookbook)

I'm working on Mesh Skinning, and when I'm running my app, I see the grid, but I can't see my Character.

It's probably because I didn't load Mesh Content Task files to my project, so I did this like it's mentioned in this article:

http://spazzarama.com/2013/11/20/visual-studio-graphics-content-pipeline-csharp-projects/

 

But after that I can't open my solution until I will remove that line mentioned in the article.

I have even tried to download the project from the repo of the Direct3D Rendering Cookbook, but I can't even open the Solution until I remove (again) the Mesh Content Task import line.

What to do?

[D3D12] Metals, Normal Mapping, Tessellation, Displacement Mapping


8x FSAA vs 8x MSAA

$
0
0
Hi Guys,

I have an issue where there is noticeable 'stair-casing' when using 8x MSAA.

L4bGA4o.png

(Image is zoomed 200% to highlight what is happening).

I am using MSAA on a render target (as global FSAA doesn't seem to have any effect on render targets).

I have double checked the render target and its dimensions are identical to the back buffer.

Is the difference between FSAA and MSAA normally this noticeable?

Thanks in advance :)

win10: no native support for pre-dx10 games. additional runtime required?

$
0
0

one of my testers was installing caveman 3 and got an error that d3dx9_43.dll is missing.

 

a google search revealed that win10 only has the runtime files for dx 10, 11, and 12, but not older versions, and one must DL the "directx end user runtime files" for win10 to get true DX capabilites for all versions of DX.

 

all true eh?

 

 

 

 

DirectX 11 Sharpdx - Instancing - ATI Vs Nvidia

$
0
0

Hi guys,

 

Working through a problem at the moment with myself and my team member around an issue with development.

 

So, here goes.

 

My PC currently has a ATI R290 card , his a GTX 960 card. (this may or may not be relevant based on some testing).

 

Currently I have instancing working with my game so basically I have 2 buffers being loaded into the GPU with instance and vertex data.  This works perfectly well on my R290 and my test machine (sans dev environment) with a ATI 7800. The buffer is a row_major matrix that Im loading for each instance.

 

On my team members PC, he has a GTX 960.  The issue is, and I have walked him through it is that the Instance buffer isn't loading in.  Now, I think I have coded in a way to be an issue.  

 

In the input assembler stage, I am loading the instance buffer in before loading the vertex buffer, in 2 separate calls.  I am also setting some other variables in the input assembler along the way.  Now they aren't being set in the same spot at the same time, but very close, only a few lines of code difference (But instance is being loaded ahead of vertex data).  This shouldn't really be an issue, and its not on my ATI cards. 

 

But my colleague has mentioned that the input assembler stage can be a little tempramental depending on the card being used.  SO.

 

I've rewritten the code to load the buffers at the same time.  2 different versons of the calls, 1 call using the Sharpdx buffer binding (setvertexbuffers call), and the other by passing the input array in including strides etc (different version sharpdx setvertexbuffers call).  

 

He is to test these, but I am wondering if there is anything else I may need to consider.

 

We narrowed it down to the instance buffer matrix not being passed by passing matrix via constant buffer instead and testing the code worked (rendered all objects in same spot, but it worked).  When it didn't work, it was rendering black triangles into the first half of the top right quartile of the screen (I had this also while developing instancing and it is consistent).

 

Sorry for the long post, I'm endeavouring to work through this one.  Will let you know my results, just any other suggestions?  At the least I've rewritten the code to test other vectors of attack, I hope he will be coming back with answers stating it works.  Otherwise, where to from here?

d3d11 frustum culling on gpu

$
0
0

I 'm going to implement frustum culling on gpu (not sure gs or cs ). 

First fill the consume structure buffer objects, and cull them, output to append structure buffer.

I 'm not sure is it efficient ?  and don't know the detail about how to use append/consume buffer ..

Any sample to learn ?

 

skip optimization + static const variable = bug?

$
0
0

Hello,

 

I have trouble with one of my shader, it works flawlessly optimized but if I compile it with skip optimization, it fails.

I tracked down the issue, it seems one of my static const variable (stored in r0 in asm) is being overwritten at some point.

 

Worth nothing that this happens in debug and release, with or without warp device and to the best of my knowledge is only related to the compilation process. The problem is clearly visible in the disassembled code.

 

The shader is quite long so I will post snippets of the shader with corresponding asm.

(I can post the whole shader or make a small program to illustrate the issue if needed).

static const float g_oneOverSqrt2 = 0.7071067811865475f;
static const float g_twoOverSqrt2 = 1.414213562373095f;

...

float4 decompressQuaternion(uint compressedQuaternion)
{
	uint4 uc = compressedQuaternion;
	uc >>= uint4(22, 12, 2, 0);
	uc &= uint4(1023, 1023, 1023, 3);
	float4 fc;
	fc.xyz = (float3)uc.xyz / 1023.0f * g_twoOverSqrt2 - g_oneOverSqrt2;
	fc.w = sqrt(1 - dot(fc.xyz, fc.xyz));
	if(uc.w == 0) return fc.wxyz;
	else if(uc.w == 1) return fc.xwyz;
	else if(uc.w == 2) return fc.xywz;
	else return fc.xyzw;
}

...

	const uint componentIndex = DTid.x;
	if(componentIndex < b_parameters.count)
	{
...
		float4 rotation = decompressQuaternion(p_data.rotation);
...
	}

The same sections in ASM looks like this:

// Init static const variables
mov r0.x, l(0.707107)  // NOTE: r0.x <- g_oneOverSqrt2
// At this point r0.x == g_oneOverSqrt2

// The asm version of the if(componentIndex < b_parameters.count)
mov r0.w, vThreadID.x  // r0.w <- componentIndex
ult r1.x, r0.w, CB0[0][0].w
if_nz r1.x
  mov r0.x, CB0[0][0].w  // r0.x <- b_parameters.count
// Just above, r0.x is overwritten by CB0[0][0].w

// The asm version of decompressQuaternion,
// note the use of the r0.x
  mov r7.xyzw, r7.xyzw
  mov r8.xyz, l(22,12,2,0)
  ushr r7.xyz, r7.xyzx, r8.xyzx
  mov r8.xyzw, l(1023,1023,1023,3)
  and r7.xyzw, r7.xyzw, r8.xyzw
  utof r7.xyz, r7.xyzx
  div r7.xyz, r7.xyzx, l(1023.000000, 1023.000000, 1023.000000, 0.000000)
  mul r7.xyz, r0.yyyy, r7.xyzx
  mov r8.xyz, -r0.xxxx              // NOTE: use of r0.x
  add r7.xyz, r7.xyzx, r8.xyzx
  itof r0.x, l(1)
  dp3 r0.y, r7.xyzx, r7.xyzx
  mov r0.y, -r0.y
  add r0.x, r0.y, r0.x
  sqrt r8.w, r0.x
  if_z r7.w
    mov r8.x, r8.w
    mov r8.yzw, r7.xxyz
  else
    mov r0.x, l(1)
    ieq r0.x, r0.x, r7.w
    if_nz r0.x
      mov r8.y, r8.w
      mov r8.zw, r7.yyyz
    else
      mov r0.x, l(2)
      ieq r0.x, r0.x, r7.w
      if_nz r0.x
        mov r8.z, r8.w
        mov r8.w, r7.z
      else
        mov r8.z, r7.z
        mov r8.w, r8.w
      endif 
      mov r8.y, r7.y
    endif 
    mov r8.x, r7.x
  endif 

I have avoided the issue by using literals in the shader code for oneOverSqrt2 and twoOverSqrt2 but I tend to use static const variable to share code between c++ and hlsl and using macros is messing up my design.

 

Anyone else had trouble with static const variables in un-optimized shaders?

 

Cheers!

Viewing all 17560 articles
Browse latest View live


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