Exemplo n.º 1
0
CDirect3D9Texture::CDirect3D9Texture(IDirect3DDevice9Ex* device, const PTexture& texture)
    : m_device(device)
{
    // Automatically generates mipmaps.
    HRESULT hr;
    D3DFORMAT fmt = PixelFormats[static_cast<uint>(texture.pixelFormat)];
    IDirect3DTexture9* pTexture;
    hr = device->CreateTexture(texture.width, texture.height, 0, 0, fmt,
        D3DPOOL_DEFAULT, &pTexture, NULL);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to create texture: " + string(DXGetErrorStringA(hr)));
    m_texture = make_directx_unique<IDirect3DTexture9>(pTexture);

    // Load bits into surface.
    auto surface = make_directx_unique<IDirect3DSurface9>(LoadTexture(m_device, texture));

    // Copy surface into texture.
    IDirect3DSurface9* pTexSurface;
    hr = m_texture->GetSurfaceLevel(0, &pTexSurface);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to get texture surface level 0: " + string(DXGetErrorDescriptionA(hr)));
    auto texSurface = make_directx_unique<IDirect3DSurface9>(pTexSurface);

    hr = device->UpdateSurface(surface.get(), NULL, pTexSurface, NULL);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to update surface: " + string(DXGetErrorDescriptionA(hr)));
}
Exemplo n.º 2
0
void CDirect3D9MeshPack::Bind(byte_t meshIdx)
{
    HRESULT hr;
    hr = m_device->SetStreamSource(0, m_vb.get(), m_meshes[meshIdx].vertexOffset,
        VertexByteSize(m_meshes[meshIdx].vertexType));
    if (FAILED(hr))
        LLWARNINGF(boost::format("Failed to set stream source: %s") % DXGetErrorDescriptionA(hr));

    hr = m_device->SetVertexDeclaration(m_vdecls[meshIdx].get());
    if (FAILED(hr))
        LLWARNINGF(boost::format("Failed to set vertex decl: %s") % DXGetErrorDescriptionA(hr));

    hr = m_device->SetIndices(m_ib.get());
    if (FAILED(hr))
        LLWARNINGF(boost::format("Failed to set indices: %s") % DXGetErrorDescriptionA(hr));
}
Exemplo n.º 3
0
tuple<byte_t*, uint> CDirect3D9DynamicTexture::Lock()
{
    D3DLOCKED_RECT lock;
    HRESULT hr = m_texture->LockRect(0, &lock, NULL, D3DLOCK_DISCARD);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to lock surface: " + string(DXGetErrorDescriptionA(hr)));
    return make_tuple(static_cast<byte_t*>(lock.pBits), lock.Pitch);
}
Exemplo n.º 4
0
tuple<byte_t*, uint> CDirect3D9DynamicTexture::Lock(const rect_t& rectangle)
{
    D3DLOCKED_RECT lock;
    const RECT rect = { rectangle.left, rectangle.top, rectangle.right, rectangle.bottom };
    HRESULT hr = m_texture->LockRect(0, &lock, &rect, 0);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to lock surface: " + string(DXGetErrorDescriptionA(hr)));
    return make_tuple(static_cast<byte_t*>(lock.pBits), lock.Pitch);
}
Exemplo n.º 5
0
void CDirect3D9CubeTexture::UpdateCubeMapSurface(D3DCUBEMAP_FACES face, IDirect3DSurface9* surface)
{
    HRESULT hr;
    IDirect3DSurface9* pCubeSurface;
    hr = m_cubeMap->GetCubeMapSurface(face, 0, &pCubeSurface);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to get cube texture surface level 0: " + string(DXGetErrorDescriptionA(hr)));
    auto cubeSurface = make_directx_unique<IDirect3DSurface9>(pCubeSurface);

    hr = m_device->UpdateSurface(surface, NULL, pCubeSurface, NULL);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to update surface: " + string(DXGetErrorDescriptionA(hr)));
}
bool D3DCheckHresult(HRESULT hr, const char* szInfo)
{
	if (FAILED(hr))
	{
		std::string msg;
		msg.append(DXGetErrorDescriptionA(hr));
		msg.append(" : ");
		msg.append(szInfo);
		MessageBoxA(NULL,msg.c_str(),"error",MB_OK);
		assert(false);
		return false;
	}
	return true;
}
Exemplo n.º 7
0
void CDirect3D9Platform::DrawMesh(const PMesh& mesh)
{
    // Only attempt to draw if has indices and positions.
    if (mesh.indexCount > 0 && (mesh.vertexType & PMesh::Positions)) {
        HRESULT hr = m_d3dDevice->DrawIndexedPrimitive(
            d3dPrimitiveTypes[static_cast<int>(mesh.primitive)],
            0,
            0,
            mesh.vertexCount,
            mesh.indexOffset/sizeof(int32_t),
            mesh.indexCount/3);
        if (FAILED(hr))
            LLWARNINGF(boost::format("Draw error: %s") % DXGetErrorDescriptionA(hr));
    }
}
Exemplo n.º 8
0
void
failed(trace::Call &call, HRESULT hr)
{
    std::ostream &os = warning(call);

    os << "failed with 0x" << std::hex << hr << std::dec;

    LPCSTR lpszErrorString = DXGetErrorStringA(hr);
    assert(lpszErrorString);
    os << " (" << lpszErrorString << "): ";

    char szErrorDesc[512];
    DXGetErrorDescriptionA(hr, szErrorDesc, sizeof szErrorDesc);
    os << szErrorDesc;

    os << "\n";
}
Exemplo n.º 9
0
bool Display::setViewConstantBuffer(const XMMATRIX& view, const XMMATRIX& invView)
{
	D3D11_MAPPED_SUBRESOURCE map;
	HRESULT hr = context_->Map(cbView, 0, D3D11_MAP_WRITE_DISCARD, 0 , &map);
	if(FAILED(hr))
	{
		CoreError::debugOutput(DXGetErrorDescriptionA(hr));
		return false;
	}
	CB_View* cb = (CB_View*)map.pData;
	cb->view = XMMatrixTranspose(view);
	cb->invView = XMMatrixTranspose(invView);
	context_->Unmap(cbView,0);

	context_->VSSetConstantBuffers(1,1,&cbView);
	context_->PSSetConstantBuffers(1,1,&cbView);
	context_->GSSetConstantBuffers(1,1,&cbView);
	return true;
}
Exemplo n.º 10
0
bool Display::setProjectionConstantBuffer(const XMMATRIX& projection, const XMMATRIX& invprojection)
{
	D3D11_MAPPED_SUBRESOURCE map;
	HRESULT hr = context_->Map(cbProjection, 0, D3D11_MAP_WRITE_DISCARD, 0 , &map);
	if(FAILED(hr))
	{
		CoreError::debugOutput(DXGetErrorDescriptionA(hr));
		return false;
	}

	CB_Projection cb;
	cb.projection = XMMatrixTranspose(projection);
	cb.invprojection = XMMatrixTranspose(invprojection);
	memcpy(map.pData, &cb, sizeof(CB_Projection));
	context_->Unmap(cbProjection,0);

	context_->VSSetConstantBuffers(2,1,&cbProjection);
	context_->PSSetConstantBuffers(2,1,&cbProjection);
	context_->GSSetConstantBuffers(2,1,&cbProjection);
	return true;
}
Exemplo n.º 11
0
void cgl::CGLLogger::LogObjectState( UINT logType, cgl::CGLObject* pObject, HRESULT result, void* pData )
{
	switch (logType)
	{
	case CGL_NOTIFICATION_INVALID_PTR:			{ Print("ERROR: invalid ptr"); } break;
	case CGL_NOTIFICATION_INSTANTIATION:		{ Print("INFO:  instantiated [%i]->%s ",				pObject->getLuid(), pObject->getTypeName().c_str()); } break;
	case CGL_NOTIFICATION_CYCLIC_DEPENDENCY:	{ Print("ERROR: cyclic dependency detected [%i]->%s",	pObject->getLuid(), pObject->getTypeName().c_str()); } break;
	case CGL_NOTIFICATION_RESET:				{ Print("INFO:  reset [%i]->%s",						pObject->getLuid(), pObject->getTypeName().c_str()); } break;
	case CGL_NOTIFICATION_DESCTRUCTION:			{ Print("INFO:  destroyed [%i]->%s",					pObject->getLuid(), pObject->getTypeName().c_str()); } break;
	case CGL_NOTIFICATION_STILL_ALIVE:			{ Print("WARNING: still alive [%i]->%s",				pObject->getLuid(), pObject->getTypeName().c_str()); } break;
	case CGL_NOTIFICATION_COM_INTERFACE_STILL_ALIVE: { Print("ERROR: [%i]->%s::OnReset() COM interface not fully released (%i refs)", pObject->getLuid(), pObject->getTypeName().c_str(), *((int*)pData) ); } break;
	case CGL_NOTIFICATION_NO_DEVICE:
		{
			if (pObject)
			{
				Print("ERROR: registration failed [%i]->%s\n                            Error: no device registered!\n",
					pObject->getLuid(),	
					pObject->getTypeName().c_str());
			}
			else
			{
				Print("ERROR: no device registered!");
			}
		} break;

	case CGL_NOTIFICATION_CREATION:
		{
			if (SUCCEEDED(result))
			{
				Print("INFO:  created [%i]->%s ",
					  pObject->getLuid(),
					  pObject->getTypeName().c_str());
			}
			else
			{			
				Print("ERROR: creation failed [%i]->%s\n                            Error: %s"
					                                 "\n                            Description: %s\n",
					 pObject->getLuid(),
					 pObject->getTypeName().c_str(),
					 DXGetErrorStringA(result),
					 DXGetErrorDescriptionA(result));
			}
		} break;

	case CGL_NOTIFICATION_RESTORATION:
		{
			if (SUCCEEDED(result))
			{
				Print("INFO:  restored [%i]->%s",
					   pObject->getLuid(),
					   pObject->getTypeName().c_str());
			}
			else
			{
				Print("ERROR: failed [%i]->%s::OnRestore()\n                            Error: %s"
													                           "\n                            Description: %s\n",
					   pObject->getLuid(),
					   pObject->getTypeName().c_str(),
					   DXGetErrorStringA(result),
					   DXGetErrorDescriptionA(result));
			}
		} break;

	case CGL_NOTIFICATION_REGISTRATION:
		{
			if (SUCCEEDED(result))
			{
				Print("INFO:  registered [%i]->%s",
					  pObject->getLuid(),
					  pObject->getTypeName().c_str());
			}
			else
			{
				Print("ERROR: not registered [%i]->%s",
					  pObject->getLuid(),
					  pObject->getTypeName().c_str());
			}
		} break;
	}
}
Exemplo n.º 12
0
const char8 * DXHelperGetErrorDescription( HRESULT hr)
{
  return Format("(DX) %s - %s", DXGetErrorStringA(hr), DXGetErrorDescriptionA(hr));
}
Exemplo n.º 13
0
/* @NOTE この関数は近い将来撤去されます */
nlPixelShader nlCreatePixelShader( 
                                  const nlInt8* script, 
                                  unsigned int scriptSize, 
                                  const nlInt8* funcName,
                                  nlEngineContext& cxt )
{
    ID3DBlob* pBlob = NULL;
    ID3DBlob* pErrorBlob = NULL;
    nlPixelShader pixelShader;
    pixelShader.shader_ = NULL;
#ifndef INTROMODE
    const DWORD flag = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR;
    HRESULT hr = D3D10CompileShader( script, scriptSize, funcName, shaderMacros, NULL, funcName, "ps_4_0", flag, &pBlob, &pErrorBlob );
    if( FAILED(hr) )
    {
        std::string error = std::string("[")+std::string(funcName)+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_018, 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 );
        /**/
        pixelShader.shader_ = NULL;
        return pixelShader;
    }
#else
    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, "ps_4_0", flag, &pBlob, &pErrorBlob );
    if( FAILED(hr) )
    {
        MessageBox( NULL, (nlInt8*)pErrorBlob->GetBufferPointer(), "", MB_OK );
    }
#endif
    NL_HR_VALID( cxt.d3dDevice->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), NULL, &pixelShader.shader_ ) );

    return pixelShader;
}
Exemplo n.º 14
0
HRESULT HookIDirect3D9::CreateDevice(LPVOID _this, UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DDevice9** ppReturnedDeviceInterface)
{

	LOG_API();
#if 1
	HRESULT res = 0;
#if 0
	if (configMgr.GetConfig(TTX_CONFIG_WINDOWED))
	{

		D3DPRESENT_PARAMETERS d3dpp;
		RECT rect;

		ShowWindow(hFocusWindow, SW_HIDE);
		GetClientRect(hFocusWindow, &rect);
		AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
		SetWindowLong(hFocusWindow, GWL_STYLE, WS_OVERLAPPEDWINDOW);
		SetWindowPos(hFocusWindow, HWND_TOPMOST, 100, 100, rect.right, rect.bottom, SWP_FRAMECHANGED | SWP_NOCOPYBITS);
		ShowWindow(hFocusWindow, SW_SHOWNORMAL);
		ShowCursor(TRUE);
		InvalidateRect(hFocusWindow, NULL, TRUE);

		logmsg("--%d,%d,%d,%d\n", rect.left,rect.top,rect.right,rect.bottom);

		ZeroMemory(&d3dpp, sizeof(d3dpp));


		GetClientRect(pPresentationParameters->hDeviceWindow, &rect);

		logmsg("Area = %d,%d\n", pPresentationParameters->BackBufferWidth, pPresentationParameters->BackBufferHeight);
		d3dpp.BackBufferHeight = pPresentationParameters->BackBufferHeight;
		d3dpp.BackBufferWidth = pPresentationParameters->BackBufferWidth;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.BackBufferFormat = pPresentationParameters->BackBufferFormat;
		d3dpp.BackBufferCount = pPresentationParameters->BackBufferCount;
		d3dpp.Windowed = TRUE;
		d3dpp.hDeviceWindow = NULL;//pPresentationParameters->hDeviceWindow;
		d3dpp.FullScreen_RefreshRateInHz = 0;
		d3dpp.PresentationInterval = pPresentationParameters->PresentationInterval;
		d3dpp.AutoDepthStencilFormat = pPresentationParameters->AutoDepthStencilFormat;
		d3dpp.Flags = pPresentationParameters->Flags;
		d3dpp.EnableAutoDepthStencil = TRUE;


		res = pD3D->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, &d3dpp, &pD3Dev);
	} else 
#endif
		logmsg("RES %dx%d\n", pPresentationParameters->BackBufferWidth, pPresentationParameters->BackBufferHeight);
		//pPresentationParameters->BackBufferWidth = 1920;
		//pPresentationParameters->BackBufferHeight = 1080;
		res = pD3D->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, &pD3Dev);
	if (FAILED(res)) {
		logmsg("Err = %X\n", res);
		MessageBox(hFocusWindow, DXGetErrorDescriptionA(res), "Erro Direct3D", MB_OK);
		*ppReturnedDeviceInterface = NULL;
	} else {
		*ppReturnedDeviceInterface = (IDirect3DDevice9*) pD3DevWrapper;
	}

	return res;
#else
	return pD3D->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface);
#endif
}
Exemplo n.º 15
0
/* @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;
}
Exemplo n.º 16
0
static IDirect3DSurface9* LoadTexture(IDirect3DDevice9Ex* device, const PTexture& texture)
{
    assert(device);
    HRESULT hr;
    IDirect3DSurface9* pSurface;

    D3DFORMAT fmt = PixelFormats[static_cast<uint>(texture.pixelFormat)];
    hr = device->CreateOffscreenPlainSurface(texture.width, texture.height,
        fmt, D3DPOOL_SYSTEMMEM, &pSurface, NULL);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to create offscreen surface: " + string(DXGetErrorDescriptionA(hr)));


    D3DLOCKED_RECT lockedRect;
    pSurface->LockRect(&lockedRect, NULL, D3DLOCK_DISCARD);
    // FIXME pitch?
    memcpy(lockedRect.pBits, texture.bits, texture.bitsSize);
    pSurface->UnlockRect();

    return pSurface;
}
Exemplo n.º 17
0
        /* 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
        }
Exemplo n.º 18
0
        /* 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
        }
Exemplo n.º 19
0
void cgl::CGLManager::Notify( UINT notificationType, CGLObject* pObject /*= NULL*/, HRESULT result /*= S_OK */, void* pData )
{
	bool debugOutput = true;
	if (m_notificationCallback)
	{
		debugOutput = m_notificationCallback(notificationType, pObject, result, DXGetErrorStringA(result), DXGetErrorDescriptionA(result));
	}

	if (debugOutput)
	{
		CGLLogger::LogObjectState(notificationType, pObject, result, pData);
	}
}
Exemplo n.º 20
0
bool GFXD3D9Shader::_compileShader( const Torque::Path &filePath, 
                                    const String& target,                                  
                                    const D3DXMACRO *defines, 
                                    GenericConstBufferLayout* bufferLayoutF, 
                                    GenericConstBufferLayout* bufferLayoutI,
                                    Vector<GFXShaderConstDesc> &samplerDescriptions )
{
   PROFILE_SCOPE( GFXD3D9Shader_CompileShader );

   HRESULT res = D3DERR_INVALIDCALL;
   LPD3DXBUFFER code = NULL;
   LPD3DXBUFFER errorBuff = NULL;

#ifdef TORQUE_DEBUG
   U32 flags = D3DXSHADER_DEBUG;
#else
   U32 flags = 0;
#endif

#ifdef TORQUE_OS_XENON
   flags |= D3DXSHADER_PREFER_FLOW_CONTROL;
#endif

#ifdef D3DXSHADER_USE_LEGACY_D3DX9_31_DLL
   if( D3DX_SDK_VERSION >= 32 )
   {
      // will need to use old compiler for 1_1 shaders - check for pixel
      // or vertex shader with appropriate version.
      if ((target.compare("vs1", 3) == 0) || (target.compare("vs_1", 4) == 0))      
         flags |= D3DXSHADER_USE_LEGACY_D3DX9_31_DLL;

      if ((target.compare("ps1", 3) == 0) || (target.compare("ps_1", 4) == 0))
         flags |= D3DXSHADER_USE_LEGACY_D3DX9_31_DLL;
   }
#endif

#if !defined(TORQUE_OS_XENON) && (D3DX_SDK_VERSION <= 40)
#error This version of the DirectX SDK is too old. Please install a newer version of the DirectX SDK: http://msdn.microsoft.com/en-us/directx/default.aspx
#endif

   ID3DXConstantTable* table = NULL;

   static String sHLSLStr( "hlsl" );
   static String sOBJStr( "obj" );

   // Is it an HLSL shader?
   if ( filePath.getExtension().equal(sHLSLStr, String::NoCase) )   
   {
      FrameAllocatorMarker fam;
      char *buffer = NULL;

      // Set this so that the D3DXInclude::Open will have this 
      // information for relative paths.
      smD3DXInclude->setPath( filePath.getRootAndPath() );

      FileStream s;
      if ( !s.open( filePath, Torque::FS::File::Read ) )
      {
         AssertISV(false, avar("GFXD3D9Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str()));

         if ( smLogErrors )
            Con::errorf( "GFXD3D9Shader::_compileShader - Failed to open shader file '%s'.", 
               filePath.getFullPath().c_str() );

         return false;
      }

      // Convert the path which might have virtualized
      // mount paths to a real file system path.
      Torque::Path realPath;
      if ( !FS::GetFSPath( filePath, realPath ) )
         realPath = filePath;

      // Add a #line pragma so that error and warning messages
      // returned by the HLSL compiler report the right file.
      String linePragma = String::ToString( "#line 1 \"%s\"\r\n", realPath.getFullPath().c_str() );
      U32 linePragmaLen = linePragma.length();

      U32 bufSize = s.getStreamSize();
      buffer = (char *)fam.alloc( bufSize + linePragmaLen + 1 );
      dStrncpy( buffer, linePragma.c_str(), linePragmaLen );
      s.read( bufSize, buffer + linePragmaLen );
      buffer[bufSize+linePragmaLen] = 0;

      res = GFXD3DX.D3DXCompileShader( buffer, bufSize + linePragmaLen, defines, smD3DXInclude, "main", 
         target, flags, &code, &errorBuff, &table );
   }

   // Is it a precompiled obj shader?
   else if ( filePath.getExtension().equal( sOBJStr, String::NoCase ) )
   {     
      FileStream  s;
      if(!s.open(filePath, Torque::FS::File::Read))
      {
         AssertISV(false, avar("GFXD3D9Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str()));

         if ( smLogErrors )
            Con::errorf( "GFXD3D9Shader::_compileShader - Failed to open shader file '%s'.", 
               filePath.getFullPath().c_str() );

         return false;
      }

      res = GFXD3DX.D3DXCreateBuffer(s.getStreamSize(), &code);
      AssertISV(res == D3D_OK, "Unable to create buffer!");
      s.read(s.getStreamSize(), code->GetBufferPointer());
      
      if (res == D3D_OK)
      {
         DWORD* data = (DWORD*) code->GetBufferPointer();
         res = GFXD3DX.D3DXGetShaderConstantTable(data, &table);
      }
   }
   else
   {
      if ( smLogErrors )
         Con::errorf( "GFXD3D9Shader::_compileShader - Unsupported shader file type '%s'.", 
            filePath.getFullPath().c_str() );

      return false;
   }

   if ( res != D3D_OK && smLogErrors )
      Con::errorf( "GFXD3D9Shader::_compileShader - Error compiling shader: %s: %s (%x)", 
         DXGetErrorStringA(res), DXGetErrorDescriptionA(res), res );

   if ( errorBuff )
   {
      // remove \n at end of buffer
      U8 *buffPtr = (U8*) errorBuff->GetBufferPointer();
      U32 len = dStrlen( (const char*) buffPtr );
      buffPtr[len-1] = '\0';

      if( res != D3D_OK )
      {
         if ( smLogErrors )
            Con::errorf( "   %s", (const char*) errorBuff->GetBufferPointer() );
      }
      else
      {
         if ( smLogWarnings )
            Con::warnf( "%s", (const char*) errorBuff->GetBufferPointer() );
      }
   }
   else if ( code == NULL && smLogErrors )
      Con::errorf( "GFXD3D9Shader::_compileShader - no compiled code produced; possibly missing file '%s'.", 
         filePath.getFullPath().c_str() );

   // Create the proper shader if we have code
   if( code != NULL )
   {
      #ifndef TORQUE_SHIPPING

         LPD3DXBUFFER disassem = NULL;
         D3DXDisassembleShader( (DWORD*)code->GetBufferPointer(), false, NULL, &disassem );
         mDissasembly = (const char*)disassem->GetBufferPointer();         
         SAFE_RELEASE( disassem );

         if ( gDisassembleAllShaders )
         {
             String filename = filePath.getFullPath();
            filename.replace( ".hlsl", "_dis.txt" );

            FileStream *fstream = FileStream::createAndOpen( filename, Torque::FS::File::Write );
            if ( fstream )
            {            
               fstream->write( mDissasembly );
               fstream->close();
               delete fstream;   
            }
         }

      #endif

      if (target.compare("ps_", 3) == 0)      
         res = mD3D9Device->CreatePixelShader( (DWORD*)code->GetBufferPointer(), &mPixShader );
      else
         res = mD3D9Device->CreateVertexShader( (DWORD*)code->GetBufferPointer(), &mVertShader );

      if (res == S_OK)
         _getShaderConstants(table, bufferLayoutF, bufferLayoutI, samplerDescriptions);

#ifdef TORQUE_ENABLE_CSF_GENERATION

      // Ok, we've got a valid shader and constants, let's write them all out.
      if ( !_saveCompiledOutput(filePath, code, bufferLayoutF, bufferLayoutI) && smLogErrors )
         Con::errorf( "GFXD3D9Shader::_compileShader - Unable to save shader compile output for: %s", 
            filePath.getFullPath().c_str() );

#endif

      SAFE_RELEASE(table);

      if ( res != S_OK && smLogErrors )
         Con::errorf( "GFXD3D9Shader::_compileShader - Unable to create shader for '%s'.", 
            filePath.getFullPath().c_str() );
   }

   bool result = code != NULL && res == S_OK;

   SAFE_RELEASE( code );
   SAFE_RELEASE( errorBuff );

   return result;
}