//-------------------------------------------------------------------------------------- CPUTGeometryShaderDX11 *CPUTGeometryShaderDX11::CreateGeometryShaderFromMemory( const cString &name, ID3D11Device *pD3dDevice, const cString &shaderMain, const cString &shaderProfile, const char *pShaderSource ) { ID3DBlob *pCompiledBlob = NULL; ID3D11GeometryShader *pNewGeometryShader = NULL; CPUTAssetLibraryDX11 *pAssetLibrary = (CPUTAssetLibraryDX11*)CPUTAssetLibrary::GetAssetLibrary(); CPUTResult result = pAssetLibrary->CompileShaderFromMemory(pShaderSource, shaderMain, shaderProfile, &pCompiledBlob); ASSERT( CPUTSUCCESS(result), _L("Error creating Geometry shader:\n\n") ); // Create the Geometry shader // TODO: Move to Geometry shader class HRESULT hr = pD3dDevice->CreateGeometryShader( pCompiledBlob->GetBufferPointer(), pCompiledBlob->GetBufferSize(), NULL, &pNewGeometryShader ); ASSERT( SUCCEEDED(hr), _L("Error compiling Geometry shader:\n\n") ); // cString DebugName = _L("CPUTAssetLibraryDX11::GetGeometryShader ")+name; // CPUTSetDebugName(pNewGeometryShader, DebugName); CPUTGeometryShaderDX11 *pNewCPUTGeometryShader = new CPUTGeometryShaderDX11( pNewGeometryShader, pCompiledBlob ); // add shader to library pAssetLibrary->AddGeometryShader(name + shaderMain + shaderProfile, pNewCPUTGeometryShader); // pNewCPUTGeometryShader->Release(); // We've added it to the library, so release our reference // return the shader (and blob) return pNewCPUTGeometryShader; }
HRESULT StateCache::GetPipelineStateObjectFromCache( SmallPsoDesc* pso_desc, ID3D12PipelineState** pso, D3D12_PRIMITIVE_TOPOLOGY_TYPE topology, const GeometryShaderUid* gs_uid, const PixelShaderUid* ps_uid, const VertexShaderUid* vs_uid) { auto it = m_small_pso_map.find(*pso_desc); if (it == m_small_pso_map.end()) { // Not found, create new PSO. // RootSignature, SampleMask, SampleDesc, NumRenderTargets, RTVFormats, DSVFormat // never change so they are set in constructor and forgotten. m_current_pso_desc.GS = pso_desc->gs_bytecode; m_current_pso_desc.PS = pso_desc->ps_bytecode; m_current_pso_desc.VS = pso_desc->vs_bytecode; m_current_pso_desc.BlendState = GetDesc12(pso_desc->blend_state); m_current_pso_desc.DepthStencilState = GetDesc12(pso_desc->depth_stencil_state); m_current_pso_desc.RasterizerState = GetDesc12(pso_desc->rasterizer_state); m_current_pso_desc.PrimitiveTopologyType = topology; m_current_pso_desc.InputLayout = pso_desc->input_layout->GetActiveInputLayout12(); ID3D12PipelineState* new_pso = nullptr; HRESULT hr = D3D::device12->CreateGraphicsPipelineState(&m_current_pso_desc, IID_PPV_ARGS(&new_pso)); if (FAILED(hr)) { return hr; } m_small_pso_map[*pso_desc] = new_pso; *pso = new_pso; // This contains all of the information needed to reconstruct a PSO at startup. SmallPsoDiskDesc disk_desc = {}; disk_desc.blend_state_hex = pso_desc->blend_state.hex; disk_desc.depth_stencil_state_hex = pso_desc->depth_stencil_state.hex; disk_desc.rasterizer_state_hex = pso_desc->rasterizer_state.hex; disk_desc.ps_uid = *ps_uid; disk_desc.vs_uid = *vs_uid; disk_desc.gs_uid = *gs_uid; disk_desc.vertex_declaration = pso_desc->input_layout->GetVertexDeclaration(); disk_desc.topology = topology; // This shouldn't fail.. but if it does, don't cache to disk. ID3DBlob* psoBlob = nullptr; hr = new_pso->GetCachedBlob(&psoBlob); if (SUCCEEDED(hr)) { s_pso_disk_cache.Append(disk_desc, reinterpret_cast<const u8*>(psoBlob->GetBufferPointer()), static_cast<u32>(psoBlob->GetBufferSize())); psoBlob->Release(); } } else { *pso = it->second; } return S_OK; }
bool InitD3D11GUIRendering( RENDERER_SETTINGS * settings ) { ID3DBlob * pCode = NULL; ID3DBlob * pErrors = NULL; if (D3DCompile( defaultGUIPixelShader, strlen(defaultGUIPixelShader), NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) { printf("[Renderer] D3DCompile (PS) failed\n"); return false; } if (pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIPixelShader ) != S_OK) { printf("[Renderer] CreatePixelShader failed\n"); return false; } if (D3DCompile( defaultGUIVertexShader, strlen(defaultGUIVertexShader), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) { printf("[Renderer] D3DCompile (VS) failed\n"); return false; } if (pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIVertexShader ) != S_OK) { printf("[Renderer] CreateVertexShader failed\n"); return false; } D3D11_BUFFER_DESC desc; ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC)); desc.ByteWidth = sizeof(float) * 7 * GUIQUADVB_SIZE; desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; if (pDevice->CreateBuffer(&desc, NULL, &pGUIQuadVB) != S_OK) { printf("[Renderer] CreateBuffer (VB) failed\n"); return false; } static D3D11_INPUT_ELEMENT_DESC pGUIDesc[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR" , 0, DXGI_FORMAT_R8G8B8A8_UNORM , 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, 4 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT , 0, 6 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, }; if (pDevice->CreateInputLayout( pGUIDesc, 4, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pGUIQuadLayout) != S_OK) { printf("[Renderer] CreateInputLayout failed\n"); return false; } D3D11_BUFFER_DESC cbDesc; ZeroMemory( &cbDesc, sizeof(D3D11_BUFFER_DESC) ); cbDesc.ByteWidth = sizeof( float ) * 4 * 4 * 2; cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; MatrixOrthoOffCenterLH( pGUIMatrix, 0, nWidth, nHeight, 0, -1.0f, 1.0f ); D3D11_SUBRESOURCE_DATA subData; ZeroMemory( &subData, sizeof(D3D11_SUBRESOURCE_DATA) ); subData.pSysMem = &pGUIMatrix; if (pDevice->CreateBuffer( &cbDesc, &subData, &pGUIConstantBuffer ) != S_OK) { printf("[Renderer] CreateBuffer (CB) failed\n"); return false; } D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() ); blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; if (pDevice->CreateBlendState( &blendDesc, &pGUIBlendState ) != S_OK) return false; D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() ); rastDesc.ScissorEnable = true; if (pDevice->CreateRasterizerState( &rastDesc, &pGUIRasterizerState ) != S_OK) return false; return true; }
/* PSの生成 */ static void createPS( unsigned int target, const ShaderScripts& ss, nlEngineContext& cxt ) { /**/ ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; nlPixelShader& pixelShader = cxt.pss[target]; const nlInt8* script = ss.psScripts.scripts[target].script; const nlInt8* funcName = "main"; /**/ NL_ASSERT(!pixelShader.shader_); /* commonと連結 */ const nlInt8* commonScript = ss.commonScripts.script; const unsigned int scriptLen = nlStrlen( script ) + nlStrlen( commonScript ); nlInt8* conbinedScript = (nlInt8*)nlMalloc( (scriptLen+1)*sizeof(nlInt8) ); nlStrcat( conbinedScript, commonScript ); nlStrcat( conbinedScript, script ); #ifndef INTROMODE const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR; HRESULT hr = D3D10CompileShader( conbinedScript, nlStrlen(conbinedScript), funcName, shaderMacros, NULL, funcName, "ps_4_0", flag, &pBlob, &pErrorBlob ); if( SUCCEEDED(hr) ) { if( SUCCEEDED( cxt.d3dDevice->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &pixelShader.shader_ ) ) ) { return ;} else { NL_ASSERT(!"このパスには来ないことになっている"); //goto RELOAD; return ; } } else { /* 失敗した場合はエラーを出力し確実に成功するシェーダをロードする */ const nlInt8* name = ss.psScripts.scripts[target].name; std::string error = std::string("[")+std::string(name)+std::string("]")+std::string(DXGetErrorDescriptionA(hr)); error.resize(error.size()-1);/* 改行コードを取り除く */ if(pErrorBlob) { error += std::string( (nlInt8*)pErrorBlob->GetBufferPointer() ); error.resize(error.size()-1);/* 改行コードを取り除く */ } NL_ERR( ERR_006, error.c_str()); /**/ const nlInt8 script[] = { "float4 main():SV_Target0" "{return float4(1,0,0,1);}" }; pixelShader = nlCreatePixelShader(script, sizeof(script)/sizeof(nlInt8), "main", cxt ); } return; #else const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_OPTIMIZATION_LEVEL3; HRESULT hr = D3D10CompileShader( conbinedScript, nlStrlen(conbinedScript), funcName, shaderMacros, NULL, funcName, "ps_4_0", flag, &pBlob, &pErrorBlob ); if( FAILED(hr) ) { MessageBox( NULL, "failed to load pixel shader", "", MB_OK ); if(pErrorBlob) { MessageBox( NULL, (nlInt8*)pErrorBlob->GetBufferPointer(), "", MB_OK ); } return; } NL_HR_VALID( cxt.d3dDevice->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &pixelShader.shader_ ) ); #endif }
// プログラマブルシェーダ作成 HRESULT MakeShaders( void ) { HRESULT hr; ID3DBlob* pVertexShaderBuffer = NULL; ID3DBlob* pPixelShaderBuffer = NULL; ID3DBlob* pError = NULL; DWORD dwShaderFlags = 0; #ifdef _DEBUG dwShaderFlags |= D3DCOMPILE_DEBUG; #endif // コンパイル hr = D3DX11CompileFromFile( _T( "Basic_2D.fx" ), NULL, NULL, "VS", "vs_4_0_level_9_1", dwShaderFlags, 0, NULL, &pVertexShaderBuffer, &pError, NULL ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't open Basic_2D.fx" ), _T( "Error" ), MB_OK ); SAFE_RELEASE( pError ); return hr; } hr = D3DX11CompileFromFile( _T( "Basic_2D.fx" ), NULL, NULL, "PS", "ps_4_0_level_9_1", dwShaderFlags, 0, NULL, &pPixelShaderBuffer, &pError, NULL ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pError ); return hr; } SAFE_RELEASE( pError ); // VertexShader作成 hr = g_pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), NULL, &g_pVertexShader ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); return hr; } // PixelShader作成 hr = g_pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader ); if ( FAILED( hr ) ) { SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); return hr; } // 入力バッファの入力形式 D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); // 入力バッファの入力形式作成 hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &g_pInputLayout ); SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); if ( FAILED( hr ) ) { return hr; } // シェーダ定数バッファ作成 D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof( bd ) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( CBNeverChanges ); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBNeverChanges ); if( FAILED( hr ) ) return hr; // 変換行列 CBNeverChanges cbNeverChanges; XMMATRIX mScreen; mScreen = XMMatrixIdentity(); mScreen._11 = 2.0f / g_nClientWidth; mScreen._22 = -2.0f / g_nClientHeight; mScreen._41 = -1.0f; mScreen._42 = 1.0f; cbNeverChanges.mView = XMMatrixTranspose( mScreen ); g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, NULL, &cbNeverChanges, 0, 0 ); return S_OK; }
void ntGenerateTextures(const ShaderScripts& shaderScript, nlEngineContext* cxt ) { #if 0 /* この関数が呼ばれる前にテクスチャは解放されている事が期待される */ for( int i=0;i<MAX_TEXTURE_NUM;++i){ NL_ASSERT( !cxt->texs[i].texture );} const ShaderScriptGroup& tsScripts = shaderScript.tsScripts; const ShaderScript& commonScrips = shaderScript.commonScripts; /**/ NL_ASSERT( 0 < tsScripts.numScript ); /**/ ID3D11Device* d3dDevice = cxt->d3dDevice; ID3D11DeviceContext* d3dContext = cxt->d3dContext; tsScripts.numScript; tsScripts.scripts[0].script; tsScripts.scripts[0].name; //const nlInt8* script = tsScripts.scripts; nlTexture* texuters = &(cxt->texs[0]); /**/ const unsigned int scriptLen = nlStrlen(script); /* 全シェーダを作成 */ ID3D11PixelShader* texturShaders[MAX_TEXTURE_NUM]; nlMemset( texturShaders, 0, sizeof(ID3D11PixelShader*)*MAX_TEXTURE_NUM ); /**/ const unsigned int numTexture = textureScripts.numTexture; /**/ for( unsigned int i=0;i<numTexture;++i) { ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; const nlInt8* funcName = textureScripts.funcs[i]; const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR; /* ピクセルシェーダの作成 */ if( FAILED( D3D10CompileShader( script, scriptLen, funcName, shaderMacros, NULL, "main", "ps_4_0",flag, &pBlob, &pErrorBlob ) ) ) { NL_ERR(ERR_009); MessageBoxA( NULL, "load texshader error", "", MB_OK ); if(pErrorBlob) { NL_ERR(ERR_003, pErrorBlob->GetBufferPointer() ); MessageBoxA( NULL, (nlInt8*)pErrorBlob->GetBufferPointer(), "", MB_OK ); } return; } if( pBlob ) { d3dDevice->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &texturShaders[i] ); } ++i; } /* 書きこむのに必要なシェーダを作成 */ ID3D11VertexShader* vsRenderQuad; ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; NL_HR_ASSSERT( D3D10CompileShader(script, scriptLen, "vs", shaderMacros, NULL, "main","vs_4_0",(D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR), &pBlob, &pErrorBlob ) ) ; d3dDevice->CreateVertexShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &vsRenderQuad ); /* 全テクスチャを作成 */ for(unsigned int i=0;i<numTexture;++i) { /**/ nlTexture& tex = texuters[i]; /**/ tex.width = 512; /* HACK サイズは適当 */ tex.height = 512; /* HACK サイズは適当 */ int mipLevel = 1; int CPUAccessFlags = 0; D3D11_TEXTURE2D_DESC descTarget = { tex.width, tex.height, mipLevel, 1, DXGI_FORMAT_B8G8R8A8_UNORM, {1,0}, D3D11_USAGE_DEFAULT, (D3D11_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE), CPUAccessFlags, 0 }; d3dDevice->CreateTexture2D( &descTarget, NULL, &tex.texture ); d3dDevice->CreateRenderTargetView( tex.texture, NULL, &tex.rtView ); d3dDevice->CreateShaderResourceView( tex.texture, NULL ,&tex.shaderView ); } /* 現在のRasterStateを取得 */ ID3D11RasterizerState* oldRasterState; d3dContext->RSGetState(&oldRasterState); /**/ D3D11_RASTERIZER_DESC rasterDesc; rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_NONE; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; ID3D11RasterizerState* rasterState; d3dDevice->CreateRasterizerState(&rasterDesc, &rasterState); d3dContext->RSSetState(rasterState); rasterState->Release(); /* 全テクスチャを焼き込む */ for(unsigned int i=0;i<numTexture;++i) { /**/ nlTexture& tex = texuters[i]; /* ビューポートの設定 */ D3D11_VIEWPORT viewport; viewport.Width = tex.width; viewport.Height = tex.height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext->RSSetViewports(1, &viewport); /* シェーダを設定する */ d3dContext->VSSetShader( vsRenderQuad, NULL, 0); d3dContext->PSSetShader( texturShaders[i], NULL, 0); /* レンダーターゲットを設定する */ const float clearColor[4] = {0.0f, 0.0f, 1.0f, 0.0f}; d3dContext->ClearRenderTargetView( tex.rtView, clearColor ); d3dContext->OMSetRenderTargets( 1, &tex.rtView, NULL ); /* 全てのテクスチャを設定する */ /* TODO 毎回全てのテクスチャを設定せずに、このループで設定したテクスチャを省くようにだけする?*/ for( unsigned int j=0;j<numTexture;++j) { if( i != j ) { nlTexture& texSamp = texuters[j]; d3dContext->PSSetShaderResources(j, 1, &texSamp.shaderView ); } } /* 描画する */ d3dContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); d3dContext->Draw( 4, 0 ); } /**/ d3dContext->VSSetShader( NULL, NULL, 0); d3dContext->PSSetShader( NULL, NULL, 0); /* ビューポート設定を元に戻す */ /* 現在のビューポート設定を取得しておく */ D3D11_VIEWPORT oldViewports = {0.0,0.0,cxt->rendertargets[0].width_,cxt->rendertargets[0].height_,0.0f,1.0f}; d3dContext->RSSetViewports( 1, &oldViewports ); /* RasterState設定を元に戻す */ d3dContext->RSSetState(oldRasterState); if( oldRasterState ){ oldRasterState->Release(); } /* PSを解放 */ for(unsigned int i=0;i<numTexture;++i) { if( texturShaders[i] ){ texturShaders[i]->Release(); } } #endif }
static void createVS( unsigned int target, const ShaderScripts& ss, nlEngineContext& cxt ) { const ShaderScript& shaderScript = ss.vsScripts.scripts[target]; const nlInt8* script = shaderScript.script; const nlInt8* funcName = "main"; const nlInt8* unitName = shaderScript.name; nlVertexShader& vs = cxt.vss[target]; NL_ASSERT( !vs.shader_ ); /**/ ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; /* commonと連結 */ const nlInt8* commonScript = ss.commonScripts.script; const nlUint32 scriptLen = nlStrlen( script ) + nlStrlen( commonScript ); nlInt8* conbinedScript = (nlInt8*)nlMalloc( (scriptLen+1)*sizeof(nlInt8) ); nlStrcat( conbinedScript, commonScript ); nlStrcat( conbinedScript, script ); //printf( conbinedScript ); #ifndef INTROMODE const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR; HRESULT hr = D3D10CompileShader( conbinedScript, nlStrlen(conbinedScript), unitName, shaderMacros, NULL, funcName, "vs_4_0", flag, &pBlob, &pErrorBlob ); /* ロードが失敗したらエラーを出力した後に確実にロードが成功するシェーダをロードする */ if(FAILED( hr ) ) { /**/ NL_ERR( ERR_005, (nlInt8*)pErrorBlob->GetBufferPointer() ); /**/ const nlInt8 script[] = { "cbuffer Const0 : register(b0){ f4x4 world; }" "cbuffer Const2 : register(b2){ f4x4 viewProj; }" "float4 main( float4 in_pos:P, float4 in_normal:N, float4 in_col:C ):SV_POSITION" "{ return mul( in_pos, mul(world,viewProj)); }" }; HRESULT hr = D3D10CompileShader( script, sizeof(script)/sizeof(nlInt8), unitName, shaderMacros, NULL, "main", "vs_4_0", flag, &pBlob, &pErrorBlob ); } #else const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_OPTIMIZATION_LEVEL3; HRESULT hr = D3DX11CompileFromMemory( conbinedScript, nlStrlen(conbinedScript), funcName, shaderMacros, NULL, funcName, "vs_4_0", flag, 0, NULL, &pBlob, &pErrorBlob, NULL ); if(FAILED( hr ) ) { MessageBoxA(NULL,(nlInt8*)pErrorBlob->GetBufferPointer(),"",MB_OK); } #endif /**/ nlFree( (void*)conbinedScript ); /* create shader */ NL_HR_VALID( cxt.d3dDevice->CreateVertexShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &vs.shader_ ) ); /* create inputlayout */ NL_HR_VALID( cxt.d3dDevice->CreateInputLayout(NLM_INPUT_ELEMENT, _countof(NLM_INPUT_ELEMENT), pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &vs.inputLayout_ ) ); }
// -------------------------------------------------------- // Loads the specified shader and builds the variable table using shader // reflection. This must be a separate step from the constructor since // we can't invoke derived class overrides in the base class constructor. // // shaderFile - A "wide string" specifying the compiled shader to load // // Returns true if shader is loaded properly, false otherwise // -------------------------------------------------------- bool ISimpleShader::LoadShaderFile(LPCWSTR shaderFile) { // Load the shader to a blob and ensure it worked ID3DBlob* shaderBlob = 0; HRESULT hr = D3DReadFileToBlob(shaderFile, &shaderBlob); if (hr != S_OK) { return false; } // Create the shader - Calls an overloaded version of this abstract // method in the appropriate child class shaderValid = CreateShader(shaderBlob); if (!shaderValid) { shaderBlob->Release(); return false; } // Set up shader reflection to get information about // this shader and its variables, buffers, etc. ID3D11ShaderReflection* refl; D3DReflect( shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&refl); // Get the description of the shader D3D11_SHADER_DESC shaderDesc; refl->GetDesc(&shaderDesc); // Create an array of constant buffers constantBufferCount = shaderDesc.ConstantBuffers; constantBuffers = new SimpleConstantBuffer[constantBufferCount]; // Handle bound resources (like shaders and samplers) unsigned int resourceCount = shaderDesc.BoundResources; for (unsigned int r = 0; r < resourceCount; r++) { // Get this resource's description D3D11_SHADER_INPUT_BIND_DESC resourceDesc; refl->GetResourceBindingDesc(r, &resourceDesc); // Check the type switch (resourceDesc.Type) { case D3D_SIT_TEXTURE: // A texture resource textureTable.insert(std::pair<std::string, unsigned int>(resourceDesc.Name, resourceDesc.BindPoint)); break; case D3D_SIT_SAMPLER: // A sampler resource samplerTable.insert(std::pair<std::string, unsigned int>(resourceDesc.Name, resourceDesc.BindPoint)); break; } } // Loop through all constant buffers for (unsigned int b = 0; b < constantBufferCount; b++) { // Get this buffer ID3D11ShaderReflectionConstantBuffer* cb = refl->GetConstantBufferByIndex(b); // Get the description of this buffer D3D11_SHADER_BUFFER_DESC bufferDesc; cb->GetDesc(&bufferDesc); // Get the description of the resource binding, so // we know exactly how it's bound in the shader D3D11_SHADER_INPUT_BIND_DESC bindDesc; refl->GetResourceBindingDescByName(bufferDesc.Name, &bindDesc); // Set up the buffer and put its pointer in the table constantBuffers[b].BindIndex = bindDesc.BindPoint; cbTable.insert(std::pair<std::string, SimpleConstantBuffer*>(bufferDesc.Name, &constantBuffers[b])); // Create this constant buffer D3D11_BUFFER_DESC newBuffDesc; newBuffDesc.Usage = D3D11_USAGE_DEFAULT; newBuffDesc.ByteWidth = bufferDesc.Size; newBuffDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; newBuffDesc.CPUAccessFlags = 0; newBuffDesc.MiscFlags = 0; newBuffDesc.StructureByteStride = 0; device->CreateBuffer(&newBuffDesc, 0, &constantBuffers[b].ConstantBuffer); // Set up the data buffer for this constant buffer constantBuffers[b].LocalDataBuffer = new unsigned char[bufferDesc.Size]; ZeroMemory(constantBuffers[b].LocalDataBuffer, bufferDesc.Size); // Loop through all variables in this buffer for (unsigned int v = 0; v < bufferDesc.Variables; v++) { // Get this variable ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(v); // Get the description of the variable D3D11_SHADER_VARIABLE_DESC varDesc; var->GetDesc(&varDesc); // Create the variable struct SimpleShaderVariable varStruct; varStruct.ConstantBufferIndex = b; varStruct.ByteOffset = varDesc.StartOffset; varStruct.Size = varDesc.Size; // Get a string version std::string varName(varDesc.Name); // Add this variable to the table varTable.insert(std::pair<std::string, SimpleShaderVariable>(varName, varStruct)); } } // All set refl->Release(); shaderBlob->Release(); return true; }
void BuildShaderFX() { m_diffuseTextureRV[0] = NULL; m_diffuseTextureTV[0] = NULL; m_distDirTextureRV = NULL; m_distDirTextureTV = NULL; m_TextureRV = NULL; m_TextureTV = NULL; m_pDepthStencilView = NULL; m_otherTextureRV = NULL; m_otherTextureTV = NULL; m_pDrawVectorsTechnique = NULL; m_pDiffuseTechnique = NULL; m_pLineAntiAliasTechnique = NULL; m_pDisplayImage = NULL; m_pInTex[0] = NULL; m_pInTex[1] = NULL; m_pInTex[2] = NULL; m_pDiffTex = NULL; m_pDiffX = NULL; m_pDiffY = NULL; m_pScale = NULL; m_pPan = NULL; m_pPolySize = NULL; m_vp.Width = (int)(WIDTH); m_vp.Height = (int)(HEIGHT); m_vp.MinDepth = 0.0f; m_vp.MaxDepth = 1.0f; m_vp.TopLeftX = 0; m_vp.TopLeftY = 0; ID3DBlob* pCode; ID3DBlob* pError; ID3DX11Effect* pEffect11; //Picture HRESULT hr = 0; hr = D3DX11CompileFromFile(_T("DiffusionCurves.fx"), NULL, NULL, NULL, "fx_5_0", D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_DEBUG, NULL, NULL, &pCode, &pError, NULL); if (FAILED(hr)) { if (pError) { MessageBoxA(0, (char*)pError->GetBufferPointer(), 0, 0); SAFE_RELEASE(pError); } DXTrace(__FILE__, __LINE__, hr, _T("D3DX11CreateEffectFromFile"), TRUE); } V(D3DX11CreateEffectFromMemory(pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, m_pd3dDevice, &pEffect11)); m_pDrawVectorsTechnique = pEffect11->GetTechniqueByName("DrawCurves"); m_pDiffuseTechnique = pEffect11->GetTechniqueByName("Diffuse"); m_pLineAntiAliasTechnique = pEffect11->GetTechniqueByName("LineAntiAlias"); m_pDisplayImage = pEffect11->GetTechniqueByName("DisplayDiffusionImage"); m_pDiffTex = pEffect11->GetVariableByName("g_diffTex")->AsShaderResource(); for (int i = 0; i < 3; i++) { m_pInTex[i] = (pEffect11->GetVariableByName("g_inTex"))->GetElement( i)->AsShaderResource(); } m_blurOn = pEffect11->GetVariableByName("g_blurOn")->AsScalar(); m_pDiffX = pEffect11->GetVariableByName("g_diffX")->AsScalar(); m_pDiffY = pEffect11->GetVariableByName("g_diffY")->AsScalar(); m_pScale = pEffect11->GetVariableByName("g_scale")->AsScalar(); m_pPolySize = pEffect11->GetVariableByName("g_polySize")->AsScalar(); m_pPan = pEffect11->GetVariableByName("g_pan")->AsVector(); D3DX11_PASS_DESC PassDesc; m_pDrawVectorsTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); if (FAILED(m_pd3dDevice->CreateInputLayout(VertexDesc_CurveVertex, 4, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_pCurveVertexLayout))) { return; } m_pDiffuseTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); if (FAILED(m_pd3dDevice->CreateInputLayout(VertexDesc_VSOVertex, 2, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_pCurveVertex2Layout))) { return; } // create the depth buffer (only needed for curve mask rendering) DXGI_SAMPLE_DESC samdesc; samdesc.Count = 1; samdesc.Quality = 0; D3D11_TEXTURE2D_DESC texdesc; ZeroMemory(&texdesc, sizeof(D3D10_TEXTURE2D_DESC)); texdesc.MipLevels = 1; texdesc.ArraySize = 1; texdesc.SampleDesc = samdesc; texdesc.Width = (int)(WIDTH); texdesc.Height = (int)(HEIGHT); texdesc.Usage = D3D11_USAGE_DEFAULT; texdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; texdesc.Format = DXGI_FORMAT_D32_FLOAT; if (m_pDepthStencil != NULL) { m_pDepthStencil->Release(); } hr = m_pd3dDevice->CreateTexture2D(&texdesc, NULL, &m_pDepthStencil); hr = m_pd3dDevice->CreateDepthStencilView(m_pDepthStencil, NULL, &m_pDepthStencilView); //create diffusion textures (2 for ping pong rendering) if (m_diffuseTexture[0] != NULL) { m_diffuseTexture[0]->Release(); } if (m_diffuseTexture[1] != NULL) { m_diffuseTexture[1]->Release(); } if (m_distDirTexture != NULL) { m_distDirTexture->Release(); } if (m_otherTexture != NULL) { m_otherTexture->Release(); } texdesc.Width = (int)(WIDTH); texdesc.Height = (int)(HEIGHT); texdesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //texdesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; // use this for higher accuracy diffusion texdesc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE; hr = m_pd3dDevice->CreateTexture2D(&texdesc, NULL, &m_diffuseTexture[0]); hr = m_pd3dDevice->CreateTexture2D(&texdesc, NULL, &m_diffuseTexture[1]); hr = m_pd3dDevice->CreateTexture2D(&texdesc, NULL, &m_otherTexture); // distance map + nearest point map texdesc.Usage = D3D11_USAGE_DEFAULT; texdesc.CPUAccessFlags = 0; texdesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE; texdesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; hr = m_pd3dDevice->CreateTexture2D(&texdesc, NULL, &m_distDirTexture); hr = m_pd3dDevice->CreateTexture2D(&texdesc, NULL, &m_Texture); //create render target views hr = m_pd3dDevice->CreateShaderResourceView(m_diffuseTexture[0], NULL, &m_diffuseTextureRV[0]); hr = m_pd3dDevice->CreateRenderTargetView(m_diffuseTexture[0], NULL, &m_diffuseTextureTV[0]); hr = m_pd3dDevice->CreateShaderResourceView(m_diffuseTexture[1], NULL, &m_diffuseTextureRV[1]); hr = m_pd3dDevice->CreateRenderTargetView(m_diffuseTexture[1], NULL, &m_diffuseTextureTV[1]); hr = m_pd3dDevice->CreateShaderResourceView(m_distDirTexture, NULL, &m_distDirTextureRV); hr = m_pd3dDevice->CreateRenderTargetView(m_distDirTexture, NULL, &m_distDirTextureTV); hr = m_pd3dDevice->CreateShaderResourceView(m_Texture, NULL, &m_TextureRV); hr = m_pd3dDevice->CreateRenderTargetView(m_Texture, NULL, &m_TextureTV); hr = m_pd3dDevice->CreateShaderResourceView(m_otherTexture, NULL, &m_otherTextureRV); hr = m_pd3dDevice->CreateRenderTargetView(m_otherTexture, NULL, &m_otherTextureTV); char s[255] = "zephyr.xml"; ReadVectorFile(s); ConstructCurves(); }
//-------------------------------------------------------------------------------------- // Direct3Dデバイスとスワップチェーン //-------------------------------------------------------------------------------------- HRESULT InitDevice() { HRESULT hr = S_OK; UINT createDeviceFlags = 0; //ドライバタイプの定義 D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; UINT numFeatureLevels = ARRAYSIZE( featureLevels ); //スワップチェーンの設定 DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = WIDTH; sd.BufferDesc.Height = HEIGHT; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; //Direct3Dデバイスの作成とスワップチェーンの作成 for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { g_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext ); if( SUCCEEDED( hr ) ) break; } if( FAILED( hr ) ) return hr; //レンダーターゲットビュー ID3D11Texture2D* pBackBuffer = NULL; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return hr; hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) return hr; //深度バッファ作成(ステンシル) D3D11_TEXTURE2D_DESC descDepth; ZeroMemory( &descDepth, sizeof(descDepth) ); descDepth.Width = WIDTH; descDepth.Height = HEIGHT; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil ); if( FAILED( hr ) ) return hr; //ステンシルビューの作成 D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV, sizeof(descDSV) ); descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView ); if( FAILED( hr ) ) return hr; //レンダーターゲットの設定 g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView ); //ビューポートの設定 D3D11_VIEWPORT vp; vp.Width = (FLOAT)WIDTH; vp.Height = (FLOAT)HEIGHT; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pImmediateContext->RSSetViewports( 1, &vp ); //頂点シェーダーをコンパイル ID3DBlob* pVSBlob = NULL; hr = CompileShaderFromFile( "SimpleShader.hlsl", "VS", "vs_4_0", &pVSBlob ); if( FAILED( hr ) ) { MessageBox( NULL,"頂点シェーダーを読み込めませんでした。", "Error", MB_OK ); return hr; } //頂点シェーダーから頂点シェーダのオブジェクトを作成 hr = g_pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader ); if( FAILED( hr ) ) { pVSBlob->Release(); return hr; } //頂点のインプットレイアウトを定義 D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); //インプットレイアウトの作成 hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pVertexLayout ); pVSBlob->Release();pVSBlob = NULL; if( FAILED( hr ) ) return hr; //インプットレイアウトのセット g_pImmediateContext->IASetInputLayout( g_pVertexLayout ); //ピクセルシェーダーをコンパイル ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile("SimpleShader.hlsl", "PS", "ps_4_0", &pPSBlob ); if( FAILED( hr ) ) { MessageBox( NULL,"頂点シェーダーを読み込めませんでした。", "Error", MB_OK ); return hr; } //ピクセルシェーダーからピクセルシェーダのオブジェクトを作成 hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader ); pPSBlob->Release(); if( FAILED( hr ) ) return hr; //頂点バッファの作成 SimpleVertex vertices[] = { { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.5f, 0.5f, 0.5f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) }, { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT4( 0.0f, 1.0f, 0.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) }, { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) }, { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) }, }; D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( SimpleVertex ) * 24; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitData; ZeroMemory( &InitData, sizeof(InitData) ); InitData.pSysMem = vertices; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer ); if( FAILED( hr ) ) return hr; //インデックスバッファの作成 WORD indices[] = { 3,1,0, 2,1,3, 6,4,5, 7,4,6, 11,9,8, 10,9,11, 14,12,13, 15,12,14, 19,17,16, 18,17,19, 22,20,21, 23,20,22 }; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( WORD ) * 36; // 36 vertices needed for 12 triangles in a triangle list bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; InitData.pSysMem = indices; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer ); if( FAILED( hr ) ) return hr; // コンスタントバッファの作成 bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pConstantBuffer ); if( FAILED( hr ) ) return hr; //画像をテクスチャにロード hr = D3DX11CreateShaderResourceViewFromFile( g_pd3dDevice, "suwako.png", NULL, NULL, &g_pTextureRV, NULL ); if( FAILED( hr ) ) return hr; //サンプラーステートの作成 D3D11_SAMPLER_DESC sampDesc; ZeroMemory( &sampDesc, sizeof(sampDesc) ); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = g_pd3dDevice->CreateSamplerState( &sampDesc, &g_pSamplerLinear ); if( FAILED( hr ) ) return hr; //行列の設定 // ワールド行列は単位行列 g_World = XMMatrixIdentity(); //ビュー行列の定義 XMVECTOR Eye = XMVectorSet( 0.0f, 1.0f, -5.0f, 0.0f ); //カメラの位置 XMVECTOR At = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f ); //カメラの注視先 XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); //カメラの真上のベクトル g_View = XMMatrixLookAtLH( Eye, At, Up ); //プロジェクション行列 g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV2, WIDTH / (FLOAT)HEIGHT, 0.01f, 100.0f ); InitOculusRiftObjects(); return S_OK; }
/** *************************************************************************************************** * DX12ImageRenderer::Init * * @brief * Initialize all members needed by this rendering class. * * @return * S_OK if successful. *************************************************************************************************** */ HRESULT DX12ImageRenderer::Init(const DX12ImageRendererConfig& config) { memcpy(&m_config, &config, sizeof(m_config)); m_srvUavCbDescriptorSize = m_config.pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); // Create command allocator HRESULT result = m_config.pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&m_pCmdAllocator)); // Create command list if (result == S_OK) { result = m_config.pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_pCmdAllocator, nullptr, IID_PPV_ARGS(&m_pCmdList)); } // Create descriptor heap for RTV if (result == S_OK) { D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {}; rtvHeapDesc.NumDescriptors = 1; rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; result = m_config.pDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&m_pInternalRtvHeap)); } // Create descriptor heap for SRV, UAV, and CBV if (result == S_OK) { // Describe and create a shader resource view (SRV) heap for the texture. D3D12_DESCRIPTOR_HEAP_DESC srvUavHeapDesc = {}; srvUavHeapDesc.NumDescriptors = RootParametersCount; srvUavHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; srvUavHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; result = m_config.pDevice->CreateDescriptorHeap(&srvUavHeapDesc, IID_PPV_ARGS(&m_pSrvUavCbHeap)); } // Create synchronization objects if (result == S_OK) { result = m_config.pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_pFence)); m_fenceValue = 1; // Create an event handle to use for frame synchronization m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); } // Create root signature if (result == S_OK) { CD3DX12_DESCRIPTOR_RANGE rangesGfx[RootParametersCount]; rangesGfx[RootParameterSRV].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); rangesGfx[RootParameterUAV].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1); rangesGfx[RootParameterCBV].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0); CD3DX12_ROOT_PARAMETER rootParamsGfx[RootParametersCount]; rootParamsGfx[RootParameterSRV].InitAsDescriptorTable(1, &rangesGfx[RootParameterSRV], D3D12_SHADER_VISIBILITY_PIXEL); rootParamsGfx[RootParameterUAV].InitAsDescriptorTable(1, &rangesGfx[RootParameterUAV], D3D12_SHADER_VISIBILITY_PIXEL); rootParamsGfx[RootParameterCBV].InitAsDescriptorTable(1, &rangesGfx[RootParameterCBV], D3D12_SHADER_VISIBILITY_ALL); D3D12_STATIC_SAMPLER_DESC sampler = CD3DX12_STATIC_SAMPLER_DESC(0, D3D12_FILTER_MIN_MAG_MIP_LINEAR); CD3DX12_ROOT_SIGNATURE_DESC rootSigDescGfx; rootSigDescGfx.Init(3, rootParamsGfx, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ID3DBlob* pSigBlobGfx = nullptr; ID3DBlob* pSigBlobGfxErr = nullptr; result = D3D12SerializeRootSignature(&rootSigDescGfx, D3D_ROOT_SIGNATURE_VERSION_1, &pSigBlobGfx, &pSigBlobGfxErr); result = m_config.pDevice->CreateRootSignature(0, pSigBlobGfx->GetBufferPointer(), pSigBlobGfx->GetBufferSize(), IID_PPV_ARGS(&m_pRootSignatureGraphics)); } // Create pipeline state if (result == S_OK) { const std::string shaderSrc = #include "FsQuadToBuffer.hlsl" ; size_t fileSize = strlen(shaderSrc.c_str()); ID3DBlob* pVertexShader = nullptr; ID3DBlob* pVsError = nullptr; result = D3DCompile(shaderSrc.c_str(), fileSize, NULL, NULL, NULL, "VsMain", "vs_5_0", 0, 0, &pVertexShader, &pVsError); if (pVsError) { OutputDebugStringA((char*)pVsError->GetBufferPointer()); pVsError->Release(); } ID3DBlob* pPixelShader = nullptr; ID3DBlob* pPsError = nullptr; result = D3DCompile(shaderSrc.c_str(), fileSize, NULL, NULL, NULL, "PsMain", "ps_5_0", 0, 0, &pPixelShader, &pPsError); if (pPsError) { OutputDebugStringA((char*)pPsError->GetBufferPointer()); pPsError->Release(); } if (result == S_OK) { // Describe and create the graphics pipeline state object (PSO). D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.VS = { reinterpret_cast<UINT8*>(pVertexShader->GetBufferPointer()), pVertexShader->GetBufferSize() }; psoDesc.PS = { reinterpret_cast<UINT8*>(pPixelShader->GetBufferPointer()), pPixelShader->GetBufferSize() }; psoDesc.pRootSignature = m_pRootSignatureGraphics; psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); psoDesc.DepthStencilState.DepthEnable = FALSE; psoDesc.DepthStencilState.StencilEnable = FALSE; psoDesc.SampleMask = UINT_MAX; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; psoDesc.SampleDesc.Count = 1; result = m_config.pDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pPipelineStateGraphics)); } } // Create constant buffer if (result == S_OK) { D3D12_HEAP_PROPERTIES heapProps = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD); D3D12_RESOURCE_DESC resDesc = CD3DX12_RESOURCE_DESC::Buffer(ConstBufSize); result = m_config.pDevice->CreateCommittedResource( &heapProps, D3D12_HEAP_FLAG_NONE, &resDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_pConstantBuffer)); } if (result == S_OK) { // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. result = m_pCmdList->Close(); } return result; }
HRESULT InitOculusRiftObjects() { HRESULT hr = S_OK; //画面に描画するための頂点バッファ SimpleVertex verticesL[] = { XMFLOAT3(-1, 1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(0,0),//頂点1 XMFLOAT3( 1, 1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(0.5,0),//頂点2 XMFLOAT3(-1,-1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(0,1),//頂点3 XMFLOAT3( 1,-1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(0.5,1),//頂点4 }; SimpleVertex verticesR[] = { XMFLOAT3(-1, 1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(0.5,0),//頂点1 XMFLOAT3( 1, 1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(1,0),//頂点2 XMFLOAT3(-1,-1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(0.5,1),//頂点3 XMFLOAT3( 1,-1,0),XMFLOAT4(1,1,1,1),XMFLOAT2(1,1),//頂点4 }; D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( SimpleVertex ) * 4; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitData; ZeroMemory( &InitData, sizeof(InitData) ); InitData.pSysMem = verticesL; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBufferOculusL ); if( FAILED( hr ) ) return hr; InitData.pSysMem = verticesR; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBufferOculusR ); if( FAILED( hr ) ) return hr; //レンダーターゲット用のテクスチャを作成する D3D11_TEXTURE2D_DESC desc; ZeroMemory( &desc, sizeof(desc) ); desc.Width = WIDTH; desc.Height = 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_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; //テクスチャを作成する g_pd3dDevice->CreateTexture2D( &desc, NULL, &g_pTextureOculus ); //シェーダーリソースビュー作ることで描画元として使用出来る g_pd3dDevice->CreateShaderResourceView( g_pTextureOculus, NULL, &g_pShaderResViewOculus ); //レンダーターゲットビューを作る g_pd3dDevice->CreateRenderTargetView( g_pTextureOculus, NULL, &g_pRenderTargetViewOculus ); //ピクセルシェーダーをコンパイル ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile("OculusRift.hlsl", "PS_OculusRift", "ps_4_0", &pPSBlob ); if( FAILED( hr ) ) { MessageBox( NULL,"ピクセルシェーダーを読み込めませんでした。", "Error", MB_OK ); return hr; } //ピクセルシェーダーからピクセルシェーダのオブジェクトを作成 hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShaderOculus ); pPSBlob->Release(); if( FAILED( hr ) ) return hr; // コンスタントバッファの作成 // ゆがませるピクセルシェーダー用の設定 bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(OculusRiftSettings); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pConstantBufferOculus ); if( FAILED( hr ) ) return hr; return hr; }
//-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_SettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); // Read the HLSL file // You should use the lowest possible shader profile for your shader to enable various feature levels. These // shaders are simple enough to work well within the lowest possible profile, and will run on all feature levels DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #ifdef _DEBUG // Disable optimizations to further improve shader debugging dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif ID3DBlob* pVertexShaderBuffer = nullptr; V_RETURN( DXUTCompileFromFile( L"SimpleSample.hlsl", nullptr, "RenderSceneVS", "vs_4_0_level_9_1", dwShaderFlags, 0, &pVertexShaderBuffer ) ); ID3DBlob* pPixelShaderBuffer = nullptr; V_RETURN( DXUTCompileFromFile( L"SimpleSample.hlsl", nullptr, "RenderScenePS", "ps_4_0_level_9_1", dwShaderFlags, 0, &pPixelShaderBuffer ) ); // Create the shaders V_RETURN( pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), nullptr, &g_pVertexShader11 ) ); DXUT_SetDebugName( g_pVertexShader11, "RenderSceneVS" ); V_RETURN( pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), nullptr, &g_pPixelShader11 ) ); DXUT_SetDebugName( g_pPixelShader11, "RenderScenePS" ); // Create a layout for the object data const D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &g_pLayout11 ) ); DXUT_SetDebugName( g_pLayout11, "Primary" ); // No longer need the shader blobs SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); // Create state objects D3D11_SAMPLER_DESC samDesc; ZeroMemory( &samDesc, sizeof(samDesc) ); samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samDesc.AddressU = samDesc.AddressV = samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.MaxAnisotropy = 1; samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samDesc.MaxLOD = D3D11_FLOAT32_MAX; V_RETURN( pd3dDevice->CreateSamplerState( &samDesc, &g_pSamLinear ) ); DXUT_SetDebugName( g_pSamLinear, "Linear" ); // Create constant buffers D3D11_BUFFER_DESC cbDesc; ZeroMemory( &cbDesc, sizeof(cbDesc) ); cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbDesc.ByteWidth = sizeof( CB_VS_PER_OBJECT ); V_RETURN( pd3dDevice->CreateBuffer( &cbDesc, nullptr, &g_pcbVSPerObject11 ) ); DXUT_SetDebugName( g_pcbVSPerObject11, "CB_VS_PER_OBJECT" ); cbDesc.ByteWidth = sizeof( CB_VS_PER_FRAME ); V_RETURN( pd3dDevice->CreateBuffer( &cbDesc, nullptr, &g_pcbVSPerFrame11 ) ); DXUT_SetDebugName( g_pcbVSPerFrame11, "CB_VS_PER_FRAME" ); // Create other render resources here // Setup the camera's view parameters static const XMVECTORF32 s_vecEye = { 0.0f, 0.0f, -5.0f, 0.f }; g_Camera.SetViewParams( s_vecEye, g_XMZero ); g_HUD.GetButton( IDC_TOGGLEWARP )->SetEnabled( true ); return S_OK; }
void BufferLayout::Init(void* shaderBlob) { ID3DBlob* shader = static_cast<ID3DBlob*>(shaderBlob); std::vector<D3D11_INPUT_ELEMENT_DESC> elementDescs; u32 lastBuffer = -1; for (u32 i = 0; i < m_Attributes.size(); i++) { D3D11_INPUT_ELEMENT_DESC current = {}; current.SemanticName = m_Attributes[i].semanticName.GetData(); if (m_Attributes[i].type == DataType::MATRIX4) { for (int k = 0; k < 4; k++) { current.SemanticIndex = k; current.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; current.InputSlot = m_Attributes[i].bufferId; current.InputSlotClass = m_Attributes[i].instancing ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA; current.InstanceDataStepRate = m_Attributes[i].instancing ? 1 : 0; if (lastBuffer != m_Attributes[i].bufferId) { lastBuffer = m_Attributes[i].bufferId; current.AlignedByteOffset = 0; } else { current.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; } elementDescs.push_back(current); } } else { current.SemanticIndex = 0; if (static_cast<DXGI_FORMAT>(m_Attributes[i].type) == DXGI_FORMAT_R32_FLOAT) { switch (m_Attributes[i].count) { case 1: current.Format = DXGI_FORMAT_R32_FLOAT; break; case 2: current.Format = DXGI_FORMAT_R32G32_FLOAT; break; case 3: current.Format = DXGI_FORMAT_R32G32B32_FLOAT; break; case 4: current.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; default: HT_ASSERT(false, "[BufferLayout] Attribute count not supported."); } } else { current.Format = static_cast<DXGI_FORMAT>(m_Attributes[i].type); } current.InputSlot = m_Attributes[i].bufferId; current.InputSlotClass = m_Attributes[i].instancing ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA; current.InstanceDataStepRate = m_Attributes[i].instancing ? 1 : 0; if (lastBuffer != m_Attributes[i].bufferId) { lastBuffer = m_Attributes[i].bufferId; current.AlignedByteOffset = 0; } else { current.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; } elementDescs.push_back(current); } } DX(HT_DXDEVICE->CreateInputLayout(&elementDescs[0], elementDescs.size(), shader->GetBufferPointer(), shader->GetBufferSize(), &m_InputLayout)); }
//-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); // Compile shaders ID3DBlob* pBlobVS = nullptr; ID3DBlob* pBlobHSInt = nullptr; ID3DBlob* pBlobHSFracEven = nullptr; ID3DBlob* pBlobHSFracOdd = nullptr; ID3DBlob* pBlobDS = nullptr; ID3DBlob* pBlobPS = nullptr; ID3DBlob* pBlobPSSolid = nullptr; // This macro is used to compile the hull shader with different partition modes // Please see the partitioning mode attribute for the hull shader for more information D3D_SHADER_MACRO integerPartitioning[] = { { "BEZIER_HS_PARTITION", "\"integer\"" }, { 0 } }; D3D_SHADER_MACRO fracEvenPartitioning[] = { { "BEZIER_HS_PARTITION", "\"fractional_even\"" }, { 0 } }; D3D_SHADER_MACRO fracOddPartitioning[] = { { "BEZIER_HS_PARTITION", "\"fractional_odd\"" }, { 0 } }; V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", nullptr, "BezierVS", "vs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobVS ) ); V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", integerPartitioning, "BezierHS", "hs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobHSInt ) ); V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", fracEvenPartitioning, "BezierHS", "hs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobHSFracEven ) ); V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", fracOddPartitioning, "BezierHS", "hs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobHSFracOdd ) ); V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", nullptr, "BezierDS", "ds_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobDS ) ); V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", nullptr, "BezierPS", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobPS ) ); V_RETURN( DXUTCompileFromFile( L"SimpleBezier11.hlsl", nullptr, "SolidColorPS", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pBlobPSSolid ) ); // Create shaders V_RETURN( pd3dDevice->CreateVertexShader( pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), nullptr, &g_pVertexShader ) ); DXUT_SetDebugName( g_pVertexShader, "BezierVS" ); V_RETURN( pd3dDevice->CreateHullShader( pBlobHSInt->GetBufferPointer(), pBlobHSInt->GetBufferSize(), nullptr, &g_pHullShaderInteger ) ); DXUT_SetDebugName( g_pHullShaderInteger, "BezierHS int" ); V_RETURN( pd3dDevice->CreateHullShader( pBlobHSFracEven->GetBufferPointer(), pBlobHSFracEven->GetBufferSize(), nullptr, &g_pHullShaderFracEven ) ); DXUT_SetDebugName( g_pHullShaderFracEven, "BezierHS frac even" ); V_RETURN( pd3dDevice->CreateHullShader( pBlobHSFracOdd->GetBufferPointer(), pBlobHSFracOdd->GetBufferSize(), nullptr, &g_pHullShaderFracOdd ) ); DXUT_SetDebugName( g_pHullShaderFracOdd, "BezierHS frac odd" ); V_RETURN( pd3dDevice->CreateDomainShader( pBlobDS->GetBufferPointer(), pBlobDS->GetBufferSize(), nullptr, &g_pDomainShader ) ); DXUT_SetDebugName( g_pDomainShader, "BezierDS" ); V_RETURN( pd3dDevice->CreatePixelShader( pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(), nullptr, &g_pPixelShader ) ); DXUT_SetDebugName( g_pPixelShader, "BezierPS" ); V_RETURN( pd3dDevice->CreatePixelShader( pBlobPSSolid->GetBufferPointer(), pBlobPSSolid->GetBufferSize(), nullptr, &g_pSolidColorPS ) ); DXUT_SetDebugName( g_pSolidColorPS, "SolidColorPS" ); // Create our vertex input layout - this matches the BEZIER_CONTROL_POINT structure const D3D11_INPUT_ELEMENT_DESC patchlayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; V_RETURN( pd3dDevice->CreateInputLayout( patchlayout, ARRAYSIZE( patchlayout ), pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(), &g_pPatchLayout ) ); DXUT_SetDebugName( g_pPatchLayout, "Primary" ); SAFE_RELEASE( pBlobVS ); SAFE_RELEASE( pBlobHSInt ); SAFE_RELEASE( pBlobHSFracEven ); SAFE_RELEASE( pBlobHSFracOdd ); SAFE_RELEASE( pBlobDS ); SAFE_RELEASE( pBlobPS ); SAFE_RELEASE( pBlobPSSolid ); // Create constant buffers D3D11_BUFFER_DESC Desc; Desc.Usage = D3D11_USAGE_DYNAMIC; Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; Desc.MiscFlags = 0; Desc.ByteWidth = sizeof( CB_PER_FRAME_CONSTANTS ); V_RETURN( pd3dDevice->CreateBuffer( &Desc, nullptr, &g_pcbPerFrame ) ); DXUT_SetDebugName( g_pcbPerFrame, "CB_PER_FRAME_CONSTANTS" ); // Create solid and wireframe rasterizer state objects D3D11_RASTERIZER_DESC RasterDesc; ZeroMemory( &RasterDesc, sizeof(D3D11_RASTERIZER_DESC) ); RasterDesc.FillMode = D3D11_FILL_SOLID; RasterDesc.CullMode = D3D11_CULL_NONE; RasterDesc.DepthClipEnable = TRUE; V_RETURN( pd3dDevice->CreateRasterizerState( &RasterDesc, &g_pRasterizerStateSolid ) ); DXUT_SetDebugName( g_pRasterizerStateSolid, "Solid" ); RasterDesc.FillMode = D3D11_FILL_WIREFRAME; V_RETURN( pd3dDevice->CreateRasterizerState( &RasterDesc, &g_pRasterizerStateWireframe ) ); DXUT_SetDebugName( g_pRasterizerStateWireframe, "Wireframe" ); D3D11_BUFFER_DESC vbDesc; ZeroMemory( &vbDesc, sizeof(D3D11_BUFFER_DESC) ); vbDesc.ByteWidth = sizeof(BEZIER_CONTROL_POINT) * ARRAYSIZE(g_MobiusStrip); vbDesc.Usage = D3D11_USAGE_DEFAULT; vbDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; D3D11_SUBRESOURCE_DATA vbInitData; ZeroMemory( &vbInitData, sizeof(vbInitData) ); vbInitData.pSysMem = g_MobiusStrip; V_RETURN( pd3dDevice->CreateBuffer( &vbDesc, &vbInitData, &g_pControlPointBuffer ) ); DXUT_SetDebugName( g_pControlPointBuffer, "Control Points" ); D3D11_SHADER_RESOURCE_VIEW_DESC vbSRV; ZeroMemory(&vbSRV, sizeof(vbSRV)); vbSRV.Buffer.NumElements = ARRAYSIZE(g_MobiusStrip); vbSRV.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; vbSRV.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; V_RETURN( pd3dDevice->CreateShaderResourceView( g_pControlPointBuffer, &vbSRV, &g_pControlPointSRV ) ); return S_OK; }
/*------------------------------------------- シェーダのコンパイル(3Dオブジェクト) --------------------------------------------*/ HRESULT CreateShaderObj(void) { HRESULT hr; // ********************************************************** // 頂点シェーダのコードをコンパイル ID3DBlob* pBlobVS = NULL; hr = D3DX11CompileFromFile( L"..\\misc\\D3D11Sample18.sh", // ファイル名 NULL, // マクロ定義(なし) NULL, // インクルード・ファイル定義(なし) "VS", // 「VS関数」がシェーダから実行される "vs_4_0", // 頂点シェーダ g_flagCompile, // コンパイル・オプション 0, // エフェクトのコンパイル・オプション(なし) NULL, // 直ぐにコンパイルしてから関数を抜ける。 &pBlobVS, // コンパイルされたバイト・コード NULL, // エラーメッセージは不要 NULL); // 戻り値 if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj D3DX11CompileShaderFromFile", hr); // 頂点シェーダの作成 hr = g_pD3DDevice->CreateVertexShader( pBlobVS->GetBufferPointer(), // バイト・コードへのポインタ pBlobVS->GetBufferSize(), // バイト・コードの長さ NULL, &g_pVertexShader); // 頂点シェーダを受け取る変数 // SAFE_RELEASE(pBlobVS); // バイト・コードを解放 if (FAILED(hr)) { SAFE_RELEASE(pBlobVS); return DXTRACE_ERR(L"CreateShaderObj g_pD3DDevice->CreateVertexShader", hr); } // ********************************************************** // 入力要素 D3D11_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(XMFLOAT3), D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(XMFLOAT3) * 2, D3D11_INPUT_PER_VERTEX_DATA, 0} }; // 入力レイアウト・オブジェクトの作成 hr = g_pD3DDevice->CreateInputLayout( layout, // 定義の配列 _countof(layout), // 定義の要素数 pBlobVS->GetBufferPointer(), // バイト・コードへのポインタ pBlobVS->GetBufferSize(), // バイト・コードのサイズ &g_pInputLayout); // 受け取る変数のポインタ SAFE_RELEASE(pBlobVS); if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj g_pD3DDevice->CreateInputLayout", hr); // ********************************************************** // ピクセル・シェーダのコードをコンパイル ID3DBlob* pBlobPS = NULL; hr = D3DX11CompileFromFile( L"..\\misc\\D3D11Sample18.sh", // ファイル名 NULL, // マクロ定義(なし) NULL, // インクルード・ファイル定義(なし) "PS", // 「PS関数」がシェーダから実行される "ps_4_0", // ピクセル・シェーダ g_flagCompile, // コンパイル・オプション 0, // エフェクトのコンパイル・オプション(なし) NULL, // 直ぐにコンパイルしてから関数を抜ける。 &pBlobPS, // コンパイルされたバイト・コード NULL, // エラーメッセージは不要 NULL); // 戻り値 if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj D3DX11CompileShaderFromFile", hr); // ピクセル・シェーダの作成 hr = g_pD3DDevice->CreatePixelShader( pBlobPS->GetBufferPointer(), // バイト・コードへのポインタ pBlobPS->GetBufferSize(), // バイト・コードの長さ NULL, &g_pPixelShader); // ピクセル・シェーダを受け取る変数 SAFE_RELEASE(pBlobPS); // バイト・コードを解放 if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj g_pD3DDevice->CreatePixelShader", hr); // ピクセル・シェーダのコードをコンパイル hr = D3DX11CompileFromFile( L"..\\misc\\D3D11Sample18.sh", // ファイル名 NULL, // マクロ定義(なし) NULL, // インクルード・ファイル定義(なし) "PS_NOSM", // 「PS_NOSM関数」がシェーダから実行される "ps_4_0", // ピクセル・シェーダ g_flagCompile, // コンパイル・オプション 0, // エフェクトのコンパイル・オプション(なし) NULL, // 直ぐにコンパイルしてから関数を抜ける。 &pBlobPS, // コンパイルされたバイト・コード NULL, // エラーメッセージは不要 NULL); // 戻り値 if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj D3DX11CompileShaderFromFile", hr); // ピクセル・シェーダの作成 hr = g_pD3DDevice->CreatePixelShader( pBlobPS->GetBufferPointer(), // バイト・コードへのポインタ pBlobPS->GetBufferSize(), // バイト・コードの長さ NULL, &g_pPixelShaderNoSM); // ピクセル・シェーダを受け取る変数 SAFE_RELEASE(pBlobPS); // バイト・コードを解放 if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj g_pD3DDevice->CreatePixelShader", hr); // ********************************************************** // ラスタライザ・ステート・オブジェクトの作成 D3D11_RASTERIZER_DESC RSDesc; RSDesc.FillMode = D3D11_FILL_SOLID; // 普通に描画する RSDesc.CullMode = D3D11_CULL_BACK; // 表面を描画する RSDesc.FrontCounterClockwise = FALSE; // 時計回りが表面 RSDesc.DepthBias = 0; RSDesc.DepthBiasClamp = 0; RSDesc.SlopeScaledDepthBias = 0; RSDesc.DepthClipEnable = TRUE; RSDesc.ScissorEnable = FALSE; RSDesc.MultisampleEnable = FALSE; RSDesc.AntialiasedLineEnable = FALSE; hr = g_pD3DDevice->CreateRasterizerState(&RSDesc, &g_pRasterizerState); if (FAILED(hr)) return DXTRACE_ERR(L"CreateShaderObj g_pD3DDevice->CreateRasterizerState", hr); return hr; }
HRESULT Controller::createShader(unsigned int& _outId, const D3D11_INPUT_ELEMENT_DESC _layout[], string _shaderName, string _shaderModel) { HRESULT hr; ID3DBlob *blob; ID3D11InputLayout* layout = nullptr; string fullPath; string model; T* shader = nullptr; /* Vertex */ if(_shaderName != "") { fullPath = m_pWorkingDirectory + "Shaders/" + _shaderName + ".hlsl"; hr = m_renderer->compileShader(fullPath.c_str(), _shaderModel.c_str(), &blob); if(FAILED(hr)) return hr; /* work out what kind of shader we want to construct - yes I know, it's not a pretty solution */ if( typeid(T) == typeid(ID3D11VertexShader) ) hr = m_renderer->g_device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), NULL, &(ID3D11VertexShader*&)shader); else if( typeid(T) == typeid(ID3D11GeometryShader) ) hr = m_renderer->g_device->CreateGeometryShader(blob->GetBufferPointer(), blob->GetBufferSize(), NULL, &(ID3D11GeometryShader*&)shader); else if( typeid(T) == typeid(ID3D11PixelShader) ) hr = m_renderer->g_device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), NULL, &(ID3D11PixelShader*&)shader); else return S_FALSE; if(FAILED(hr)) return hr; if( typeid(T) == typeid(ID3D11VertexShader) ) { hr = m_renderer->g_device->CreateInputLayout(_layout, ARRAYSIZE(standardLayout), blob->GetBufferPointer(), blob->GetBufferSize(), &layout); m_layouts[0] = layout; if(FAILED(hr)) return hr; } blob->Release(); if( typeid(T) == typeid(ID3D11VertexShader) ) { _outId = m_vertexShaders.size(); m_vertexShaders[_outId] = (ID3D11VertexShader*&)shader; } else if( typeid(T) == typeid(ID3D11GeometryShader) ) { _outId = m_geometryShaders.size(); m_geometryShaders[_outId] = (ID3D11GeometryShader*&)shader; } else if( typeid(T) == typeid(ID3D11PixelShader) ) { _outId = m_pixelShaders.size(); m_pixelShaders[_outId] = (ID3D11PixelShader*&)shader; } else // this shouldn't be able to happen { return S_FALSE; } } return S_OK; }
bool Shader::Initialise(ID3D11Device* device, LPCWSTR vertexFilename, LPCWSTR pixelFilename) { //This method loads and compiles the Vertex and Pixel shader code, sets up the vertex layout and creates a CPU accessable buffer to hold the matrices ID3DBlob* vertexShaderBlob = NULL; //Compiled shader code is stored as a binary blob of data, this is for the vertex shader ID3DBlob* pixelShaderBlob = NULL; //and this one is for the pixel shader ID3DBlob* errorBlob = NULL; //Any compiler errors are stored in this blob, they will be a string which we can output if needed const unsigned int numberOfVertexElements = 4; //The input layout needs to know how many elements make up our vertices D3D11_INPUT_ELEMENT_DESC vertexLayout[numberOfVertexElements]; //Each element will have a Description struct which tells us how they should be layed out D3D11_BUFFER_DESC matrixBufferDescription; //We will also need to create a Description struct for the buffer we are creating for the matrices //We use D3DCompileFromFile to compile the HLSL code for our shaders if (FAILED(D3DCompileFromFile(vertexFilename, //The filename of the source code file NULL, //Any marco defines we want to include D3D_COMPILE_STANDARD_FILE_INCLUDE, //Here we can specify include files "main", //This is the name of the entry point method "vs_4_0", //What Shader Model (version) do we want to target, shader model 4 is old but works almost everywhere D3DCOMPILE_ENABLE_STRICTNESS, 0, //Misc flags, more info can be found at MSDN &vertexShaderBlob, &errorBlob))) //Pointers to the shader blob and error blob, these are output parameters, if everything went well then //vertexSahderBlob should be something and errorBlob should be NULL { //If the compilation failed... if (errorBlob) //If there is an error blob then it was most likely a syntax error in the shader { OutputDebugString((char*)errorBlob->GetBufferPointer()); //We'll output it to the Output window in Visual Studio errorBlob->Release(); //And release everything and return false } if (vertexShaderBlob) vertexShaderBlob->Release(); return false; } //Compiling the pixel shader is the same process but we use "ps_4_0" as the shader model if (FAILED(D3DCompileFromFile(pixelFilename, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "ps_4_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pixelShaderBlob, &errorBlob))) { if (errorBlob) { OutputDebugString((char*)errorBlob->GetBufferPointer()); errorBlob->Release(); } if (vertexShaderBlob) vertexShaderBlob->Release(); return false; } //If we have compiled everything correctly then we can create the actual shader objects, if they fail we release everything and return false if (FAILED(device->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &m_vertexShader))) { if (errorBlob) errorBlob->Release(); if (vertexShaderBlob) vertexShaderBlob->Release(); if (pixelShaderBlob) pixelShaderBlob->Release(); return false; } if (FAILED(device->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &m_pixelShader))) { if (errorBlob) errorBlob->Release(); if (vertexShaderBlob) vertexShaderBlob->Release(); if (pixelShaderBlob) pixelShaderBlob->Release(); return false; } //Here we start filling out the Descriptions of each Vertex Element //The Input Layout uses a concept known as "Semantics". Each element has a semantic name, these names match semantics that are defined in the shader code //The order of these descriptions must match the order of the elements on our Vertex struct, see Mesh.h vertexLayout[0].SemanticName = "POSITION"; //The first element is the position vector so we use the "POSITION" semantic vertexLayout[0].SemanticIndex = 0; //Semantics can be indexed (like an array) so that you can pass more then one in. We only have one position though vertexLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; //This specifies how the element is interpreted, our vector is made up of 3 32-bit floats so the format needs to //support that much data vertexLayout[0].InputSlot = 0; //Shader input can come from lots of different places, we only use one input slot so 0 is fine for us vertexLayout[0].AlignedByteOffset = 0; //This specifies the offset from the start of the Vertex where this element begins, //this is the first element so there is no offset. vertexLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; //This specifies that this element is present for each vertex vertexLayout[0].InstanceDataStepRate = 0; //This is for a technique called instancing, we won't be covering it this semester vertexLayout[1].SemanticName = "COLOR"; //The next input element is our colour vertexLayout[1].SemanticIndex = 0; vertexLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;//It is 4 32-bit floats so our format matches that vertexLayout[1].InputSlot = 0; vertexLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; //Here we would calculate the byte offset by factoring in the size of the last element //however this value here tells Direct3D to calculate it for us, which is nice! vertexLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; vertexLayout[1].InstanceDataStepRate = 0; vertexLayout[2].SemanticName = "NORMAL"; //The next element is the normal vertexLayout[2].SemanticIndex = 0; vertexLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; //A normal is 3 32-bit floats vertexLayout[2].InputSlot = 0; vertexLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; vertexLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; vertexLayout[2].InstanceDataStepRate = 0; vertexLayout[3].SemanticName = "TEXCOORD"; //The final element is the texture coordinate vertexLayout[3].SemanticIndex = 0; vertexLayout[3].Format = DXGI_FORMAT_R32G32_FLOAT; //A texture coord is 2 32-bit floats vertexLayout[3].InputSlot = 0; vertexLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; vertexLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; vertexLayout[3].InstanceDataStepRate = 0; //After we have described our input elements we can create our input layout, this method needs the descriptions we created //and the vertex shader with the semantics that match the ones in the descriptions if (FAILED(device->CreateInputLayout(vertexLayout, numberOfVertexElements, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &m_layout))) { if (errorBlob) errorBlob->Release(); if (vertexShaderBlob) vertexShaderBlob->Release(); if (pixelShaderBlob) pixelShaderBlob->Release(); return false; } //After the shaders and the input layout are created then we can release the shader blobs vertexShaderBlob->Release(); vertexShaderBlob = NULL; pixelShaderBlob->Release(); pixelShaderBlob = NULL; //The final step is to configure the buffer that will hold the matrices for the vertex shader matrixBufferDescription.Usage = D3D11_USAGE_DYNAMIC; //The buffer is used for dynamic data that changes often matrixBufferDescription.ByteWidth = sizeof(MatrixBuffer); //It's big enough to hold one "MatrixBuffer" sized object matrixBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER; //It's a buffer containing shader constants matrixBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; //It is directly writable to by the CPU matrixBufferDescription.MiscFlags = 0; //Misc flags matrixBufferDescription.StructureByteStride = 0; //Data offsets //Create the buffer based on that description! if (FAILED(device->CreateBuffer(&matrixBufferDescription, NULL, &m_matrixBuffer))) { return false; } return true; }
/* @NOTE この関数は近い将来撤去されます */ nlVertexShader nlCreateVertexShader( const nlInt8* script, unsigned int scriptSize, const nlInt8* funcName, nlEngineContext& cxt ) { struct GOD_VERTEX { nlVec4 pos_; nlVec4 normal_; nlVec4 uv_; D3DCOLOR color_; }; ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; nlVertexShader vertexShader; vertexShader.inputLayout_ = NULL; vertexShader.shader_ = NULL; #ifdef INTROMODE const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_OPTIMIZATION_LEVEL3; HRESULT hr = D3D10CompileShader( script, scriptSize, funcName, shaderMacros, NULL, funcName, "vs_4_0", flag, &pBlob, &pErrorBlob ); if(FAILED( hr ) ) { MessageBoxA(NULL,(nlInt8*)pErrorBlob->GetBufferPointer(),"",MB_OK); } #else const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR; HRESULT hr = D3D10CompileShader( script, scriptSize, funcName, shaderMacros, NULL, funcName, "vs_4_0", flag, &pBlob, &pErrorBlob ); #endif #ifndef INTROMODE if( FAILED(hr) ) { std::string error = std::string("[")+std::string(funcName)+std::string("]")+std::string(DXGetErrorDescriptionA(hr)); if(pErrorBlob) { error += std::string( (nlInt8*)pErrorBlob->GetBufferPointer() ); error.resize(error.size()-1);/* 改行コードを取り除く */ } NL_ERR( ERR_005, error.c_str() ); /* ファイルに書き出す */ QString fileName; QTime now = QDateTime::currentDateTime().time(); fileName.sprintf("err_%s_%d_%d_d.log",funcName,now.hour(),now.minute(),now.second() ); QString path = sandboxPath(SP_APP)+fileName; QFile dataFile(path); dataFile.open(QIODevice::WriteOnly|QIODevice::Text); dataFile.write( script ); /**/ return vertexShader; } #endif /* create shader */ NL_HR_VALID( cxt.d3dDevice->CreateVertexShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &vertexShader.shader_ ) ); /* create inputlayout */ NL_HR_VALID( cxt.d3dDevice->CreateInputLayout(NLM_INPUT_ELEMENT, _countof(NLM_INPUT_ELEMENT), pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &vertexShader.inputLayout_ ) ); /**/ return vertexShader; }
void CD3DDevice::CreateVertexShaderAndLayout( const char* szFilename, const char* szEntryPoint, InputElementLayout Layout[], uint nLayoutCount, IGfxVertexShader** pShader, IGfxVertexLayout** pLayout ) { ////////////////////////////////////////// ID3D11VertexShader* pVertexShader = NULL; ID3D11InputLayout* pInputLayout = NULL; ID3DBlob* pShaderBlob = NULL; HRESULT hr = S_OK; Result nResult = rResultSuccess; // First compile the shader char szFormattedFilename[256] = { 0 }; sprintf( szFormattedFilename, "%s.hlsl", szFilename ); nResult = CompileShader( szFormattedFilename, szEntryPoint, m_szVSProfile, &pShaderBlob ); ASSERT( nResult == rResultSuccess ); void* pShaderCode = pShaderBlob->GetBufferPointer(); uint nShaderSize = (uint)pShaderBlob->GetBufferSize(); // Then create the shader hr = m_pDevice->CreateVertexShader( pShaderCode, nShaderSize, NULL, &pVertexShader ); assert( hr == S_OK ); // Now return them CD3DVertexShader* pNewShader = new CD3DVertexShader; pNewShader->m_pShader = pVertexShader; *pShader = pNewShader; if( pLayout != NULL ) { //static D3D11_INPUT_ELEMENT_DESC inputLayout[ 16 ] = { 0 }; //// and finally create the input layout //for( uint i = 0; i < nLayoutCount; ++i ) //{ // strcpy( inputLayout[i].SemanticName, Layout[i].szSemanticName ); // inputLayout[i].SemanticIndex = Layout[i].nSlot; // inputLayout[i].Format = (DXGI_FORMAT)Layout[i].nFormat; // inputLayout[i].InputSlot = Layout[i].nIndex; // inputLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; //} if( nLayoutCount == 7 ) { D3D11_INPUT_ELEMENT_DESC inputLayout[] = { { Layout[0].szSemanticName, Layout[0].nIndex, (DXGI_FORMAT)Layout[0].nFormat, Layout[0].nSlot, 0, (D3D11_INPUT_CLASSIFICATION)Layout[0].nData, 0 }, { Layout[1].szSemanticName, Layout[1].nIndex, (DXGI_FORMAT)Layout[1].nFormat, Layout[1].nSlot, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[1].nData, 0 }, { Layout[2].szSemanticName, Layout[2].nIndex, (DXGI_FORMAT)Layout[2].nFormat, Layout[2].nSlot, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[2].nData, 0 }, { Layout[3].szSemanticName, Layout[3].nIndex, (DXGI_FORMAT)Layout[3].nFormat, Layout[3].nSlot, 0, (D3D11_INPUT_CLASSIFICATION)Layout[3].nData, 1 }, { Layout[4].szSemanticName, Layout[4].nIndex, (DXGI_FORMAT)Layout[4].nFormat, Layout[4].nSlot, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[4].nData, 1 }, { Layout[5].szSemanticName, Layout[5].nIndex, (DXGI_FORMAT)Layout[5].nFormat, Layout[5].nSlot, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[5].nData, 1 }, { Layout[6].szSemanticName, Layout[6].nIndex, (DXGI_FORMAT)Layout[6].nFormat, Layout[6].nSlot, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[6].nData, 1 }, }; hr = m_pDevice->CreateInputLayout( inputLayout, nLayoutCount, pShaderCode, nShaderSize, &pInputLayout ); } else if( nLayoutCount == 3 ) { D3D11_INPUT_ELEMENT_DESC inputLayout[] = { { Layout[0].szSemanticName, Layout[0].nSlot, (DXGI_FORMAT)Layout[0].nFormat, Layout[0].nIndex, 0, (D3D11_INPUT_CLASSIFICATION)Layout[0].nData, 0 }, { Layout[1].szSemanticName, Layout[1].nSlot, (DXGI_FORMAT)Layout[1].nFormat, Layout[1].nIndex, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[1].nData, 0 }, { Layout[2].szSemanticName, Layout[2].nSlot, (DXGI_FORMAT)Layout[2].nFormat, Layout[2].nIndex, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[2].nData, 0 }, }; hr = m_pDevice->CreateInputLayout( inputLayout, nLayoutCount, pShaderCode, nShaderSize, &pInputLayout ); } else if( nLayoutCount == 2 ) { D3D11_INPUT_ELEMENT_DESC inputLayout[] = { { Layout[0].szSemanticName, Layout[0].nSlot, (DXGI_FORMAT)Layout[0].nFormat, Layout[0].nIndex, 0, (D3D11_INPUT_CLASSIFICATION)Layout[0].nData, 0 }, { Layout[1].szSemanticName, Layout[1].nSlot, (DXGI_FORMAT)Layout[1].nFormat, Layout[1].nIndex, D3D11_APPEND_ALIGNED_ELEMENT, (D3D11_INPUT_CLASSIFICATION)Layout[1].nData, 0 }, }; hr = m_pDevice->CreateInputLayout( inputLayout, nLayoutCount, pShaderCode, nShaderSize, &pInputLayout ); } else if( nLayoutCount == 1 ) { D3D11_INPUT_ELEMENT_DESC inputLayout[] = { { Layout[0].szSemanticName, Layout[0].nSlot, (DXGI_FORMAT)Layout[0].nFormat, Layout[0].nIndex, 0, (D3D11_INPUT_CLASSIFICATION)Layout[0].nData, 0 }, }; hr = m_pDevice->CreateInputLayout( inputLayout, nLayoutCount, pShaderCode, nShaderSize, &pInputLayout ); } else { ASSERT( 0 ); } assert( hr == S_OK ); CD3DVertexLayout* pNewLayout = new CD3DVertexLayout; pNewLayout->m_pLayout = pInputLayout; *pLayout = pNewLayout; } }
/* GSの生成 */ static void createGS( nlUint32 target, const ShaderScripts& ss, nlEngineContext& cxt ) { /**/ ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; nlGeometoryShader& geometoryShader = cxt.gss[target]; const nlInt8* script = ss.gsScripts.scripts[target].script; const nlInt8* funcName = "main"; /**/ NL_ASSERT(!geometoryShader.shader); /* commonと連結 */ const nlInt8* commonScript = ss.commonScripts.script; const nlUint32 scriptLen = nlStrlen( script ) + nlStrlen( commonScript ); nlInt8* conbinedScript = (nlInt8*)nlMalloc( (scriptLen+1)*sizeof(nlInt8) ); nlStrcat( conbinedScript, commonScript ); nlStrcat( conbinedScript, script ); #ifndef INTROMODE const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR; HRESULT hr = D3D10CompileShader( conbinedScript, nlStrlen(conbinedScript), funcName, shaderMacros, NULL, funcName, "gs_4_0", flag, &pBlob, &pErrorBlob); if( SUCCEEDED(hr) ) { if( SUCCEEDED( cxt.d3dDevice->CreateGeometryShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &geometoryShader.shader ) ) ) { return ;} else { NL_ASSERT(!"このパスには来ないことになっている"); //goto RELOAD; return ; } } else { /* 失敗した場合はエラーを出力し確実に成功するシェーダをロードする */ const nlInt8* name = ss.gsScripts.scripts[target].name; std::string error = std::string("[")+std::string(name)+std::string("]")+std::string(DXGetErrorDescriptionA(hr)); error.resize(error.size()-1);/* 改行コードを取り除く */ if(pErrorBlob) { error += std::string( (nlInt8*)pErrorBlob->GetBufferPointer() ); error.resize(error.size()-1);/* 改行コードを取り除く */ } NL_ERR( ERR_006, error.c_str()); /**/ const nlInt8 script[] = { "struct GSSceneIn\n" "{\n" " float4 Pos : POS;\n" " float3 Norm : NORMAL;\n" " float2 Tex : TEXCOORD0;\n" "};\n" "struct PSSceneIn\n" "{\n" " float4 Pos : SV_Position;\n" " float3 Norm : TEXCOORD0;\n" " float2 Tex : TEXCOORD1;\n" "};\n" "[maxvertexcount(3)]\n" "void GSScene( triangleadj GSSceneIn input[6], inout TriangleStream<PSSceneIn> OutputStream )\n" "{\n" " PSSceneIn output = (PSSceneIn)0;\n" " for( uint i=0; i<6; i+=2 )\n" " {\n" " output.Pos = input[i].Pos;\n" " output.Norm = input[i].Norm;\n" " output.Tex = input[i].Tex;\n" " OutputStream.Append( output );\n" " }\n" " OutputStream.RestartStrip();\n" "}\n" }; geometoryShader = nlCreateGeometoryShader(script, sizeof(script)/sizeof(nlInt8), "main", cxt ); } return; #else const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR | D3D10_SHADER_OPTIMIZATION_LEVEL3; HRESULT hr = D3D10CompileShader( conbinedScript, nlStrlen(conbinedScript), funcName, shaderMacros, NULL, funcName, "gs_4_0", flag, &pBlob, &pErrorBlob ); if( FAILED(hr) ) { MessageBox( NULL, "failed to load geometory shader", "", MB_OK ); if(pErrorBlob) { MessageBox( NULL, (nlInt8*)pErrorBlob->GetBufferPointer(), "", MB_OK ); } return; } NL_HR_VALID( cxt.d3dDevice->CreateGeometryShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &geometoryShader.shader ) ); #endif }
void Terrain::init(ID3D11Device* device) { ID3D11DeviceContext* deviceContext; device->GetImmediateContext(&deviceContext); ID3DBlob* errorBlob; ID3DBlob* shaderBlob; HRESULT result = D3DX11CompileFromFileA("Content\\Effects\\SimpleTerrain.fx", 0, 0, 0, "fx_5_0", 0, 0, 0, &shaderBlob, &errorBlob, 0); char* errorBuffer; if(errorBlob) { errorBuffer = (char*)errorBlob->GetBufferPointer(); } result = D3DX11CreateEffectFromMemory(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), 0, device, &effect); if(shaderBlob) shaderBlob->Release(); if(errorBlob) errorBlob->Release(); // vertex buffer TerrainVertex vertices[] = { {Vector3(0.0f, 0, INSTANCE_SIZE), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(0, 0)}, {Vector3(INSTANCE_SIZE, 0, INSTANCE_SIZE), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(1, 0)}, {Vector3(0.0f, 0, 0.0f), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(0, 1)}, {Vector3(INSTANCE_SIZE, 0, 0.0f), Vector3::up, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), Vector2(1, 1)} }; D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(vertices); vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA vertexData; ZeroMemory( &vertexData, sizeof(D3D11_SUBRESOURCE_DATA) ); vertexData.pSysMem = vertices; device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer); // Instance Buffer TerrainInstance instances[INSTANCE_COUNT]; for(int i = 0; i < INSTANCE_COUNT_X; ++i) for(int j = 0; j < INSTANCE_COUNT_Y; ++j) instances[i * INSTANCE_COUNT_X + j].position = Vector3((float)i*INSTANCE_SIZE, 0, (float)j*INSTANCE_SIZE); D3D11_BUFFER_DESC instanceBufferDesc; ZeroMemory(&instanceBufferDesc, sizeof(D3D11_BUFFER_DESC)); instanceBufferDesc.Usage = D3D11_USAGE_DEFAULT; instanceBufferDesc.ByteWidth = sizeof(instances); instanceBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; instanceBufferDesc.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA instanceData; ZeroMemory(&instanceData, sizeof(D3D11_SUBRESOURCE_DATA)); instanceData.pSysMem = instances; device->CreateBuffer(&instanceBufferDesc, &instanceData, &instanceBuffer); // index buffer unsigned indices[] = { 0, 1, 2, 3 }; indexCount = sizeof(indices) / sizeof(unsigned); D3D11_BUFFER_DESC indexBufferDesc; ZeroMemory(&indexBufferDesc, sizeof(D3D11_BUFFER_DESC)); indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(indices); indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA indexData; ZeroMemory(&indexData, sizeof(D3D11_SUBRESOURCE_DATA)); indexData.pSysMem = indices; device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer); D3D11_INPUT_ELEMENT_DESC inputElementDesc[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 1, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1} }; int inputElementCount = sizeof(inputElementDesc) / sizeof(D3D11_INPUT_ELEMENT_DESC); technique = effect->GetTechniqueByIndex(0); pass = technique->GetPassByIndex(0); D3DX11_PASS_DESC passDesc; pass->GetDesc(&passDesc); result = device->CreateInputLayout(inputElementDesc, inputElementCount, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &inputLayout); DXUTGetGlobalResourceCache().CreateTextureFromFile(device, deviceContext, L"Content/Textures/Terrain/Grass.dds", &surfaceTexture); evSurfaceTexture = effect->GetVariableByName("SurfaceTexture")->AsShaderResource(); evWorld = effect->GetVariableByName("World")->AsMatrix(); evViewProjection = effect->GetVariableByName("ViewProjection")->AsMatrix(); evSurfaceTexture->SetResource(surfaceTexture); world = Matrix::createTranslation((-INSTANCE_COUNT_X * INSTANCE_SIZE) / 2, 0, (-INSTANCE_COUNT_Y * INSTANCE_SIZE) / 2); deviceContext->Release(); }
void Simulation::InitializePipeline() { D3D11_INPUT_ELEMENT_DESC vDesc[] = { { "POSITION", NULL, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, NULL }, { "COLOR", NULL, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, NULL }, { "TEXCOORD", NULL, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, NULL }, { "NORMAL", NULL, DXGI_FORMAT_R32G32B32_FLOAT, 0, 36, D3D11_INPUT_PER_VERTEX_DATA, NULL }, { "TANGENT", NULL, DXGI_FORMAT_R32G32B32_FLOAT, 0, 44, D3D11_INPUT_PER_VERTEX_DATA, NULL } }; ID3DBlob* vertexByte; D3DReadFileToBlob(L"Default.cso", &vertexByte); dev->CreateInputLayout(vDesc, ARRAYSIZE(vDesc), vertexByte->GetBufferPointer(), vertexByte->GetBufferSize(), &inputLayout); ReleaseMacro(vertexByte); D3D11_BUFFER_DESC cd; ZeroMemory(&cd, sizeof(D3D11_BUFFER_DESC)); cd.ByteWidth = sizeof(matrixBufferData); cd.Usage = D3D11_USAGE_DEFAULT; cd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cd.CPUAccessFlags = 0; cd.MiscFlags = 0; cd.StructureByteStride = 0; dev->CreateBuffer(&cd, NULL, &matrixBuffer); D3D11_BLEND_DESC bd; ZeroMemory(&bd, sizeof(D3D11_BLEND_DESC)); bd.AlphaToCoverageEnable = false; bd.IndependentBlendEnable = false; bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; dev->CreateBlendState(&bd, &blendState); D3D11_RASTERIZER_DESC rd; ZeroMemory(&rd, sizeof(D3D11_RASTERIZER_DESC)); rd.FillMode = D3D11_FILL_WIREFRAME; rd.CullMode = D3D11_CULL_BACK; rd.FrontCounterClockwise = false; rd.DepthBias = 0; rd.DepthBiasClamp = 0; rd.SlopeScaledDepthBias = 0; rd.DepthClipEnable = true; rd.ScissorEnable = false; rd.MultisampleEnable = false; rd.AntialiasedLineEnable = false; dev->CreateRasterizerState(&rd, &wireframe); rd.FillMode = D3D11_FILL_SOLID; dev->CreateRasterizerState(&rd, &solid); D3D11_DEPTH_STENCIL_DESC dsd; ZeroMemory(&dsd, sizeof(D3D11_DEPTH_STENCIL_DESC)); dsd.DepthEnable = true; dsd.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; dsd.StencilEnable = false; dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; dsd.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; dsd.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; dsd.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; dsd.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsd.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsd.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; dsd.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; dsd.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsd.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dev->CreateDepthStencilState(&dsd, &depthStencilState); }
bool KeyboardDemo::LoadContent( ) { ID3DBlob* vsBuffer = 0; bool compileResult = CompileD3DShader( "CustomColor.hlsl", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { MessageBox( 0, "Error loading vertex shader!", "Compile Error", MB_OK ); return false; } HRESULT d3dResult; d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &customColorVS_ ); if( FAILED( d3dResult ) ) { if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); vsBuffer->Release( ); if( FAILED( d3dResult ) ) { return false; } ID3DBlob* psBuffer = 0; compileResult = CompileD3DShader( "CustomColor.hlsl", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { MessageBox( 0, "Error loading pixel shader!", "Compile Error", MB_OK ); return false; } d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &customColorPS_ ); psBuffer->Release( ); if( FAILED( d3dResult ) ) { return false; } VertexPos vertices[] = { XMFLOAT3( 0.5f, 0.5f, 0.5f ), XMFLOAT3( 0.5f, -0.5f, 0.5f ), XMFLOAT3( -0.5f, -0.5f, 0.5f ) }; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 3; D3D11_SUBRESOURCE_DATA resourceData; ZeroMemory( &resourceData, sizeof( resourceData ) ); resourceData.pSysMem = vertices; d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, &resourceData, &vertexBuffer_ ); if( FAILED( d3dResult ) ) { return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory( &constDesc, sizeof( constDesc ) ); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof( XMFLOAT4 ); constDesc.Usage = D3D11_USAGE_DEFAULT; d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &colorCB_ ); if( FAILED( d3dResult ) ) { return false; } return true; }
HRESULT DrawFunction::CompileTheShader(void) { HRESULT hr = S_OK;//ret ID3DBlob* pVSBlob = nullptr; ID3DBlob* pErrorBlob = nullptr; //Compiler vertex shader //组建加载顶点着色器 hr = D3DCompileFromFile(L"Squance.fx", nullptr, nullptr, "VS", "vs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pVSBlob, &pErrorBlob); if (FAILED(hr)) { #ifdef _DEBUG printf("Fail in FX_VS File \n Error HRESULT:%ld\n Error:%s\n", hr, pErrorBlob->GetBufferPointer()); return hr; #else MessageBox(nullptr, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; #endif } //Create VERTEX shader hr = dev->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &pVertexShader); if (FAILED(hr)) { pVSBlob->Release(); return hr; } // Define the input layout //定义输入布局 D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE(layout); // Create the input layout hr = dev->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout); if (FAILED(hr)) return hr; // Set the input layout devContext->IASetInputLayout(pVertexLayout); // Compile the pixel shader //组建加载像素着色器 ID3DBlob* pPSBlob = nullptr; hr = D3DCompileFromFile(L"Squance.fx", nullptr, nullptr, "PS", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, &pPSBlob, &pErrorBlob); if (FAILED(hr)) { #ifdef _DEBUG printf("Fail in FX_FS File \n Error HRESULT:%ld\n Error:%s\n", hr, pErrorBlob->GetBufferPointer()); return hr; #else MessageBox(nullptr, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; #endif } // Create the pixel shader hr = dev->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &pPixelShader); if (FAILED(hr)) return hr; //release resource pVSBlob->Release(); pPSBlob->Release(); return hr; }
bool D3D11GeometryShader::Initialize(ShaderBytecode *_bytecode, int rasterized_stream, const std::vector<StreamOutDescriptor> &stream_outs) { CHECK(bytecode==0)<<"Cannot initialize twice"; bytecode = static_cast<D3D11ShaderBytecode *>(_bytecode); const D3D11ShaderReflection &reflect = *bytecode->GetReflection(); std::vector<D3D11_SO_DECLARATION_ENTRY> entries; uint32_t size = reflect.GetOutputSize(); for (uint32_t i = 0; i < size; i++) { const D3D11ShaderReflection::Parameter& output_param = reflect.GetOutput(i); int slot_index = -1; for (auto it = stream_outs.begin(); it != stream_outs.end(); it++) { if (output_param.stream == it->stream_index) { slot_index = it->index; } } if (slot_index != -1) { D3D11_SO_DECLARATION_ENTRY entry; entry.Stream = output_param.stream; entry.SemanticName = output_param.semantic.c_str(); entry.SemanticIndex = output_param.semantic_index; entry.StartComponent = 0; entry.ComponentCount = output_param.size / TypeInfoManager::GetSingleton()->Get(output_param.type_name).GetSize(); entry.OutputSlot = slot_index; entries.push_back(entry); } } unsigned real_rasterized_stream; if (rasterized_stream < 0) { real_rasterized_stream = D3D11_SO_NO_RASTERIZED_STREAM; } else { real_rasterized_stream = rasterized_stream; } ID3DBlob *blob = bytecode->GetBlob(); HRESULT result = 1; result = manager->GetDevice()->CreateGeometryShaderWithStreamOutput( blob->GetBufferPointer(), blob->GetBufferSize(), &entries[0], entries.size(), 0, 0, real_rasterized_stream, 0, &shader ); if(FAILED(result)) { S2StringFormat(&error, "Fail to create streamout geometry shader error %d", GetLastError()); return false; } else { return true; } }
bool InitD3D11QuadRendering( RENDERER_SETTINGS * settings ) { ID3DBlob * pCode = NULL; ID3DBlob * pErrors = NULL; if (D3DCompile( defaultVertexShader, strlen(defaultVertexShader), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) { printf("[Renderer] D3DCompile failed\n"); return false; } if (pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pVertexShader ) != S_OK) { printf("[Renderer] CreateVertexShader failed\n"); return false; } ////////////////////////////////////////////////////////////////////////// static float pQuad[] = { -1.0, -1.0, 0.5, 0.0, 0.0, -1.0, 1.0, 0.5, 0.0, 1.0, 1.0, -1.0, 0.5, 1.0, 0.0, 1.0, 1.0, 0.5, 1.0, 1.0, }; D3D11_BUFFER_DESC desc; ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC)); desc.ByteWidth = sizeof(float) * 5 * 4; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA subData; ZeroMemory(&subData, sizeof(D3D11_SUBRESOURCE_DATA)); subData.pSysMem = pQuad; if (pDevice->CreateBuffer(&desc, &subData, &pFullscreenQuadVB) != S_OK) { printf("[Renderer] CreateBuffer failed\n"); return false; } static D3D11_INPUT_ELEMENT_DESC pQuadDesc[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, }; if (pDevice->CreateInputLayout( pQuadDesc, 2, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pFullscreenQuadLayout) != S_OK) { printf("[Renderer] CreateInputLayout failed\n"); return false; } ////////////////////////////////////////////////////////////////////////// D3D11_VIEWPORT viewport; ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = settings->nWidth; viewport.Height = settings->nHeight; pContext->RSSetViewports(1, &viewport); ////////////////////////////////////////////////////////////////////////// D3D11_SAMPLER_DESC sampDesc = CD3D11_SAMPLER_DESC( CD3D11_DEFAULT() ); sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; if (pDevice->CreateSamplerState( &sampDesc, &pFullscreenQuadSamplerState ) != S_OK) return false; ////////////////////////////////////////////////////////////////////////// D3D11_BUFFER_DESC cbDesc; ZeroMemory( &cbDesc, sizeof(D3D11_BUFFER_DESC) ); cbDesc.ByteWidth = sizeof( pFullscreenQuadConstants ); cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; ZeroMemory( &subData, sizeof(D3D11_SUBRESOURCE_DATA) ); subData.pSysMem = &pFullscreenQuadConstants; if (pDevice->CreateBuffer( &cbDesc, &subData, &pFullscreenQuadConstantBuffer ) != S_OK) return false; ////////////////////////////////////////////////////////////////////////// D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() ); if (pDevice->CreateBlendState( &blendDesc, &pFullscreenQuadBlendState ) != S_OK) return false; D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() ); if (pDevice->CreateRasterizerState( &rastDesc, &pFullscreenQuadRasterizerState ) != S_OK) return false; return true; }
HRESULT ForwardRenderer::init(HWND hwnd, ID3D11Device* pDevice, ID3D11DeviceContext* pContext, IDXGISwapChain* pSwapChain) { // Create a render target view HRESULT hr = S_OK; pRenderTarget = NULL; RECT rc; GetClientRect( hwnd, &rc ); mWidth = rc.right - rc.left; mHeight = rc.bottom - rc.top; ID3D11Texture2D* pBackBuffer = NULL; hr = pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return hr; hr = pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTarget ); pBackBuffer->Release(); if( FAILED( hr ) ) return hr; pContext->OMSetRenderTargets( 1, &pRenderTarget, NULL ); CreateDepthStencil(pDevice, pContext); // Setup the viewport D3D11_VIEWPORT vp; vp.Width = (FLOAT)mWidth; vp.Height = (FLOAT)mHeight; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; pContext->RSSetViewports( 1, &vp ); // Create the constant buffer D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; bd.StructureByteStride = 0; hr = pDevice->CreateBuffer( &bd, NULL, &g_pConstantBuffer ); if( FAILED( hr ) ) return hr; // Create test light shader // Compile the pixel shader ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile2( "testShader.fx", "PSSolid", "ps_4_0", &pPSBlob ); if( FAILED( hr ) ) { MessageBox( NULL, "The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", "Error", MB_OK ); return hr; } // Create the pixel shader hr = pDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShaderSolid ); pPSBlob->Release(); if( FAILED( hr ) ) return hr; // Initialize the world matrix g_World = XMMatrixIdentity(); // Initialize the view matrix XMVECTOR Eye = XMVectorSet( 0.0f, 1.0f, -5.0f, 0.0f ); XMVECTOR At = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); g_View = XMMatrixLookAtLH( Eye, At, Up ); // Initialize the projection matrix g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV4, mWidth / (FLOAT)mHeight, 0.01f, 100.0f ); pTestCamera = new Camera(); return S_OK; }
HRESULT DXSourceWindow::CreateShaderResources() { HRESULT hr = S_OK; // Set up constant buffer D3D11_BUFFER_DESC Desc; Desc.Usage = D3D11_USAGE_DYNAMIC; Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; Desc.MiscFlags = 0; Desc.ByteWidth = sizeof( CUBE_CB ); hr = m_pd3dDevice->CreateBuffer( &Desc, NULL, &m_Cube_pcb ); PASS_TEST( hr ); // create vertex buffer const float pVertices[] = { -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f }; const float pNormal[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f }; const float pTexture[] = { 1.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f, 0.0f,0.0f}; const float pColors[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; CUBE_Vertex1 verts[24]; for (int i=0; i<24; i++) { verts[i].pos = D3DXVECTOR3(pVertices[3*i], pVertices[3*i+1], pVertices[3*i+2]); verts[i].texture = D3DXVECTOR2(pTexture[2*i], pTexture[2*i+1] ); verts[i].normal = D3DXVECTOR3(pNormal[3*i], pNormal[3*i+1], pNormal[3*i+2] ); verts[i].color = D3DXVECTOR3(pColors[3*i], pColors[3*i+1], pColors[3*i+2]); } D3D11_BUFFER_DESC vbDesc = {0}; vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; // Type of resource vbDesc.ByteWidth = 24*sizeof(CUBE_Vertex1); // size in bytes vbDesc.Usage = D3D11_USAGE_DEFAULT; vbDesc.CPUAccessFlags = 0; vbDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vbData = {0}; vbData.pSysMem = verts; hr = m_pd3dDevice->CreateBuffer( &vbDesc, &vbData, &m_Cube_pVertexBuffer); PASS_TEST(hr); // create index buffer int indices[36] = {-1}; for (int i=0; i<6; i++) { indices[6*i]=4*i; indices[6*i+1]=4*i+1; indices[6*i+2]=4*i+3; indices[6*i+3]=4*i+1; indices[6*i+4]=4*i+2; indices[6*i+5]=4*i+3; } vbDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; vbDesc.ByteWidth = 36*sizeof(unsigned int); vbData.pSysMem = indices; hr = m_pd3dDevice->CreateBuffer( &vbDesc, &vbData, &m_Cube_pIndexBuffer ); PASS_TEST(hr); // Compile the shaders using the lowest possible profile for broadest feature level support ID3DBlob* pVertexShaderBuffer = NULL; hr = CompileShaderFromFile(L"DrawCube.hlsl", "VSMain", "vs_4_0_level_9_1", &pVertexShaderBuffer ); if ( hr == D3D11_ERROR_FILE_NOT_FOUND ) { MessageBoxA(NULL,"ERROR, file DrawCube.hlsl not found.","DirectGMA",NULL); return D3D11_ERROR_FILE_NOT_FOUND; } PASS_TEST(hr); hr = m_pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), NULL, &m_Cube_pVertexShader ); PASS_TEST(hr); ID3DBlob* pPixelShaderBuffer = NULL; hr = CompileShaderFromFile( L"DrawCube.hlsl", "PSMain", "ps_4_0_level_9_1", &pPixelShaderBuffer ); PASS_TEST(hr); hr = m_pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), NULL, &m_Cube_pPixelShader ); PASS_TEST(hr); // Create our vertex input layout const D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; hr = m_pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &m_Cube_pVertexLayout11 ); PASS_TEST(hr); SAFE_RELEASE( pVertexShaderBuffer ); SAFE_RELEASE( pPixelShaderBuffer ); // Create a sampler state D3D11_SAMPLER_DESC sampDesc; ZeroMemory( &sampDesc, sizeof(sampDesc) ); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = m_pd3dDevice->CreateSamplerState( &sampDesc, &m_Cube_pSamplerLinear ); PASS_TEST(hr); // Set the raster state D3D11_RASTERIZER_DESC RasterizerDesc; RasterizerDesc.FillMode = D3D11_FILL_SOLID; RasterizerDesc.CullMode = D3D11_CULL_NONE; RasterizerDesc.FrontCounterClockwise = TRUE; RasterizerDesc.DepthBias = 0; RasterizerDesc.DepthBiasClamp = 0.0f; RasterizerDesc.SlopeScaledDepthBias = 0.0f; RasterizerDesc.DepthClipEnable = TRUE; RasterizerDesc.ScissorEnable = FALSE; RasterizerDesc.MultisampleEnable = FALSE; RasterizerDesc.AntialiasedLineEnable = FALSE; hr = m_pd3dDevice->CreateRasterizerState( &RasterizerDesc, &m_Cube_pRasterizerStateSolid ); PASS_TEST(hr); // Set state Objects m_pImmediateContext->RSSetState( m_Cube_pRasterizerStateSolid ); hr = D3DX11CreateShaderResourceViewFromFile( m_pd3dDevice, L"amdlogo.dds", NULL, NULL, &m_Cube_pTextureRV, NULL ); if ( hr == D3D11_ERROR_FILE_NOT_FOUND ) { MessageBoxA(NULL,"ERROR, file amdlogo.dds not found.","DirectGMA",NULL); return D3D11_ERROR_FILE_NOT_FOUND; } PASS_TEST(hr); return S_OK; }
void DeferredRendering::CreateShaders() { ID3DBlob* errorBlob; HRESULT hr; ID3DBlob* pVS = nullptr; //Deferred rendering geo vertex shader D3DCompileFromFile(L"GeoVertex.hlsl", nullptr, nullptr, "VS_main", "vs_4_0", 0, 0, &pVS, nullptr); Device->CreateVertexShader(pVS->GetBufferPointer(), pVS->GetBufferSize(), nullptr, &GeoVertexShader); D3D11_INPUT_ELEMENT_DESC geoInputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA, 0 },{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA, 0 },{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT,0,20,D3D11_INPUT_PER_VERTEX_DATA, 0 } }; Device->CreateInputLayout(geoInputDesc, ARRAYSIZE(geoInputDesc), pVS->GetBufferPointer(), pVS->GetBufferSize(), &GeoVertexLayout); pVS->Release(); //Deferred rendering and shadow map pixel shader D3DCompileFromFile(L"LightVertex.hlsl", nullptr, nullptr, "VS_main", "vs_4_0", 0, 0, &pVS, nullptr); Device->CreateVertexShader(pVS->GetBufferPointer(), pVS->GetBufferSize(), nullptr, &LightVertexShader); D3D11_INPUT_ELEMENT_DESC lightInputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA, 0 } }; Device->CreateInputLayout(lightInputDesc, ARRAYSIZE(lightInputDesc), pVS->GetBufferPointer(), pVS->GetBufferSize(), &LightVertexLayout); pVS->Release(); //Compiling LightShadowVertex Shader D3DCompileFromFile(L"LightShadowVertex.hlsl", nullptr, nullptr, "VS_main", "vs_4_0", 0, 0, &pVS, nullptr); Device->CreateVertexShader(pVS->GetBufferPointer(), pVS->GetBufferSize(), nullptr, &LightShadowVertexShader); D3D11_INPUT_ELEMENT_DESC LightShadowInputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA, 0 },{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA, 0 },{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT,0,20,D3D11_INPUT_PER_VERTEX_DATA, 0 } }; Device->CreateInputLayout(LightShadowInputDesc, ARRAYSIZE(LightShadowInputDesc), pVS->GetBufferPointer(), pVS->GetBufferSize(), &LightShadowVertexLayout); pVS->Release(); //Geometry shader ID3DBlob* pGS = nullptr; hr = D3DCompileFromFile(L"GeoGeometryShader.hlsl", nullptr, nullptr, "GS_main", "gs_4_0", 0, 0, &pGS, &errorBlob); if (FAILED(hr)) { if (errorBlob != nullptr) { OutputDebugStringA((char*)errorBlob->GetBufferPointer()); errorBlob->Release(); } } Device->CreateGeometryShader(pGS->GetBufferPointer(), pGS->GetBufferSize(), nullptr, &GeoGeometryShader); pGS->Release(); //Pixel shader ID3DBlob* pPS = nullptr; hr = D3DCompileFromFile(L"LightFragment.hlsl", nullptr, nullptr, "PS_main", "ps_4_0", 0, 0, &pPS, &errorBlob); if (FAILED(hr)) { if (errorBlob != nullptr) { OutputDebugStringA((char*)errorBlob->GetBufferPointer()); errorBlob->Release(); } } Device->CreatePixelShader(pPS->GetBufferPointer(), pPS->GetBufferSize(), nullptr, &LightPixelShader); pPS->Release(); hr = D3DCompileFromFile(L"GeoFragment.hlsl", nullptr, nullptr, "PS_main", "ps_4_0", 0, 0, &pPS, &errorBlob); if (FAILED(hr)) { if (errorBlob != nullptr) { OutputDebugStringA((char*)errorBlob->GetBufferPointer()); errorBlob->Release(); } } Device->CreatePixelShader(pPS->GetBufferPointer(), pPS->GetBufferSize(), nullptr, &GeoPixelShader); pPS->Release(); }