Count field incorrect syntax error - c++

for the last several days i'm trying to connect to store procedure using ODBC.
This is my CRecordset code:
sp_insertSesMessageStore::sp_insertSesMessageStore(CDatabase* pdb)
: CRecordset(pdb){
// Param Init
m_RETURN_VALUE = -1;
m_PROVIDER_IDParam = _T("");
m_BRANCH_IDParam = _T("");
m_ACCOUNTParam = _T("");
m_SES_USER_UNIQUE_IDParam = _T("");
m_DISPLAY_NAMEParam = _T("");
m_SMTP_ADDRESSParam = _T("");
m_MESSAGE_TYPE_IDParam = 0;
m_PRIORITYParam = 0;
m_SUBJECTParam = _T("");
m_SUMMARYParam = _T("");
m_TEMPLATE_IDParam = _T("");
m_BODY_TYPE_IDParam = 0;
m_TRACKING_IDParam = _T("");
m_EXPIRATION_TIMEParam = _T("");
m_SUBCATEGORY_IDParam = 0;
m_FOLDER_IDParam = 0;
m_NUM_ATTACHMENTSParam = 0;
m_ACCESS_IDParam = _T("");
m_FLAGSParam = 0;
m_FAVORITEParam = FALSE;
m_CERTIFIED_IDParam = _T("");
m_SECURE_RESPONSE_OTPParam = _T("");
m_MESSAGE_IDParam = _T("");
m_nParams = 24;
m_nDefaultType = snapshot;}
This is the DoDataExchange.
void sp_insertSesMessageStore::DoFieldExchange(CFieldExchange* pFX){
// RFX output param mapping
/*pFX->SetFieldType(CFieldExchange::outputParam);
RFX_Long(pFX, _T("[#RETURN_VALUE]"), m_RETURN_VALUE);*/
// RFX input param mapping
pFX->SetFieldType(CFieldExchange::inputParam);
RFX_Text(pFX, _T("[#PROVIDER_ID]"), m_PROVIDER_IDParam, 3);
RFX_Text(pFX, _T("[#BRANCH_ID]"), m_BRANCH_IDParam, 50);
RFX_Text(pFX, _T("[#ACCOUNT]"), m_ACCOUNTParam, 255);
RFX_Text(pFX, _T("[#SES_USER_UNIQUE_ID]"), m_SES_USER_UNIQUE_IDParam, 8);
RFX_Text(pFX, _T("[#DISPLAY_NAME]"), m_DISPLAY_NAMEParam, 255);
RFX_Text(pFX, _T("[#SMTP_ADDRESS]"), m_SMTP_ADDRESSParam, 255);
RFX_Int(pFX, _T("[#MESSAGE_TYPE_ID]"), m_MESSAGE_TYPE_IDParam);
RFX_Byte(pFX, _T("[#PRIORITY]"), m_PRIORITYParam);
RFX_Text(pFX, _T("[#SUBJECT]"), m_SUBJECTParam, 255);
RFX_Text(pFX, _T("[#SUMMARY]"), m_SUMMARYParam, 255);
RFX_Text(pFX, _T("[#TEMPLATE_ID]"), m_TEMPLATE_IDParam, 255);
RFX_Int(pFX, _T("[#BODY_TYPE_ID]"), m_BODY_TYPE_IDParam);
RFX_Text(pFX, _T("[#TRACKING_ID]"), m_TRACKING_IDParam, 255);
RFX_Text(pFX, _T("[#EXPIRATION_TIME]"), m_EXPIRATION_TIMEParam, 16);
RFX_Int(pFX, _T("[#SUBCATEGORY_ID]"), m_SUBCATEGORY_IDParam);
RFX_Int(pFX, _T("[#FOLDER_ID]"), m_FOLDER_IDParam);
RFX_Int(pFX, _T("[#NUM_ATTACHMENTS]"), m_NUM_ATTACHMENTSParam);
RFX_LongBinary(pFX, _T("[#BODY]"), m_BODYParam);
RFX_Text(pFX, _T("[#ACCESS_ID]"), m_ACCESS_IDParam, 255);
RFX_Long(pFX, _T("[#FLAGS]"), m_FLAGSParam);
RFX_Bool(pFX, _T("[#FAVORITE]"), m_FAVORITEParam);
RFX_Text(pFX, _T("[#CERTIFIED_ID]"), m_CERTIFIED_IDParam, 100);
RFX_Text(pFX, _T("[#SECURE_RESPONSE_OTP]"), m_SECURE_RESPONSE_OTPParam, 50);
// RFX input_output param mapping
pFX->SetFieldType(CFieldExchange::inoutParam);
RFX_Text(pFX, _T("[#MESSAGE_ID]"), m_MESSAGE_IDParam, 8);}
BOOL sp_insertSesMessageStore::ExecDirect(){
return Open(CRecordset::forwardOnly, GetDefaultSQL(), CRecordset::executeDirect);}
This is the statement i'm passing.
CString sp_insertSesMessageStore::GetDefaultSQL(){
return _T("{CALL sp_insertSesMessageStore (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");}
This is an auto generated code from a tool i found on the web.
I had isolated the problem, the cause of this exception is the CLongBinary member, can't find the issue, any suggestions?!

Related

DxgiOuputDuplication texture frames to DirectX VideoProcessor

I was playing with this project DirectXVideoScreen because I am trying to find a way to convert RGBA to NV12 so I can make a video using the h264 transformation of my GPU. (You can only use the transformation when you have NV12 or YUV2 color format)
I have tried doing the color conversion using the Windows Media Foundation MFT (Video processor) but I am trying to go directly and use DirectX in order to have more control.
While you duplicate the screen the texture you get back is of type DXGI_FORMAT_B8G8R8A8_UNORM and I have to transform it to DXGI_FORMAT_NV12.
So I took the code from the project "D3D11VideoProcessor" and added the code from the "SimpleDesktopDuplication" project.
It is like this.
CD3D11VideoProcessor cD3D11VideoProcessor;
CSimpleDesktopDuplication cSimpleDesktopDuplication;
ID3D11Texture2D* output = NULL;
if (cSimpleDesktopDuplication.InitDesktopDuplication() == S_OK)
{
output = cSimpleDesktopDuplication.ProcessDesktopDuplication();
}
if(cD3D11VideoProcessor.InitDXVA2(2560,1440, DXGI_FORMAT_NV12) == S_OK)
{
cD3D11VideoProcessor.ProcessImageConversion(output, CONVERTED_IMAGE);
}
The problem (I think?) is that
m_pDXGIOutputDuplication->AcquireNextFrame(500, &FrameInfo, &pDXGIResource));
pDXGIResource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&pScreenShotTexture2D)));
Returns a texture with the following flags.
Width: a00
Height: 5a0
MipLevels: 1
ArraySize: 1
Format: 57
Usage: 0
BindFlags: 28 // D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE
CPUAccessFlags: 0
MiscFlags: 2900
And here the code fails while executing
m_pD3D11VideoContext->VideoProcessorBlt(m_pD3D11VideoProcessor, pD3D11VideoProcessorOutputView, 0, 1, &StreamData)
HRESULT CD3D11VideoProcessor::ProcessImageConversion(ID3D11Texture2D* outputDuplicationTexture, LPCWSTR wszOutputImageFile)
{
HRESULT hr = S_OK;
ID3D11VideoProcessorInputView* pD3D11VideoProcessorInputViewIn = NULL;
ID3D11VideoProcessorOutputView* pD3D11VideoProcessorOutputView = NULL;
ID3D11VideoDevice* pD3D11VideoDevice = NULL;
ID3D11Texture2D* pOutTexture2D = NULL;
IF_FAILED_RETURN(m_pD3D11VideoContext == NULL ? E_UNEXPECTED : S_OK);
try
{
IF_FAILED_THROW(m_pD3D11Device->QueryInterface(__uuidof(ID3D11VideoDevice), reinterpret_cast<void**>(&pD3D11VideoDevice)));
D3D11_TEXTURE2D_DESC desc2D;
desc2D.Width = 2560;
desc2D.Height = 1440;
desc2D.MipLevels = 1;
desc2D.ArraySize = 1;
desc2D.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc2D.SampleDesc.Count = 1;
desc2D.SampleDesc.Quality = 0;
desc2D.Usage = D3D11_USAGE_DEFAULT;
desc2D.BindFlags = D3D11_BIND_RENDER_TARGET;
desc2D.CPUAccessFlags = 0;
desc2D.MiscFlags = 0;
D3D11_TEXTURE2D_DESC desc2Dtmp;
outputDuplicationTexture->GetDesc(&desc2Dtmp);
printf("Width: %x\n", desc2Dtmp.Width);
printf("Height: %x\n", desc2Dtmp.Height);
printf("MipLevels: %x\n", desc2Dtmp.MipLevels);
printf("ArraySize: %x\n", desc2Dtmp.ArraySize);
printf("Format: %x\n", desc2Dtmp.Format);
printf("Usage: %x\n", desc2Dtmp.Usage);
printf("BindFlags: %x\n", desc2Dtmp.BindFlags);
printf("CPUAccessFlags: %x\n", desc2Dtmp.CPUAccessFlags);
printf("MiscFlags: %x\n", desc2Dtmp.MiscFlags);
D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC pInDesc;
ZeroMemory(&pInDesc, sizeof(pInDesc));
pInDesc.FourCC = 0;
pInDesc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D;
pInDesc.Texture2D.MipSlice = 0;
pInDesc.Texture2D.ArraySlice = 0;
IF_FAILED_THROW(pD3D11VideoDevice->CreateVideoProcessorInputView(outputDuplicationTexture, m_pD3D11VideoProcessorEnumerator, &pInDesc, &pD3D11VideoProcessorInputViewIn));
desc2D.Format = DXGI_FORMAT_NV12;
IF_FAILED_THROW(m_pD3D11Device->CreateTexture2D(&desc2D, NULL, &pOutTexture2D));
D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC pOutDesc;
ZeroMemory(&pOutDesc, sizeof(pOutDesc));
pOutDesc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D;
pOutDesc.Texture2D.MipSlice = 0;
IF_FAILED_THROW(pD3D11VideoDevice->CreateVideoProcessorOutputView(pOutTexture2D, m_pD3D11VideoProcessorEnumerator, &pOutDesc, &pD3D11VideoProcessorOutputView));
D3D11_VIDEO_PROCESSOR_STREAM StreamData;
ZeroMemory(&StreamData, sizeof(StreamData));
StreamData.Enable = TRUE;
StreamData.OutputIndex = 0;
StreamData.InputFrameOrField = 0;
StreamData.PastFrames = 0;
StreamData.FutureFrames = 0;
StreamData.ppPastSurfaces = NULL;
StreamData.ppFutureSurfaces = NULL;
StreamData.pInputSurface = pD3D11VideoProcessorInputViewIn;
StreamData.ppPastSurfacesRight = NULL;
StreamData.ppFutureSurfacesRight = NULL;
/*Error is here !!!*/
IF_FAILED_THROW(m_pD3D11VideoContext->VideoProcessorBlt(m_pD3D11VideoProcessor, pD3D11VideoProcessorOutputView, 0, 1, &StreamData));
IF_FAILED_THROW(CreateBmpFileFromYUVSurface(pOutTexture2D, wszOutputImageFile));
}
catch(HRESULT){}
SAFE_RELEASE(pOutTexture2D);
SAFE_RELEASE(outputDuplicationTexture);
SAFE_RELEASE(pD3D11VideoProcessorOutputView);
SAFE_RELEASE(pD3D11VideoProcessorInputViewIn);
SAFE_RELEASE(pD3D11VideoDevice);
return hr;
}
The error code is 0x80070057 meaning E_INVALIDARG One or more arguments are invalid.. I can not find the invalid arg :/
Can you help me ? or guide me ? Maybe I have to somehow change the ID3D11Texture2D* outputDuplicationTexture to match a simpler version of the texture (change misc params) ?
Thank you!

AUGraph Record and Play

When I use AUGraph to implemention record and play, I want to get audio data through RenderCallback.There is a problem in remote io unit callback with error kAudioConverterErr_InvalidInputSize(1768846202),I don't know how to solve it.
Is there any other way to get audio data?
NSAssert(NewAUGraph(&_auGraph) == noErr, #"NewAUGraph failed");
const AudioComponentDescription ioComponentDesc = {
.componentType = kAudioUnitType_Output,
.componentSubType = kAudioUnitSubType_RemoteIO,
.componentManufacturer = kAudioUnitManufacturer_Apple,
.componentFlags = 0,
.componentFlagsMask = 0
};
AUGraphAddNode(_auGraph, &ioComponentDesc, &_ioNode);
const AudioComponentDescription effectComponent = {
.componentType = kAudioUnitType_Effect,
.componentSubType = kAudioUnitSubType_Reverb2,
.componentManufacturer = kAudioUnitManufacturer_Apple,
.componentFlags = 0,
.componentFlagsMask = 0
};
AUGraphAddNode(_auGraph, &effectComponent, &_reverbNode);
const AudioComponentDescription inConvertComponentDesc = {
.componentType = kAudioUnitType_FormatConverter,
.componentSubType = kAudioUnitSubType_AUConverter,
.componentManufacturer = kAudioUnitManufacturer_Apple,
.componentFlags = 0,
.componentFlagsMask = 0
};
AUGraphAddNode(_auGraph, &inConvertComponentDesc, &_inConvertNode);
const AudioComponentDescription outConvertComponentDesc = {
.componentType = kAudioUnitType_FormatConverter,
.componentSubType = kAudioUnitSubType_AUConverter,
.componentManufacturer = kAudioUnitManufacturer_Apple,
.componentFlags = 0,
.componentFlagsMask = 0
};
AUGraphAddNode(_auGraph, &outConvertComponentDesc, &_outConvertNode);
NSAssert(AUGraphOpen(_auGraph) == noErr, #"AUGraphOpen failed");
AUGraphNodeInfo(_auGraph, _ioNode, NULL, &_ioUnit);
AUGraphNodeInfo(_auGraph, _reverbNode, NULL, &_reverbUnit);
AUGraphNodeInfo(_auGraph, _inConvertNode, NULL, &_inConvertUnit);
AUGraphNodeInfo(_auGraph, _outConvertNode, NULL, &_outConvertUnit);
UInt32 enable = 1;
AudioUnitElement inputBus = 1;
AudioUnitElement outputBus = 0;
AudioUnitSetProperty(_ioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, inputBus, &enable, sizeof(enable));
AudioUnitSetProperty(_ioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, outputBus, &enable, sizeof(enable));
AudioStreamBasicDescription absd;
memset(&absd, 0, sizeof(absd));
absd.mSampleRate = 44100;
absd.mFormatID = kAudioFormatLinearPCM;
absd.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
absd.mBitsPerChannel = 16;
absd.mChannelsPerFrame = 2;
absd.mBytesPerFrame = absd.mBitsPerChannel / 8 * absd.mChannelsPerFrame;
absd.mFramesPerPacket = 1;
absd.mBytesPerPacket = absd.mBytesPerFrame;
AudioUnitSetProperty(_ioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &absd, sizeof(absd));
AudioUnitSetProperty(_ioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, outputBus, &absd, sizeof(absd));
AURenderCallbackStruct callback = {0};
callback.inputProc = audioUnitRenderCallback;
callback.inputProcRefCon = (__bridge void *)self;
AudioUnitSetProperty(_ioUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input,
outputBus,
&callback,
sizeof(callback));
OSStatus status;
AudioStreamBasicDescription reverbABSD;
memset(&reverbABSD, 0, sizeof(reverbABSD));
reverbABSD.mSampleRate = 44100;
reverbABSD.mFormatID = kAudioFormatLinearPCM;
reverbABSD.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
reverbABSD.mBitsPerChannel = 32;
reverbABSD.mChannelsPerFrame = 2;
reverbABSD.mBytesPerFrame = reverbABSD.mBitsPerChannel / 8;
reverbABSD.mFramesPerPacket = 1;
reverbABSD.mBytesPerPacket = reverbABSD.mBytesPerFrame;
AudioUnitSetProperty(_reverbUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &reverbABSD, sizeof(reverbABSD));
AudioUnitSetProperty(_reverbUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &reverbABSD, sizeof(reverbABSD));
AudioUnitSetParameter(_reverbUnit, kReverb2Param_Gain, kAudioUnitScope_Global, 0, 20, 0);
AudioUnitSetParameter(_reverbUnit, kReverb2Param_DryWetMix, kAudioUnitScope_Global, 0, 50, 0);
status = AudioUnitSetProperty(_outConvertUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &reverbABSD, sizeof(reverbABSD));
status = AudioUnitSetProperty(_outConvertUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &absd, sizeof(absd));
AUGraphConnectNodeInput(_auGraph, _ioNode, 1, _inConvertNode, 0);
AUGraphConnectNodeInput(_auGraph, _inConvertNode, 0, _reverbNode, 0);
AUGraphConnectNodeInput(_auGraph, _reverbNode, 0, _outConvertNode, 0);
static OSStatus audioUnitRenderCallback(void * inRefCon,
AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp * inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList * __nullable ioData)
{
XLAudioCaptureGraph *THIS = (__bridge XLAudioCaptureGraph *)inRefCon;
memset(ioData->mBuffers[0].mData, 0, ioData->mBuffers[0].mDataByteSize);
OSStatus status = AudioUnitRender(THIS.outConvertUnit, ioActionFlags, inTimeStamp, 0, inNumberFrames, ioData);
}
The audioUnitRenderCallback status return kAudioConverterErr_InvalidInputSize.

I can't assign a texture to IMGUI because I can't create directx texture

I'm trying to add some images for using with IMGUI library. Basically, IMGUI can get directx or OpenGL raw texture data to draw. You can see example code from IMGUI for creating a texture ;
// Simple helper function to load an image into a DX11 texture with common settings
bool LoadTextureFromFile(const char* filename, ID3D11ShaderResourceView** out_srv, int* out_width, int* out_height)
{
// Load from disk into a raw RGBA buffer
int image_width = 0;
int image_height = 0;
unsigned char* image_data = stbi_load(filename, &image_width, &image_height, NULL, 4);
if (image_data == NULL)
return false;
// Create texture
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = image_width;
desc.Height = image_height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D11Texture2D *pTexture = NULL;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = image_data;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, out_srv);
pTexture->Release();
*out_width = image_width;
*out_height = image_height;
stbi_image_free(image_data);
return true;
}
Everything is ok except 'g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);' line. Because as you can see g_pd3dDevice is undefined. That's why I put a line for this like : ID3D11Device* g_pd3dDevice = nullptr; but when I run code it hangs.. I guess I must create a 3ddevice before using this part. But I can't. Any suggestions? Thanks
Now I can get some image but it's wrong:
Now my code like this ;
bool LoadTextureFromBufferDX11(unsigned char* address, ID3D11ShaderResourceView** out_srv, int* out_width, int* out_height)
{
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
::RegisterClassEx(&wc);
//HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 200, 200, NULL, NULL, wc.hInstance, NULL);
HWND hwnd = GetForegroundWindow();
CreateDeviceD3D(hwnd);
/*
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
*/
//ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Load from disk into a raw RGBA buffer
int image_width = 0;
int image_height = 0;
const char* filename = "e:\\obama.png";
unsigned char* image_data = stbi_load(filename, &image_width, &image_height, NULL, 4);
//unsigned char* image_data = address;
if (image_data == NULL)
return false;
// Create texture
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = image_width;
desc.Height = image_height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D11Texture2D *pTexture = NULL;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = image_data;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, out_srv);
pTexture->Release();
*out_width = image_width;
*out_height = image_height;
return true;
}
And I trigger this function from host app.
static ID3D11ShaderResourceView* my_texture = NULL;
int my_image_width = 0;
int my_image_height = 0;
fn_export double imgui_showimage(unsigned char* address) {
bool ret = LoadTextureFromBufferDX11(address, &my_texture, &my_image_width, &my_image_height);
//IM_ASSERT(ret);
//ImGui::Image((void*)my_texture, ImVec2(my_image_width, my_image_height));
return 1;
}
And I draw imgu image from host like ;
fn_export double imgui_image(char* address) {
ImGui::Image((void*)my_texture, ImVec2(my_image_width, my_image_height));
return 1;
}

Direct X: How to display an image loaded in a texture?

I'm new to DirectX and have been reading tons of tutorials and samples, however I'm unable to find any documentation on how to directly display an image that is loaded into a Texture2D on the screen. Almost all tutorials I've seen deal with 3D graphics, shaders, etc. However, I just want to display the contents of the texture.
Here's what I have so far:
DeviceResources.cpp:
#include "DeviceResources.h"
#include "Renderer.h"
DeviceResources::DeviceResources()
{
}
HRESULT DeviceResources::CreateDeviceResources(HWND hwnd)
{
D3D_FEATURE_LEVEL levels[] = {
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_12_0,
D3D_FEATURE_LEVEL_12_1
};
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
DXGI_SWAP_CHAIN_DESC swap_chain_desc;
ZeroMemory(&swap_chain_desc, sizeof(DXGI_SWAP_CHAIN_DESC));
swap_chain_desc.Windowed = TRUE;
swap_chain_desc.BufferCount = 2;
swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R10G10B10A2_UNORM;
swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap_chain_desc.SampleDesc.Count = 1;
swap_chain_desc.SampleDesc.Quality = 0;
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
swap_chain_desc.OutputWindow = hwnd;
Microsoft::WRL::ComPtr<ID3D11Device> device;
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context;
Microsoft::WRL::ComPtr<IDXGISwapChain> swapChain;
D3D11CreateDeviceAndSwapChain(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
flags,
levels,
ARRAYSIZE(levels),
D3D11_SDK_VERSION,
&swap_chain_desc,
swapChain.GetAddressOf(),
device.GetAddressOf(),
&m_feature_level,
context.GetAddressOf()
);
device.As(&m_device);
context.As(&m_context);
swapChain.As(&m_swapChain);
cv::directx::ocl::initializeContextFromD3D11Device(m_device.Get());
auto hdr = Renderer::HDRMetadata();
m_swapChain->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(DXGI_HDR_METADATA_HDR10), &hdr);
m_swapChain->SetColorSpace1(DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020);
m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), static_cast<void**>(& m_backBuffer));
m_backBuffer->GetDesc(&m_bbDesc);
ZeroMemory(&m_viewport, sizeof(D3D11_VIEWPORT));
m_viewport.Height = static_cast<float>(m_bbDesc.Height);
m_viewport.Width = static_cast<float>(m_bbDesc.Width);
m_viewport.MinDepth = 0;
m_viewport.MaxDepth = 1;
m_context->RSSetViewports(1, &m_viewport);
m_device->CreateRenderTargetView(m_backBuffer.Get(), nullptr, m_renderTargetView.GetAddressOf());
return S_OK;
}
HRESULT DeviceResources::ConfigureBackBuffer()
{
m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), static_cast<void**>(& m_backBuffer));
m_device->CreateRenderTargetView(m_backBuffer.Get(), nullptr, m_renderTargetView.GetAddressOf());
m_backBuffer->GetDesc(&m_bbDesc);
ZeroMemory(&m_viewport, sizeof(D3D11_VIEWPORT));
m_viewport.Height = static_cast<float>(m_bbDesc.Height);
m_viewport.Width = static_cast<float>(m_bbDesc.Width);
m_viewport.MinDepth = 0;
m_viewport.MaxDepth = 1;
m_context->RSSetViewports(1, &m_viewport);
return S_OK;
}
HRESULT DeviceResources::ReleaseBackBuffer()
{
m_renderTargetView.Reset();
m_backBuffer.Reset();
m_context->Flush();
return S_OK;
}
HRESULT DeviceResources::SetFullscreen(bool fullscreen)
{
m_swapChain->SetFullscreenState(fullscreen, nullptr);
ReleaseBackBuffer();
m_swapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
ConfigureBackBuffer();
return S_OK;
}
void DeviceResources::Present()
{
m_swapChain->Present(1, 0);
}
DeviceResources::~DeviceResources()
= default;
Renderer.cpp:
#include "Renderer.h"
#include <utility>
#include <comdef.h>
#include <vector>
Renderer::Renderer(std::shared_ptr<DeviceResources> resources) : m_resources(std::move(resources)), m_frameCount(0)
{
m_frameCount = 0;
}
HRESULT Renderer::CreateDeviceDependentResources()
{
return S_OK;
}
HRESULT Renderer::CreateWindowSizeDependentResources()
{
return S_OK;
}
void Renderer::Update()
{
//
}
void Renderer::Render()
{
cv::Mat mat = cv::imread("C:/Users/Richard/Downloads/orig_cave_L.ppm", cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH);
cv::Mat as4channelMat(mat.size(), CV_MAKE_TYPE(mat.depth(), 4));
int conversion[] = { 0, 0, 1, 1, 2, 2, -1, 3 };
cv::mixChannels(&mat, 1, &as4channelMat, 1, conversion, 4);
D3D11_TEXTURE2D_DESC desc;
desc.Width = 3840;
desc.Height = 2160;
desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R16G16B16A16_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;
ID3D11Texture2D* tex = nullptr;
auto hr = m_resources->GetDevice()->CreateTexture2D(&desc, nullptr, &tex);
if FAILED(hr)
{
_com_error err(hr);
auto errMsg = err.ErrorMessage();
}
try {
cv::directx::convertToD3D11Texture2D(as4channelMat, tex);
} catch (cv::Exception& e)
{
std::cerr << "ERROR: " << e.msg << std::endl;
throw e;
}
auto hr3 = m_resources->m_device->CreateShaderResourceView(tex.Get(), nullptr, m_texture.GetAddressOf());
if FAILED(hr3)
{
_com_error err(hr3);
auto errMsg = err.ErrorMessage();
}
std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch;
DirectX::SimpleMath::Vector2 m_screenPos, m_origin;
m_spriteBatch = std::make_unique<DirectX::SpriteBatch>(m_resources->m_context.Get());
CD3D11_TEXTURE2D_DESC catDesc;
tex->GetDesc(&catDesc);
m_origin.x = float(catDesc.Width / 2);
m_origin.y = float(catDesc.Height / 2);
m_screenPos.x = m_resources->m_bbDesc.Width / 2.f;
m_screenPos.y = m_resources->m_bbDesc.Height / 2.f;
m_spriteBatch->Begin();
m_spriteBatch->Draw(
m_texture.Get(),
m_screenPos,
nullptr,
DirectX::Colors::White,
0.0f,
m_origin
);
m_spriteBatch->End();
}
DXGI_HDR_METADATA_HDR10 Renderer::HDRMetadata()
{
//
}
Renderer::~Renderer()
{
}
From my understand, I have to somehow create a "Quad", apply the texture to it, and then display the quad itself. However,I am unsure how to do any of this and can't find any resources to help.
Edit: Given the recommendations, I have tried using DirectXTK, specifically SpriteBatch. I followed the relevant instructions in the documentation, however Draw doesn't seem to do / display anything. (In Renderer.cpp)

correct resizing of D2D over D3D

I have problem with resizing D2D render target over D3D11. I make function to resize swap chain buffer.
It works great, but when I activate D2D, resizing became broken.
When I make window smaller, all meshes disappear from window - only text displayed.
When I make bigger - meshes rendered, but proportions not correct, despite that I recreate projection Matrix.
My question is - how to correctly resize D2D render target and text after window size changed?
Here is my code for creating D3D11Device, swapchain1 and D2D.
bool D3D11::InitializeD3D11(HWND hwnd, SettingsContainer* settingsContainer)
{
this->hwnd = hwnd;
HRESULT result;
IDXGIFactory2* factory;
IDXGIAdapter* adapter;
IDXGIOutput* adapterOutput;
D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_UNKNOWN;
unsigned int numModes, numerator, denominator;
DXGI_MODE_DESC* displayModeList;
DXGI_ADAPTER_DESC adapterDesc;
DXGI_OUTPUT_DESC displayDesc;
DXGI_SWAP_CHAIN_DESC1 swapChainDescription;
D3D_FEATURE_LEVEL featureLevel;
ID3D11Texture2D* backBufferPtr;
D3D11_TEXTURE2D_DESC depthBufferDescription;
D3D11_DEPTH_STENCIL_DESC depthStencilDescription;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDescription;
D3D11_RASTERIZER_DESC rasterizerDescription;
D3D11_VIEWPORT viewPort;
D3D11_DEPTH_STENCIL_DESC depthStencilDescriptionDisabled;
D3D11_BLEND_DESC blendStateDescrition;
AdapterInfo* adapterInfo;
DisplayInfo* displayInfo;
adapterInfo = NULL;
//Создаём фабрику графических интерфейсов DX
result = CreateDXGIFactory1(__uuidof(IDXGIFactory2), (void**)&factory);
if (FAILED(result))
{
return false;
}
/*IDXGIDevice2 * pDXGIDevice;
result = d3d11_Device->QueryInterface(__uuidof(IDXGIDevice2), (void **)&pDXGIDevice);*/
/*IDXGIAdapter * pDXGIAdapter;
result = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter);*/
/*IDXGIFactory2 * pIDXGIFactory;
pDXGIAdapter->GetParent(__uuidof(IDXGIFactory2), (void **)&pIDXGIFactory);*/
//pIDXGIFactory->EnumAdapters1(0,&adapter);
//adapter->EnumOutputs(0, &adapterOutput);
//Достаём все графические адаптеры
for (UINT i = 0; factory->EnumAdapters(i,&adapter)!= DXGI_ERROR_NOT_FOUND;++i)
{
adapterInfo = new AdapterInfo(adapter);
adapter->GetDesc(&adapterDesc);
adapterInfo->Name = adapterDesc.Description;
adapterInfo->InternalMemory = (float)adapterDesc.DedicatedVideoMemory/1024/1024;
for (UINT j = 0; adapter->EnumOutputs(j, &adapterOutput) != DXGI_ERROR_NOT_FOUND;++j)
{
displayInfo = new DisplayInfo;
adapterOutput->GetDesc(&displayDesc);
displayInfo->MonitorHWND = displayDesc.Monitor;
DWORD cPhysicalMonitors;
LPPHYSICAL_MONITOR pPhysicalMonitors = NULL;
BOOL bSuccess = GetNumberOfPhysicalMonitorsFromHMONITOR(displayInfo->MonitorHWND, &cPhysicalMonitors);
ZeroMemory(&pPhysicalMonitors, sizeof(pPhysicalMonitors));
pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(
cPhysicalMonitors* sizeof(PHYSICAL_MONITOR));
GetPhysicalMonitorsFromHMONITOR(displayInfo->MonitorHWND, cPhysicalMonitors, pPhysicalMonitors);
displayInfo->Name = pPhysicalMonitors->szPhysicalMonitorDescription;
//Получаем количество режимов которые удовлетворяют формату монитора DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM
adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL );
displayModeList = new DXGI_MODE_DESC[numModes];
if (!displayModeList)
{
return false;
}
//Заполняем структуру display mode list
result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
//Проходимся по всем режимам дисплея и находим тот, который совпадает с высотой и шириной экрана
//Когда совпадение найдено сохраняем нумератор и деноминатор частоты обновления для монитора
std::ofstream input_file("file.txt");
for(int k=0; k<numModes; k++)
{
if (input_file.is_open())
{
input_file << displayModeList[k].Width<<" "<<displayModeList[k].Height<<" "<<displayModeList[k].RefreshRate.Numerator<<" "<<displayModeList[k].RefreshRate.Denominator
<<" "<<displayModeList[k].ScanlineOrdering<<" "<<displayModeList[k].Format<<" "<<displayModeList[k].Scaling<<std::endl;
}
if (displayModeList[k].Width >= 1024)
{
if ((displayModeList[k].RefreshRate.Numerator/displayModeList[k].RefreshRate.Denominator)>59)
{
if (displayModeList[k].Scaling == DXGI_MODE_SCALING_CENTERED)
{
DisplayMode displayMode;
displayMode.Width = displayModeList[k].Width;
displayMode.Height = displayModeList[k].Height;
displayMode.Numerator = displayModeList[k].RefreshRate.Numerator;
displayMode.Denominator = displayModeList[k].RefreshRate.Denominator;
displayInfo->DisplayModes.push_back(displayMode);
/*numerator = displayModeList[k].RefreshRate.Numerator;
denominator = displayModeList[k].RefreshRate.Denominator;*/
}
}
}
}
//Удаляем display mode list
delete[] displayModeList;
displayModeList = NULL;
adapterInfo->displayList.push_back(displayInfo);
input_file.close ();
}
//добавляем в вектор всю собранную информацию по видеокарте
adapterList.push_back(adapterInfo);
}
//Удаляем адаптер и адаптер output
//adapter->Release();
adapter = 0;
//adapterOutput->Release();
adapterOutput = 0;
//Удаляем фабрику
/*factory->Release();
factory = 0;*/
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
factory->EnumAdapters(0,&adapter);
//Создаём устройство Direct3D и контекст устройства Direct3D
/*result = D3D11CreateDevice(NULL, driverType,NULL,D3D11_CREATE_DEVICE_DEBUG|D3D11_CREATE_DEVICE_BGRA_SUPPORT, featureLevels,numFeatureLevels,
D3D11_SDK_VERSION, &d3d11_Device, &featureLevel, &d3d11_DeviceContext );*/
result = D3D11CreateDevice(adapterList[0]->adapter, driverType, NULL, D3D11_CREATE_DEVICE_DEBUG|D3D11_CREATE_DEVICE_BGRA_SUPPORT, featureLevels,numFeatureLevels,
D3D11_SDK_VERSION, &d3d11_Device, &featureLevel, &d3d11_DeviceContext );
if (FAILED(result))
{
return false;
}
UINT qualityLevels;
d3d11_Device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &qualityLevels);
//Инициализируем структуру swap chain description
ZeroMemory(&swapChainDescription, sizeof(swapChainDescription));
//Устанавливаем количество буферов
swapChainDescription.BufferCount = 1;
//устанавливаем ширину и высоту заднего буфера
swapChainDescription.Width = settingsContainer->renderSettingsDX11->GetScreenWidth();
swapChainDescription.Height = settingsContainer->renderSettingsDX11->GetScreenHeight();
//устанавливаем формат пикселей
swapChainDescription.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDescription.SampleDesc.Count = 1;
swapChainDescription.SampleDesc.Quality = 0;
//Устанавливаем использование заднего буфера
swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDescription.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDescription.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreen;
fullscreen.RefreshRate.Numerator = 0;
fullscreen.RefreshRate.Denominator = 1;
fullscreen.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
fullscreen.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
//Устанавливаем в полноэкранный режим и оконный
if (settingsContainer->renderSettingsDX11->IsFullScreenEnabled())
{
fullscreen.Windowed = FALSE;
}
else
{
fullscreen.Windowed = TRUE;
}
//Создаём swap chain
result = factory->CreateSwapChainForHwnd(d3d11_Device, hwnd, &swapChainDescription, &fullscreen, NULL, &swapChain);
if(FAILED(result))
return false;
//Получаем указатель на задний буфер
result = swapChain->GetBuffer(0,__uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
if (FAILED(result))
return false;
//Создаём render target view с указателем на задний буфер
result = d3d11_Device->CreateRenderTargetView(backBufferPtr, NULL, &d3d11_RenderTargetView);
if(FAILED(result))
return false;
//Освобождаем указатель на задний буфер, так как он больше не нужен
backBufferPtr->Release();
backBufferPtr = 0;
//Инициализируем описание структуры Depth_Buffer
ZeroMemory(&depthBufferDescription, sizeof(depthBufferDescription));
//Заполняем описание структуры
depthBufferDescription.Width = settingsContainer->renderSettingsDX11->GetScreenWidth();
depthBufferDescription.Height = settingsContainer->renderSettingsDX11->GetScreenHeight();
depthBufferDescription.MipLevels = 1;
depthBufferDescription.ArraySize = 1;
depthBufferDescription.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDescription.SampleDesc.Count = 1;
depthBufferDescription.SampleDesc.Quality = 0;
depthBufferDescription.Usage = D3D11_USAGE_DEFAULT;
depthBufferDescription.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDescription.CPUAccessFlags = 0;
depthBufferDescription.MiscFlags = 0;
//Создаём текстуру для буфера глубины используя заполненную структуру
result = d3d11_Device->CreateTexture2D(&depthBufferDescription, NULL, &d3d11_DepthStencilBuffer);
if (FAILED(result))
return false;
//Инициализируем описание stencil state
ZeroMemory(&depthStencilDescription, sizeof(depthStencilDescription));
//Вводим описание структуры stencil_state
depthStencilDescription.DepthEnable = true;
depthStencilDescription.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDescription.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDescription.StencilEnable = true;
depthStencilDescription.StencilReadMask = 0xFF;
depthStencilDescription.StencilWriteMask = 0xFF;
//Шаблонные операции если пиксель впереди
depthStencilDescription.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDescription.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDescription.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDescription.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
//Швблонные операции, если пиксель на обратной стороне
depthStencilDescription.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDescription.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDescription.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDescription.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
//Создаём Depth_Stencil_State
result = d3d11_Device->CreateDepthStencilState(&depthStencilDescription, &d3d11_DepthStencilState);
if (FAILED(result))
{
return false;
}
//Задаём состояние Depth Stencil State
d3d11_DeviceContext->OMSetDepthStencilState(d3d11_DepthStencilState,1);
//Инициализируем структуру Depth Stencil View
ZeroMemory (&depthStencilViewDescription, sizeof(depthStencilViewDescription));
//Заполняем описание структуры Depth_Stencil_View
depthStencilViewDescription.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDescription.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDescription.Texture2D.MipSlice = 0;
//Задаём описание структуры Depth_Stencil_View
result = d3d11_Device->CreateDepthStencilView(d3d11_DepthStencilBuffer, &depthStencilViewDescription, &d3d11_DepthStencilView);
if (FAILED(result))
return false;
//Привязываем render target view и depth stencil buffer к output pipeline
d3d11_DeviceContext->OMSetRenderTargets(1, &d3d11_RenderTargetView, d3d11_DepthStencilView);
//Заполняем структуру Raster_Description, которая будет определять как и какие полигоны будут нарисованы
rasterizerDescription.AntialiasedLineEnable = false;
rasterizerDescription.CullMode = D3D11_CULL_BACK;
rasterizerDescription.DepthBias = 0;
rasterizerDescription.DepthBiasClamp = 0.0f;
rasterizerDescription.DepthClipEnable = true;
rasterizerDescription.FillMode = D3D11_FILL_SOLID;
rasterizerDescription.FrontCounterClockwise = false;
rasterizerDescription.MultisampleEnable = true;
rasterizerDescription.ScissorEnable = false;
rasterizerDescription.SlopeScaledDepthBias = 0.0f;
//Создаём rasterizerState из описания, которое только что заполнили
result = d3d11_Device->CreateRasterizerState(&rasterizerDescription, &d3d11_RasterizerState);
if(FAILED(result))
{
return false;
}
//Устанавливаем rasterizer state (можно менять состояние с D3D11_FILL_SOLID на D3D11_FILL_WIREFRAME)
d3d11_DeviceContext->RSSetState(d3d11_RasterizerState);
//Устанавливаем вьюпорт для рендеринга
viewPort.Width = (float)settingsContainer->renderSettingsDX11->GetScreenWidth();
viewPort.Height = (float)settingsContainer->renderSettingsDX11->GetScreenHeight();
viewPort.MinDepth = 0.0f;
viewPort.MaxDepth = 1.0f;
viewPort.TopLeftX = 0.0f;
viewPort.TopLeftY = 0.0f;
//Создаём ViewPort
d3d11_DeviceContext->RSSetViewports(1,&viewPort);
return true;
}
void D3D11::ResizeSwapChain()
{
HRESULT result;
if (swapChain)
{
RECT rc;
GetClientRect(hwnd, &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
d3d11_DeviceContext->OMSetRenderTargets(0,0,0);
d3d11_RenderTargetView->Release();
swapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
d3d11_Device->CreateRenderTargetView(backBufferPtr, NULL, &d3d11_RenderTargetView);
//Инициализируем описание структуры Depth_Buffer
ZeroMemory(&depthBufferDescription, sizeof(depthBufferDescription));
//Заполняем описание структуры
depthBufferDescription.Width = width;
depthBufferDescription.Height = height;
depthBufferDescription.MipLevels = 1;
depthBufferDescription.ArraySize = 1;
depthBufferDescription.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDescription.SampleDesc.Count = 1;
depthBufferDescription.SampleDesc.Quality = 0;
depthBufferDescription.Usage = D3D11_USAGE_DEFAULT;
depthBufferDescription.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDescription.CPUAccessFlags = 0;
depthBufferDescription.MiscFlags = 0;
d3d11_DepthStencilBuffer->Release();
d3d11_DepthStencilBuffer = NULL;
//Создаём текстуру для буфера глубины используя заполненную структуру
result = d3d11_Device->CreateTexture2D(&depthBufferDescription, NULL, &d3d11_DepthStencilBuffer);
bool D3D11::InitializeD2D11()
{
options.debugLevel = D2D1_DEBUG_LEVEL_ERROR;
D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, options, &d2dfactory);
swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackbuffer));
D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_HARDWARE,
D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED));
d2dfactory->CreateDxgiSurfaceRenderTarget(dxgiBackbuffer, props, &d2dRenderTarget);
dxgiBackbuffer->Release();
dxgiBackbuffer = NULL;
d2dfactory->Release();
d2dfactory = NULL;
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(DWriteFactory), (IUnknown**)(&DWriteFactory));
DWriteFactory->CreateTextFormat(
L"Cambria",
NULL,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
12,
L"",
&textFormat);
DWriteFactory->CreateTextFormat(
L"Cambria",
NULL,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
12,
L"",
&textFormat2);
textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
textFormat2->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_FAR);
textFormat2->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
d2dRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &Brush);
return true;
}
//Задаём состояние Depth Stencil State
d3d11_DeviceContext->OMSetDepthStencilState(d3d11_DepthStencilState, 1);
//Инициализируем структуру Depth Stencil View
ZeroMemory (&depthStencilViewDescription, sizeof(depthStencilViewDescription));
//Заполняем описание структуры Depth_Stencil_View
depthStencilViewDescription.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDescription.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDescription.Texture2D.MipSlice = 0;
d3d11_DepthStencilView->Release();
d3d11_DepthStencilView = NULL;
//Задаём описание структуры Depth_Stencil_View
result = d3d11_Device->CreateDepthStencilView(d3d11_DepthStencilBuffer, &depthStencilViewDescription, &d3d11_DepthStencilView);
//Освобождаем указатель на задний буфер, так как он больше не нужен
backBufferPtr->Release();
backBufferPtr = 0;
d3d11_DeviceContext->OMSetRenderTargets(1, &d3d11_RenderTargetView, d3d11_DepthStencilView);
//d3d11_DeviceContext->OMSetRenderTargets(1, &d3d11_RenderTargetView, NULL);
//Устанавливаем вьюпорт для рендеринга
D3D11_VIEWPORT viewPort;
viewPort.Width = (float)width;
viewPort.Height = (float)height;
viewPort.MinDepth = 0.0f;
viewPort.MaxDepth = 1.0f;
viewPort.TopLeftX = 0.0f;
viewPort.TopLeftY = 0.0f;
//Создаём ViewPort
d3d11_DeviceContext->RSSetViewports(1,&viewPort);
}
}
I resize buffer on WM_SIZE event:
case WM_SIZE:
{
int Width = LOWORD(lparam);
int Height = HIWORD(lparam);
WCHAR* str = NULL;
if (wparam == SIZE_RESTORED)
{
if (system->application)
{
system->application->d3d11->ResizeSwapChain();
system->application->d3d11->ResizeD2DBuffer();
system->application->cameraDX_Free->perspective(system->application->cameraDX_Free->m_fovx,
static_cast<float>(Width) / static_cast<float>(Height),
system->application->cameraDX_Free->m_znear,
system->application->cameraDX_Free->m_zfar);
}
}
}
To correctly resize D2D in my case you need first to delete all d2d resources and after resizing swap chain recreate all resources again.