Exemple #1
0
static bool hlsl_compile_program(
      void *data,
      unsigned idx,
      void *program_data,
      struct shader_program_info *program_info)
{
   HRESULT ret, ret_fp, ret_vp;
   hlsl_shader_data_t *hlsl                  = (hlsl_shader_data_t*)data;
   d3d_video_t *d3d                          = (d3d_video_t*)hlsl->d3d;
   struct shader_program_hlsl_data *program  = (struct shader_program_hlsl_data*)program_data;
   LPDIRECT3DDEVICE d3d_device_ptr           = (LPDIRECT3DDEVICE)d3d->dev;
   ID3DXBuffer *listing_f                    = NULL;
   ID3DXBuffer *listing_v                    = NULL;
   ID3DXBuffer *code_f                       = NULL;
   ID3DXBuffer *code_v                       = NULL;

   if (!program)
      program = &hlsl->prg[idx];

   if (program_info->is_file)
   {
      ret_fp = D3DXCompileShaderFromFile(program_info->combined, NULL, NULL,
            "main_fragment", "ps_3_0", 0, &code_f, &listing_f, &program->f_ctable); 
      ret_vp = D3DXCompileShaderFromFile(program_info->combined, NULL, NULL,
            "main_vertex", "vs_3_0", 0, &code_v, &listing_v, &program->v_ctable); 
   }
   else
   {
      /* TODO - crashes currently - to do with 'end of line' of stock shader */
      ret_fp = D3DXCompileShader(program_info->combined, strlen(program_info->combined), NULL, NULL,
            "main_fragment", "ps_3_0", 0, &code_f, &listing_f, &program->f_ctable );
      ret_vp = D3DXCompileShader(program_info->combined, strlen(program_info->combined), NULL, NULL,
            "main_vertex", "vs_3_0", 0, &code_v, &listing_v, &program->v_ctable );
   }

   if (ret_fp < 0 || ret_vp < 0 || listing_v || listing_f)
   {
      RARCH_ERR("Cg/HLSL error:\n");
      if(listing_f)
         RARCH_ERR("Fragment:\n%s\n", (char*)listing_f->GetBufferPointer());
      if(listing_v)
         RARCH_ERR("Vertex:\n%s\n", (char*)listing_v->GetBufferPointer());

      ret = false;
      goto end;
   }

   d3d_device_ptr->CreatePixelShader((const DWORD*)code_f->GetBufferPointer(),  &program->fprg);
   d3d_device_ptr->CreateVertexShader((const DWORD*)code_v->GetBufferPointer(), &program->vprg);
   code_f->Release();
   code_v->Release();

end:
   if (listing_f)
      listing_f->Release();
   if (listing_v)
      listing_v->Release();
   return ret;
}
void CompileShader()
{
	DWORD dwShaderFlags = 0;

#if defined( DEBUG ) || defined( _DEBUG )
    // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
    // Setting this flag improves the shader debugging experience, but still allows 
    // the shaders to be optimized and to run exactly the way they will run in 
    // the release configuration of this program.
    dwShaderFlags |= D3DXSHADER_DEBUG;
    #endif

#ifdef DEBUG_VS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG;
    #endif
#ifdef DEBUG_PS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG;
    #endif
	
	WCHAR* shader_file = L"torus_shader.hlsl";

	// Compile Vertex Shader
	LPD3DXBUFFER pVertexShaderCode;
	HRESULT hr = D3DXCompileShaderFromFile(shader_file, NULL, NULL, "VS", "vs_3_0", dwShaderFlags, &pVertexShaderCode, NULL, NULL);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Compile Vertex Shader Failed!", 0);
	}

	// Create Vertex Shader
	hr = g_pd3dDevice->CreateVertexShader((DWORD*)pVertexShaderCode->GetBufferPointer(), &g_pVertexShader);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Create Vertex Shader Failed!", 0);
	}

	// Compile Pixel Shader
	LPD3DXBUFFER pPixelShaderCode;
	hr = D3DXCompileShaderFromFile(shader_file, NULL, NULL, "PS", "ps_3_0", dwShaderFlags, &pPixelShaderCode, NULL, NULL);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Compile Pixel Shader Failed!", 0);
	}

	// Create Pixel Shader
	hr = g_pd3dDevice->CreatePixelShader((DWORD*)pPixelShaderCode->GetBufferPointer(), &g_pPixelShader);
	if(FAILED(hr))
	{
		MessageBox(NULL, L"Error", L"Create Pixel Shader Failed!", 0);
	}

	// cleanup
	pVertexShaderCode->Release();
	pPixelShaderCode->Release();
}
Exemple #3
0
Plane* Plane::init(LPDIRECT3DDEVICE9 device) {

	CUSTOMVERTEX vtx[] = {
		CUSTOMVERTEX(D3DXVECTOR3(-1, 0,  1), D3DXVECTOR3(0, 1, 0), 0x00ffffff, D3DXVECTOR2(0, 0)),
		CUSTOMVERTEX(D3DXVECTOR3( 1, 0,  1), D3DXVECTOR3(0, 1, 0), 0x00ffffff, D3DXVECTOR2(1, 0)),
		CUSTOMVERTEX(D3DXVECTOR3(-1, 0, -1), D3DXVECTOR3(0, 1, 0), 0xffffffff, D3DXVECTOR2(0, 1)),
		CUSTOMVERTEX(D3DXVECTOR3( 1, 0, -1), D3DXVECTOR3(0, 1, 0), 0xffffffff, D3DXVECTOR2(1, 1)),
	};
	setVertices(vtx, 4);

	LPD3DXBUFFER code;
	LPD3DXBUFFER error;

	D3DXCompileShaderFromFile("shader.hlsl", NULL, NULL,
								"vertexShaderTexture", "vs_2_0", 0,
								&code, &error, &_vs_constant_table);

	if(error) {
		OutputDebugString((LPCSTR)error->GetBufferPointer());
		vbuf->Release();
		error->Release();
		return 0;
	}

	device->CreateVertexShader((DWORD*)code->GetBufferPointer(), &_vs);
	code->Release();

	D3DXCompileShaderFromFile("shader.hlsl", NULL, NULL,
								"pixelShaderTexture", "ps_2_0", 0,
								&code, &error, &_ps_constant_table);

	if(error) {
		OutputDebugString((LPCSTR)error->GetBufferPointer());
		vbuf->Release();
		_vs_constant_table->Release();
		_vs->Release();
		error->Release();
		return 0;
	}

	device->CreatePixelShader((DWORD*)code->GetBufferPointer(), &_ps);
	code->Release();

	D3DXCreateTextureFromFile(device, "textures/ground.png", &texture);

	angle = (D3DX_PI / 180.0f * 2);
	//D3DXMATRIX rot;
	//D3DXMatrixRotationAxis(&rot, &D3DXVECTOR3(1, 0, 0), (D3DX_PI / 180.0f * -90));
	//world *= rot;

	return this;
}
Exemple #4
0
static bool load_program(void *data, unsigned index, const char *prog, bool path_is_file)
{
   d3d_video_t *d3d = (d3d_video_t*)data;
   LPDIRECT3DDEVICE d3d_device_ptr = (LPDIRECT3DDEVICE)d3d->dev;
   HRESULT ret, ret_fp, ret_vp;
   ID3DXBuffer *listing_f = NULL;
   ID3DXBuffer *listing_v = NULL;
   ID3DXBuffer *code_f = NULL;
   ID3DXBuffer *code_v = NULL;

   if (path_is_file)
   {
      ret_fp = D3DXCompileShaderFromFile(prog, NULL, NULL,
            "main_fragment", "ps_3_0", 0, &code_f, &listing_f, &prg[index].f_ctable); 
      ret_vp = D3DXCompileShaderFromFile(prog, NULL, NULL,
            "main_vertex", "vs_3_0", 0, &code_v, &listing_v, &prg[index].v_ctable); 
   }
   else
   {
      /* TODO - crashes currently - to do with 'end of line' of stock shader */
      ret_fp = D3DXCompileShader(prog, strlen(prog), NULL, NULL,
            "main_fragment", "ps_3_0", 0, &code_f, &listing_f, &prg[index].f_ctable );
      ret_vp = D3DXCompileShader(prog, strlen(prog), NULL, NULL,
            "main_vertex", "vs_3_0", 0, &code_v, &listing_v, &prg[index].v_ctable );
   }

   if (ret_fp < 0 || ret_vp < 0 || listing_v || listing_f)
   {
      RARCH_ERR("Cg/HLSL error:\n");
      if(listing_f)
         RARCH_ERR("Fragment:\n%s\n", (char*)listing_f->GetBufferPointer());
      if(listing_v)
         RARCH_ERR("Vertex:\n%s\n", (char*)listing_v->GetBufferPointer());

      ret = false;
      goto end;
   }

   d3d_device_ptr->CreatePixelShader((const DWORD*)code_f->GetBufferPointer(), &prg[index].fprg);
   d3d_device_ptr->CreateVertexShader((const DWORD*)code_v->GetBufferPointer(), &prg[index].vprg);
   code_f->Release();
   code_v->Release();

end:
   if (listing_f)
      listing_f->Release();
   if (listing_v)
      listing_v->Release();
   return ret;
}
HRESULT CD3D9ShaderMaterialRenderer::stubD3DXCompileShaderFromFile(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines, 
								LPD3DXINCLUDE pInclude, LPCSTR pFunctionName,
								LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs,
								LPD3DXCONSTANTTABLE* ppConstantTable)
{
	// wondering what I'm doing here?
	// see comment in CD3D9ShaderMaterialRenderer::stubD3DXAssembleShader()

	#if ( D3DX_SDK_VERSION < 24 ) 
		// directly link functions, old d3d sdks didn't try to load external dlls
		// when linking to the d3dx9.lib
		#ifdef _MSC_VER
		#pragma comment (lib, "d3dx9.lib")
		#endif

		// invoke static linked function
		return D3DXCompileShaderFromFile(pSrcFile, pDefines, pInclude, pFunctionName, pProfile, Flags, ppShader, ppErrorMsgs, ppConstantTable);
	#else
	{
		// try to load shader functions from the dll and print error if failed.
	
		// D3DXCompileShaderFromFileA
		typedef HRESULT (WINAPI *D3DXCompileShaderFromFileFunction)(LPCSTR pSrcFile,
			CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName,
			LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs,
			LPD3DXCONSTANTTABLE* ppConstantTable);

		static bool LoadFailed = false;
		static D3DXCompileShaderFromFileFunction pFn = 0;

		if (!pFn && !LoadFailed)
		{
			// try to load dll
			core::stringc strDllName = "d3dx9_";
			strDllName += (int)D3DX_SDK_VERSION;
			strDllName += ".dll";

			HMODULE hMod = LoadLibrary(strDllName.c_str());
			if (hMod)
				 pFn = (D3DXCompileShaderFromFileFunction)GetProcAddress(hMod, "D3DXCompileShaderFromFileA");

			if (!pFn)
			{
				LoadFailed = true;
				os::Printer::log("Could not load shader function D3DXCompileShaderFromFileA from dll, shaders disabled", 
					strDllName.c_str(), ELL_ERROR);				
			}
		}

		if (pFn)
		{
			// call already loaded function
			return (*pFn)(pSrcFile, pDefines, pInclude, pFunctionName, pProfile, Flags, ppShader, ppErrorMsgs, ppConstantTable);
		}
	}
	#endif // D3DX_SDK_VERSION < 24

	return 0;
}
HRESULT EvaluateMask::CreateShaders()
{
    LPD3DXBUFFER pCode = NULL;

    if( FAILED( D3DXCompileShaderFromFile
                ("Shaders/evaluate_motionmask.psh", NULL, NULL,
                 "ViewThreshold", "ps_3_0", NULL, &pCode, NULL, &m_tabViewThres) ) )
        return E_FAIL;
    if( FAILED( g_pd3dDevice->CreatePixelShader
                ((DWORD*)pCode->GetBufferPointer(), &m_shViewThres) ) )
        return E_FAIL;
    SAFE_RELEASE( pCode );

    if( FAILED( D3DXCompileShaderFromFile
                ("Shaders/evaluate_motionmask.psh", NULL, NULL,
                 "ViewGraphCuts", "ps_3_0", NULL, &pCode, NULL, &m_tabViewGraph) ) )
        return E_FAIL;
    if( FAILED( g_pd3dDevice->CreatePixelShader
                ((DWORD*)pCode->GetBufferPointer(), &m_shViewGraph) ) )
        return E_FAIL;
    SAFE_RELEASE( pCode );

    if( FAILED( D3DXCompileShaderFromFile
                ("Shaders/evaluate_motionmask.psh", NULL, NULL,
                 "ViewDynamicProg", "ps_3_0", NULL, &pCode, NULL, &m_tabViewReliable) ) )
        return E_FAIL;
    if( FAILED( g_pd3dDevice->CreatePixelShader
                ((DWORD*)pCode->GetBufferPointer(), &m_shViewReliable) ) )
        return E_FAIL;
    SAFE_RELEASE( pCode );

    if( FAILED( D3DXCompileShaderFromFile
                ("Shaders/evaluate_motionmask.psh", NULL, NULL,
                 "EvaluateMask", "ps_3_0", NULL, &pCode, NULL, &m_tabEvalMask) ) )
        return E_FAIL;
    if( FAILED( g_pd3dDevice->CreatePixelShader
                ((DWORD*)pCode->GetBufferPointer(), &m_shEvalMask) ) )
        return E_FAIL;
    SAFE_RELEASE( pCode );

    return S_OK;
}
Exemple #7
0
void D3D9PixelShader::Reset(GraphicsDevice &graphics)
{
    FreeMemory();

    HRESULT hr;

    _device = graphics.CastD3D9().GetDevice();
    Assert(_device != NULL, "_device == NULL");

    DWORD dwShaderFlags = 0;
    #ifdef DEBUG_PS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_DEBUG;
    #endif

    LPD3DXBUFFER pCode = NULL;
    LPD3DXBUFFER pErrors = NULL;

    PersistentAssert(Utility::FileExists(_shaderFile), String("Shader file not found: ") + _shaderFile);

    // Assemble the vertex shader from the file
    hr = D3DXCompileShaderFromFile( _shaderFile.CString(), NULL, NULL, "PShaderEntry",
                                    "ps_3_0", dwShaderFlags, &pCode,
                                    &pErrors, &_constantTable );
    
    String ErrorString;
    if(pErrors)
    {
        char *ErrorMessage = (char *)pErrors->GetBufferPointer();
        DWORD ErrorLength = pErrors->GetBufferSize();

        ofstream file("ShaderDebug.txt");
        for(UINT i = 0; i < ErrorLength; i++)
        {
            file << ErrorMessage[i];
            ErrorString += String(ErrorMessage[i]);
        }
        file.close();
    }

    PersistentAssert(!FAILED(hr), String("D3DXCompileShaderFromFile failed: ") + ErrorString);

    hr = _device->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                            &_shader );

    if(pErrors)
    {
        pErrors->Release();
    }
    if(pCode)
    {
        pCode->Release();
    }
    PersistentAssert(!FAILED(hr), "CreatePixelShader failed");
}
void D3D9PixelShader::Reset(LPDIRECT3DDEVICE9 _Device)
{
    FreeMemory();

    HRESULT hr;

    Device = _Device;
    Assert(Device != NULL, "Device == NULL");

    DWORD dwShaderFlags = 0;
    #ifdef DEBUG_PS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_DEBUG;
    #endif

    LPD3DXBUFFER pCode = NULL;
    LPD3DXBUFFER pErrors = NULL;

    // Assemble the vertex shader from the file
    hr = D3DXCompileShaderFromFile( ShaderFile.CString(), NULL, NULL, "PShaderEntry",
                                    "ps_3_0", dwShaderFlags, &pCode,
                                    &pErrors, &ConstantTable );
    
    String ErrorString;
    if(pErrors)
    {
        char *ErrorMessage = (char *)pErrors->GetBufferPointer();
        DWORD ErrorLength = pErrors->GetBufferSize();

        ofstream file("ShaderDebug.txt");
        for(UINT i = 0; i < ErrorLength; i++)
        {
            file << ErrorMessage[i];
            ErrorString += String(ErrorMessage[i]);
        }
        file.close();
    }

    PersistentAssert(!FAILED(hr), String("D3DXCompileShaderFromFile failed: ") + ErrorString);

    // Create the vertex shader
    hr = Device->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                            &Shader );

    if(pErrors)
    {
        pErrors->Release();
    }
    if(pCode)
    {
        pCode->Release();
    }
    PersistentAssert(!FAILED(hr), "CreatePixelShader failed");
}
Exemple #9
0
	ETOOLS_API HRESULT WINAPI
		D3DX_CompileShaderFromFile(
		LPCSTR                          pSrcFile,
		CONST D3DXMACRO*                pDefines,
		LPD3DXINCLUDE                   pInclude,
		LPCSTR                          pFunctionName,
		LPCSTR                          pTarget,
		DWORD                           Flags,
		LPD3DXBUFFER*                   ppShader,
		LPD3DXBUFFER*                   ppErrorMsgs,
		LPD3DXCONSTANTTABLE*            ppConstantTable)
	{
		return D3DXCompileShaderFromFile(
			pSrcFile, pDefines, pInclude, pFunctionName, pTarget,
			Flags, ppShader, ppErrorMsgs, ppConstantTable);
	}
Exemple #10
0
void Overlay::CreateNullPixelShader()
{
    HRESULT hr;

    DWORD dwShaderFlags = 0;
    D3D9Base::LPD3DXBUFFER pCode = NULL;
    D3D9Base::LPD3DXBUFFER pErrors = NULL;

    String ShaderFilename = g_Globals.BaseDirectory + String("\\") + String("Null.psh");

    PersistentAssert(Utility::FileExists(ShaderFilename), "Null.psh not found");

    // Assemble the vertex shader from the file
    hr = D3DXCompileShaderFromFile( ShaderFilename.CString(), NULL, NULL, "PShaderEntry",
                                    "ps_3_0", dwShaderFlags, &pCode,
                                    &pErrors, NULL );
    
    String ErrorString;
    if(pErrors)
    {
        char *ErrorMessage = (char *)pErrors->GetBufferPointer();
        DWORD ErrorLength = pErrors->GetBufferSize();

        for(UINT i = 0; i < ErrorLength; i++)
        {
            g_Globals.ErrorFile() << ErrorMessage[i];
            ErrorString += String(ErrorMessage[i]);
        }
    }

    PersistentAssert(!FAILED(hr), String("D3DXCompileShaderFromFile failed: ") + ErrorString);

    // Create the pixel shader
    hr = _Device->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                     &_NullPixelShader );

    if(pErrors)
    {
        pErrors->Release();
    }
    if(pCode)
    {
        pCode->Release();
    }
    PersistentAssert(!FAILED(hr), "CreatePixelShader failed");
}
HRESULT D3D9RenderImpl::SetPixelShader(LPCWSTR pPixelShaderName, LPCSTR entryPoint, LPCSTR shaderModel, LPSTR* ppError)
{
    CComPtr<ID3DXBuffer> code;
    CComPtr<ID3DXBuffer> errMsg;

    HRESULT hr = D3DXCompileShaderFromFile(pPixelShaderName, NULL, NULL, entryPoint, shaderModel, 0, &code, &errMsg, &m_pPixelConstantTable);
    if (FAILED(hr))
    {	
        if(errMsg != NULL)
        {
            size_t len = errMsg->GetBufferSize() + 1;
            *ppError = new CHAR[len];		
            memcpy(*ppError, errMsg->GetBufferPointer(), len);	
        }
        return hr;
    }

    return m_pDevice->CreatePixelShader((DWORD*)code->GetBufferPointer(), &m_pPixelShader);
}
Exemple #12
0
bool Create_VS(char* hlsl, char* name, LPDIRECT3DVERTEXSHADER9* shader, LPD3DXCONSTANTTABLE* table, LPDIRECT3DDEVICE9 pDevice)
{
	HRESULT hr;
	LPD3DXBUFFER err;
	LPD3DXBUFFER code;
	// hlsl読み込み
	hr = D3DXCompileShaderFromFile(hlsl, NULL, NULL, name, "vs_3_0", 0, &code, &err, table);
	if (FAILED(hr)){
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), name, MB_OK);
		err->Release();
		return false;
	}
	// ピクセルシェーダ作成 
	hr = pDevice->CreateVertexShader((DWORD*)code->GetBufferPointer(), shader);
	if (FAILED(hr)){
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), name, MB_OK);
		return false;
	}
	return true;
}
// Load and compiler a HLSL pixel shader from a file. Provide the source code filename and pointers
// to the variables to hold the resultant shader and it associated constant table
bool LoadPixelShader( const string& fileName, LPDIRECT3DPIXELSHADER9* pixelShader,
					  LPD3DXCONSTANTTABLE* constants )
{
	// Temporary variable to hold compiled pixel shader code
    LPD3DXBUFFER pShaderCode;

	// Compile external HLSL pixel shader into shader code to submit to the hardware
	string fullFileName = ShaderFolder + fileName;
	HRESULT hr = 
		D3DXCompileShaderFromFile( fullFileName.c_str(), // File containing pixel shader (HLSL)
			                       NULL, NULL,       // Advanced compilation options - not needed here
								   "main",           // Name of main function in the shader
								   "ps_3_0",         // Target pixel shader hardware - ps_1_1 is lowest level
												     // and will work on all video cards with a pixel shader
								   SHADER_FLAGS,     // Additional compilation flags (such as debug flags)
								   &pShaderCode,     // Ptr to variable to hold compiled shader code
								   NULL,             // Ptr to variable to hold error messages (not needed)
								   constants );      // Ptr to variable to hold constants for the shader
    if (FAILED(hr))
	{
		// Return if compilation failed
		return false;
	}

	// Create the pixel shader using the compiled shader code
    hr = g_pd3dDevice->CreatePixelShader( (DWORD*)pShaderCode->GetBufferPointer(), pixelShader );
    
	// Discard the shader code now the shader has been created 
	pShaderCode->Release();

	// If the creation failed then return (wait until after shader code has been discarded)
    if (FAILED(hr))
	{
		return false;
	}

	return true;
}
Exemple #14
0
static bool load_program(unsigned index, const char *prog, bool path_is_file)
{
   bool ret, ret_fp, ret_vp;
   ID3DXBuffer *listing_f = NULL;
   ID3DXBuffer *listing_v = NULL;
   ID3DXBuffer *code_f = NULL;
   ID3DXBuffer *code_v = NULL;

   ret = true;
   ret_fp = false;
   ret_vp = false;

   if (prg[index].f_ctable)
      prg[index].f_ctable->Release();
   if (prg[index].v_ctable)
      prg[index].v_ctable->Release();

   if (path_is_file)
   {
      ret_fp = D3DXCompileShaderFromFile(prog, NULL, NULL,
            "main_fragment", "ps_3_0", 0, &code_f, &listing_f, &prg[index].f_ctable); 
      ret_vp = D3DXCompileShaderFromFile(prog, NULL, NULL,
            "main_vertex", "vs_3_0", 0, &code_v, &listing_v, &prg[index].v_ctable); 
   }
   else
   {
      /* TODO - crashes currently - to do with 'end of line' of stock shader */
      ret_fp = D3DXCompileShader(prog, (UINT)strlen(prog), NULL, NULL,
            "main_fragment", "ps_3_0", 0, &code_f, &listing_f, &prg[index].f_ctable );
      ret_vp = D3DXCompileShader(prog, (UINT)strlen(prog), NULL, NULL,
            "main_vertex", "vs_3_0", 0, &code_v, &listing_v, &prg[index].v_ctable );
   }

   if (FAILED(ret_fp) || FAILED(ret_vp) || listing_v || listing_f)
   {
      RARCH_ERR("HLSL error:\n");
      if(listing_f)
         RARCH_ERR("Fragment:\n%s\n", (char*)listing_f->GetBufferPointer());
      if(listing_v)
         RARCH_ERR("Vertex:\n%s\n", (char*)listing_v->GetBufferPointer());

      ret = false;
      goto end;
   }

   if (prg[index].fprg)
	   prg[index].fprg->Release();
   if (prg[index].vprg)
	   prg[index].vprg->Release();

   d3d_device_ptr->CreatePixelShader((const DWORD*)code_f->GetBufferPointer(), &prg[index].fprg);
   d3d_device_ptr->CreateVertexShader((const DWORD*)code_v->GetBufferPointer(), &prg[index].vprg);
   code_f->Release();
   code_v->Release();

end:
   if (listing_f)
      listing_f->Release();
   if (listing_v)
      listing_v->Release();
   return ret;
}
Exemple #15
0
int DXApp::run(HINSTANCE hInst, HWND hWnd)
{
    MSG msg;
    HACCEL hAccelTable;
    hAccelTable = LoadAccelerators(hInst, (LPCTSTR)IDC_TESTDXPROJ);
    QueryPerformanceFrequency((LARGE_INTEGER*)&Frequency);


    if(!_p_physdk) return -1;

    NxSceneDesc sceneDesc;
    sceneDesc.gravity.set(0, -9800.f, 0);
    sceneDesc.collisionDetection = true;
    sceneDesc.groundPlane = true;
    _p_scene = _p_physdk->createScene(sceneDesc);
    if(!_p_scene) return -2;

    _time_step = 1.0f/400.0f;
    _p_scene->setTiming(_time_step);

    NxMaterialDesc ParticleMaterialDesc;
    ParticleMaterialDesc.restitution = 0.80f;
    //ParticleMaterialDesc.spinFriction = 0.2f;
    ParticleMaterialDesc.staticFriction = 0.8f;
    ParticleMaterialDesc.dynamicFriction = 0.5f;
    NxMaterial* ParticleMaterial = _p_scene->createMaterial(ParticleMaterialDesc);
    _particle_material = ParticleMaterial->getMaterialIndex();


    D3DPRESENT_PARAMETERS D3DParams;
    D3DParams.Windowed = true;
    D3DParams.BackBufferWidth = width;
    D3DParams.BackBufferHeight = height;
    D3DParams.MultiSampleType = D3DMULTISAMPLE_NONE;
    D3DParams.MultiSampleQuality = 0;
    D3DParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
    D3DParams.Flags = 0;
    D3DParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
    D3DParams.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
    D3DParams.BackBufferFormat = D3DFMT_UNKNOWN;
    D3DParams.BackBufferCount = 3;
    D3DParams.hDeviceWindow = hWnd;
    D3DParams.EnableAutoDepthStencil = true;
    D3DParams.AutoDepthStencilFormat = D3DFMT_D16;

    if(FAILED(_p_D3D->CreateDevice( D3DADAPTER_DEFAULT,
                                    D3DDEVTYPE_HAL,
                                    hWnd,
                                    D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                    &D3DParams,
                                    &_p_device)))
    {
        return -3;
    }

    D3DXCreateFont(_p_device, 12, 0, FW_NORMAL, 1, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH|FF_DONTCARE, "Arial", &FPSFont);

    _p_device->SetFVF(particle_fvf);
    if(FAILED(D3DXCompileShaderFromFile(
                  strPixelShader,
                  NULL,
                  NULL,
                  "ps_main",
                  "ps_2_0",
                  0,
                  &_p_code,
                  NULL,
                  &_p_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Pixel Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreatePixelShader((DWORD*)_p_code->GetBufferPointer(), &_p_shader);
    _p_code->Release();
    _p_code = NULL;

    //SHADOW Buffer Pixel Shaders
    if(FAILED(D3DXCompileShaderFromFile(
                  strShadowPS,
                  NULL,
                  NULL,
                  "ps_main",
                  "ps_2_0",
                  0,
                  &_p_code,
                  NULL,
                  &_p_SB_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Pixel Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreatePixelShader((DWORD*)_p_code->GetBufferPointer(), &_p_SB_shader);
    _p_code->Release();
    _p_code = NULL;

    //SHADOW Buffer Vertex Shaders
    if(FAILED(D3DXCompileShaderFromFile(
                  strShadowVS,
                  NULL,
                  NULL,
                  "vs_main",
                  "vs_2_0",
                  0,
                  &_p_code,
                  NULL,
                  &_p_SB_vertex_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Vertex Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreateVertexShader((DWORD*)_p_code->GetBufferPointer(), &_p_SB_vshader);
    _p_code->Release();
    _p_code = NULL;

    if(FAILED(D3DXCompileShaderFromFile(
                  strCombinerShader,
                  NULL,
                  NULL,
                  "ps_main",
                  "ps_2_b",
                  0,
                  &_p_code,
                  NULL,
                  &_p_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Pixel Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreatePixelShader((DWORD*)_p_code->GetBufferPointer(), &_p_combinershader);
    _p_code->Release();
    _p_code = NULL;

    if(FAILED(D3DXCompileShaderFromFile(
                  strScreenAlignShader,
                  NULL,
                  NULL,
                  "vs_main",
                  "vs_2_0",
                  0,
                  &_p_code,
                  NULL,
                  &_p_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Vertex Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreateVertexShader((DWORD*)_p_code->GetBufferPointer(), &_p_alignshader);
    _p_code->Release();
    _p_code = NULL;

    _p_device->SetFVF(light_fvf);
    if(FAILED(D3DXCompileShaderFromFile(
                  strLightShader,
                  NULL,
                  NULL,
                  "ps_main",
                  "ps_2_0",
                  0,
                  &_p_code,
                  NULL,
                  &_p_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Pixel Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreatePixelShader((DWORD*)_p_code->GetBufferPointer(), &_p_lightshader);
    _p_code->Release();
    _p_code = NULL;

    _p_device->SetFVF(particle_fvf);
    if(FAILED(D3DXCompileShaderFromFile(
                  strVertexShader,
                  NULL,
                  NULL,
                  "vs_main",
                  "vs_2_0",
                  0,
                  &_p_code,
                  NULL,
                  &_p_vertex_constant_able )))
    {
        MessageBox(hWnd, "Error compiling Script", "Vertex Shader Compile Error", MB_ICONERROR);
        return 1;
    }

    _p_device->CreateVertexShader((DWORD*)_p_code->GetBufferPointer(), &_p_vshader);
    _p_code->Release();
    _p_code = NULL;

    hMatProjection = _p_vertex_constant_able->GetConstantByName(NULL, strMatProjection);
    hMatView = _p_vertex_constant_able->GetConstantByName(NULL, strMatView);
    hMatTexture = _p_vertex_constant_able->GetConstantByName(NULL, strMatTexture);
    hMatWorld = _p_vertex_constant_able->GetConstantByName(NULL, strMatWorld);
    hLightPosition = _p_vertex_constant_able->GetConstantByName(NULL, strLightPosition);
    hDeltaPos = _p_vertex_constant_able->GetConstantByName(NULL, strDeltaPos);
    hSBMatProjection = _p_SB_vertex_constant_able->GetConstantByName(NULL, strMatProjection);
    hSBMatWorld = _p_SB_vertex_constant_able->GetConstantByName(NULL, strMatWorld);

    //Setup our particle mesh.
    {
        LPD3DXMESH _tmp_mesh;
        if(FAILED(D3DXLoadMeshFromX(strCubeMesh, D3DXMESH_VB_MANAGED, _p_device, NULL, NULL, NULL, NULL, &_tmp_mesh)))
        {
            MessageBox(hWnd, "Error Loading Cube Model", "Mesh Load Error", MB_ICONERROR);
            return 1;
        }
        _tmp_mesh->CloneMeshFVF(D3DXMESH_VB_MANAGED, particle_fvf, _p_device, &_particle_Mesh);
        _tmp_mesh->Release();
    }

    // We now have _p_physdk, _p_scene, _p_D3D, _p_device initialized

    // Setup the Camera
    CameraAngleX = (D3DX_PI/4)*3;
    CameraAngleY = 0;

    // Light Setup
    DrawLight.location = NxVec3(500, 500, 50);
    DrawLight.point_size = _particle_size;
    DrawLight.diffuse = (((_particle_color & 0xFF000000)>>24))<<24
                        | (((_particle_color & 0x00FF0000)>>16))<<16
                        | (((_particle_color & 0x0000FF00)>>8))<<8
                        | ((_particle_color & 0x000000FF));

    D3DCAPS9 DevCaps;
    _p_device->GetDeviceCaps(&DevCaps);
    if(FAILED(_p_device->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &_screen_buffer, NULL)))
    {
        MessageBox(hWnd, "Error Creating Texture", "Texture Error", MB_ICONERROR);
        return 1;
    }

    if(DevCaps.NumSimultaneousRTs > 1)
    {
        bMotionBlur = true;
        if(FAILED(_p_device->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &_blur_buffer, NULL)))
        {
            MessageBox(hWnd, "Error Creating BLUR Texture", "Texture Error", MB_ICONERROR);
            return 1;
        }
        if(FAILED(_p_device->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &_old_blur_buffer, NULL)))
        {
            MessageBox(hWnd, "Error Creating BLUR Texture", "Texture Error", MB_ICONERROR);
            return 1;
        }
        //_p_device->CreateRenderTarget(width, height, D3DFMT_D32, D3DMULTISAMPLE_NONE , 0, false, &_blur_buffer, NULL);
    }
    else
        bMotionBlur = false;


    if(FAILED(_p_device->CreateTexture(ShadowMapSize, ShadowMapSize, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R32F, D3DPOOL_DEFAULT, &ShadowBuffer, NULL)))
    {
        MessageBox(hWnd, "Error Creating Shadow Buffer", "Texture Error", MB_ICONERROR);
        return 1;
    }


    while(loop_continue)
    {
        Frame();
        if(PeekMessage(&msg, NULL, 0, 0, 1))
        {
            if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }

    return (int) msg.wParam;
}
//
// Framework functions
//
bool Setup()
{
	HRESULT hr = 0;

	//
	// Create geometry.
	//

	Device->CreateVertexBuffer(
		6 * sizeof(MultiTexVertex), 
		D3DUSAGE_WRITEONLY,
		MultiTexVertex::FVF,
		D3DPOOL_MANAGED,
		&QuadVB,
		0);

	MultiTexVertex* v = 0;
	QuadVB->Lock(0, 0, (void**)&v, 0);

	v[0] = MultiTexVertex(-10.0f, -10.0f, 5.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f);
	v[1] = MultiTexVertex(-10.0f,  10.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
	v[2] = MultiTexVertex( 10.0f,  10.0f, 5.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f);

	v[3] = MultiTexVertex(-10.0f, -10.0f, 5.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f);
	v[4] = MultiTexVertex( 10.0f,  10.0f, 5.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f);
	v[5] = MultiTexVertex( 10.0f, -10.0f, 5.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f);

	QuadVB->Unlock();

	//
	// Compile shader
	//

	ID3DXBuffer* shader      = 0;
	ID3DXBuffer* errorBuffer = 0;

	hr = D3DXCompileShaderFromFile(
		"ps_multitex-ps.hlsl",
		0,
		0,
		"Main", // entry point function name
		"ps_2_0",
		//D3DXSHADER_DEBUG, 
		D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY,
		&shader,
		&errorBuffer,
		&MultiTexCT);

	// output any error messages
	if( errorBuffer )
	{
		::MessageBox(0, (char*)errorBuffer->GetBufferPointer(), 0, 0);
		d3d::Release<ID3DXBuffer*>(errorBuffer);
	}

	if(FAILED(hr))
	{
		::MessageBox(0, "D3DXCompileShaderFromFile() - FAILED", 0, 0);
		return false;
	}

	//
	// Create Pixel Shader
	//
	hr = Device->CreatePixelShader(
		(DWORD*)shader->GetBufferPointer(),
		&MultiTexPS);

	if(FAILED(hr))
	{
		::MessageBox(0, "CreateVertexShader - FAILED", 0, 0);
		return false;
	}

	d3d::Release<ID3DXBuffer*>(shader);

	//
	// Load textures.
	//

	D3DXCreateTextureFromFile(Device, "../media/texture/crate.bmp", &BaseTex);
	D3DXCreateTextureFromFile(Device, "../media/texture/spotlight.bmp", &SpotLightTex);
	D3DXCreateTextureFromFile(Device, "../media/texture/text.bmp", &StringTex);

	//
	// Set Projection Matrix
	//

	D3DXMATRIX P;
	D3DXMatrixPerspectiveFovLH(
			&P,	D3DX_PI * 0.25f, 
			(float)Width / (float)Height, 1.0f, 1000.0f);

	Device->SetTransform(D3DTS_PROJECTION, &P);

	//
	// Disable lighting.
	//

	Device->SetRenderState(D3DRS_LIGHTING, false);

	// 
	// Get Handles
	//

	BaseTexHandle      = MultiTexCT->GetConstantByName(0, "BaseTex");
	SpotLightTexHandle = MultiTexCT->GetConstantByName(0, "SpotLightTex");
	StringTexHandle    = MultiTexCT->GetConstantByName(0, "StringTex");

	//
	// Set constant descriptions:
	//

	UINT count;
	
	MultiTexCT->GetConstantDesc(BaseTexHandle,      &BaseTexDesc, &count);
	MultiTexCT->GetConstantDesc(SpotLightTexHandle, &SpotLightTexDesc, &count);
	MultiTexCT->GetConstantDesc(StringTexHandle,    &StringTexDesc, &count);

	MultiTexCT->SetDefaults(Device);

	return true;
}
Exemple #17
0
void main(int argc, char* argv[]) {
	int i, n;
	HRESULT hr;
	LPD3DXBUFFER pCode;
	LPD3DXBUFFER pErr;
	LPD3DXCONSTANTTABLE pTbl;
	char* src_name = "test.hlsl";
	char* cod_name = "test.cod";
	char* prm_name = "test.prm";
	char* profile = "ps_3_0";

	if (argc > 1) {
		src_name = argv[1];
	}
	if (argc > 2) {
		cod_name = argv[2];
	}
	if (argc > 3) {
		prm_name = argv[3];
	}
	if (argc > 4) {
		profile = argv[4];
	}

	hr = D3DXCompileShaderFromFile(src_name, NULL, NULL, "main", profile, D3DXSHADER_PREFER_FLOW_CONTROL, &pCode, &pErr, &pTbl);
	if (D3D_OK == hr) {
		D3DXCONSTANTTABLE_DESC desc;

		pTbl->GetDesc(&desc);
		n = desc.Constants;
		SymTbl* pSym = new SymTbl(2*1024*1024);
		s_tbl.nb_param = 0;

		printf("# const = %d\n", n);
		PARAM_INFO* pInfo = s_tbl.info;
		for (i = 0; i < n; ++i) {
			UINT count = 1;
			D3DXCONSTANT_DESC info[1];
			D3DXHANDLE hConst = pTbl->GetConstant(NULL, i);
			pTbl->GetConstantDesc(hConst, info, &count);
			printf("%s, reg = %d, len = %d\n", info[0].Name, info[0].RegisterIndex, info[0].RegisterCount);

			int sym_id = pSym->Add((char*)info[0].Name);
			pInfo->name = sym_id;
			pInfo->reg = info[0].RegisterIndex;
			pInfo->len = info[0].RegisterCount;
			switch (info[0].Type) {
				case D3DXPT_FLOAT:
					if (info[0].Class == D3DXPC_SCALAR) {
						pInfo->type = E_PARAMTYPE_FLOAT;
					} else {
						pInfo->type = E_PARAMTYPE_FVEC;
					}
					break;
				case D3DXPT_INT:
					if (info[0].Class == D3DXPC_SCALAR) {
						pInfo->type = E_PARAMTYPE_INT;
					} else {
						pInfo->type = E_PARAMTYPE_IVEC;
					}
					break;
				case D3DXPT_BOOL:
					pInfo->type = E_PARAMTYPE_BOOL;
					break;
				case D3DXPT_SAMPLER:
				case D3DXPT_SAMPLER1D:
				case D3DXPT_SAMPLER2D:
				case D3DXPT_SAMPLER3D:
				case D3DXPT_SAMPLERCUBE:
					pInfo->type = E_PARAMTYPE_SMP;
					break;
			}
			++pInfo;
			++s_tbl.nb_param;
		}

		int tbl_size = sizeof(int) + s_tbl.nb_param*sizeof(PARAM_INFO);
		int prm_size = tbl_size + pSym->Length();
		char* pPrm = new char[prm_size];
		memcpy(pPrm, &s_tbl, tbl_size);
		memcpy(pPrm + tbl_size, pSym->Top(), pSym->Length());

		Bin_write(cod_name, pCode->GetBufferPointer(), pCode->GetBufferSize());
		Bin_write(prm_name, pPrm, prm_size);

		delete pSym;

		if (pTbl) {
			pTbl->Release();
		}
	} else {
		if (pErr) {
			char* pErr_msg = (char*)pErr->GetBufferPointer();
			printf("%s", pErr_msg);
		}
	}

	if (pErr) {
		pErr->Release();
	}
}
Exemple #18
0
BOOL RenderMultiTex::Init(UINT width, UINT height, HWND hwnd, BOOL windowed, D3DDEVTYPE devType) {
    HRESULT hr = Render::Init(width, height, hwnd, windowed, devType);
    SGL_FAILED_DO(hr, MYTRACE_DX("Render::Init", hr); return FALSE);

    // Create geometry.

    IDirect3DVertexBuffer9* vb;
    m_D3DDev->CreateVertexBuffer(6 * sizeof(MultiTexVertex), D3DUSAGE_WRITEONLY, MultiTexVertex::FVF, D3DPOOL_MANAGED, &vb, NULL);
    m_QuadVB.Attach(vb);

    MultiTexVertex* v = NULL;
    vb->Lock(0, 0, (void**) &v, 0);

    v[0] = MultiTexVertex(-10.0f, -10.0f, 5.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f);
    v[1] = MultiTexVertex(-10.0f,  10.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
    v[2] = MultiTexVertex( 10.0f,  10.0f, 5.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f);

    v[3] = MultiTexVertex(-10.0f, -10.0f, 5.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f);
    v[4] = MultiTexVertex( 10.0f,  10.0f, 5.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f);
    v[5] = MultiTexVertex( 10.0f, -10.0f, 5.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f);

    vb->Unlock();

    // Compile shader
    ID3DXBuffer* shaderBuf = NULL;
    ID3DXBuffer* errBuf = NULL;

    ID3DXConstantTable* constTbl;
    hr = D3DXCompileShaderFromFile(MultiTexPSFile, NULL, NULL, "Main", "ps_1_1", D3DXSHADER_DEBUG | D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, &shaderBuf, &errBuf, &constTbl);
    // output any error messages
    if (errBuf != NULL) {
        MYTRACEA("D3DXCompileShaderFromFile failed: %s", (char*) errBuf->GetBufferPointer());
        SGL::Release(errBuf);
    }
    SGL_FAILED_DO(hr, MYTRACE_DX("D3DXCompileShaderFromFile", hr); return FALSE);
    m_MultiTexCT.Attach(constTbl);

    // Create Pixel Shader
    IDirect3DPixelShader9* shader;
    hr = m_D3DDev->CreatePixelShader((DWORD*) shaderBuf->GetBufferPointer(), &shader);
    SGL_FAILED_DO(hr, MYTRACE_DX("CreatePixelShader", hr); return FALSE);
    m_MultiTexPS.Attach(shader);

    SGL::Release(shaderBuf);

    // Load textures.

    IDirect3DTexture9* tex;
    D3DXCreateTextureFromFile(m_D3DDev, BaseTexFile, &tex);
    SGL_FAILED_DO(hr, MYTRACE_DX("D3DXCreateTextureFromFile", hr); return FALSE);
    m_BaseTex.Attach(tex);

    D3DXCreateTextureFromFile(m_D3DDev, SpotLightTexFile, &tex);
    SGL_FAILED_DO(hr, MYTRACE_DX("D3DXCreateTextureFromFile", hr); return FALSE);
    m_SpotLightTex.Attach(tex);

    D3DXCreateTextureFromFile(m_D3DDev, StringTexFile, &tex);
    SGL_FAILED_DO(hr, MYTRACE_DX("D3DXCreateTextureFromFile", hr); return FALSE);
    m_StringTex.Attach(tex);

    // Set Projection Matrix
    D3DXMATRIX P;
    D3DXMatrixPerspectiveFovLH(&P, D3DX_PI * 0.25f, (float) width / (float) height, 1.0f, 1000.0f);
    m_D3DDev->SetTransform(D3DTS_PROJECTION, &P);

    // Disable lighting.
    m_D3DDev->SetRenderState(D3DRS_LIGHTING, FALSE);

    // Get Handles
    m_BaseTexHandle      = constTbl->GetConstantByName(NULL, "BaseTex");
    m_SpotLightTexHandle = constTbl->GetConstantByName(NULL, "SpotLightTex");
    m_StringTexHandle    = constTbl->GetConstantByName(NULL, "StringTex");

    // Set constant descriptions:
    UINT count;
    constTbl->GetConstantDesc(m_BaseTexHandle, &m_BaseTexDesc, &count);
    constTbl->GetConstantDesc(m_SpotLightTexHandle, &m_SpotLightTexDesc, &count);
    constTbl->GetConstantDesc(m_StringTexHandle, &m_StringTexDesc, &count);
    constTbl->SetDefaults(m_D3DDev);

    if (!InitFont())
        return FALSE;

    return TRUE;
}
Exemple #19
0
//--------------------------------------------------------------------------------------
//  CreateResources( )
//
//      DESC:
//          This function creates the necessary texture chain for downsampling the
//          initial HDR texture to a 1x1 luminance texture.
//
//      PARAMS:
//          pDevice      : The current device that resources should be created with/from
//          pDisplayDesc : Describes the back-buffer currently in use, can be useful when
//                         creating GUI based resources.
//
//      NOTES:
//          n/a
//--------------------------------------------------------------------------------------
HRESULT CreateResources( IDirect3DDevice9* pDevice, const D3DSURFACE_DESC* pDisplayDesc )
{

    //[ 0 ] DECLARATIONS
    //------------------
    HRESULT hr = S_OK;
    LPD3DXBUFFER pCode;      // Container for the compiled HLSL code



    //[ 1 ] DETERMINE FP TEXTURE SUPPORT
    //----------------------------------
    V( HDREnumeration::FindBestLuminanceFormat( &Luminance::g_fmtHDR ) );
    if( FAILED( hr ) )
    {
        // Bad news!
        OutputDebugString( L"Luminance::CreateResources() - Current hardware does not support HDR rendering!\n" );
        return hr;
    }



    //[ 2 ] CREATE HDR RENDER TARGETS
    //-------------------------------
    int iTextureSize = 1;
    for( int i = 0; i < Luminance::g_dwLumTextures; i++ )
    {

        // Create this element in the array
        V( pDevice->CreateTexture( iTextureSize, iTextureSize, 1,
                                   D3DUSAGE_RENDERTARGET, Luminance::g_fmtHDR,
                                   D3DPOOL_DEFAULT, &Luminance::g_pTexLuminance[i], NULL ) );
        if( FAILED( hr ) )
        {
            // Couldn't create this texture, probably best to inspect the debug runtime
            // for more information
            WCHAR str[MAX_PATH];
            swprintf_s( str, MAX_PATH, L"Luminance::CreateResources() : Unable to create luminance"
                             L" texture of %dx%d (Element %d of %d).\n",
                             iTextureSize,
                             iTextureSize,
                             ( i + 1 ),
                             Luminance::g_dwLumTextures );
            OutputDebugString( str );
            return hr;
        }

        // Increment for the next texture
        iTextureSize *= 3;

    }



    //[ 3 ] CREATE GUI DISPLAY SHADER
    //-------------------------------
    // Because the intermediary luminance textures are stored as either G32R32F
    // or G16R16F, we need a pixel shader that can convert this to a more meaningful
    // greyscale ARGB value. This shader doesn't actually contribute to the
    // luminance calculations - just the way they are presented to the user via the GUI.
    WCHAR str[MAX_PATH];
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\Luminance.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "LuminanceDisplay",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       NULL
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString(
            L"Luminance::CreateResources() - Compiling of 'LuminanceDisplay' from 'Luminance.psh' failed!\n" );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ),
                                   &Luminance::g_pLumDispPS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString(
            L"Luminance::CreateResources() - Could not create a pixel shader object for 'LuminanceDisplay'.\n" );
        pCode->Release();
        return hr;

    }

    pCode->Release();



    //[ 4 ] CREATE FIRST-PASS DOWNSAMPLE SHADER
    //-----------------------------------------
    // The first pass of down-sampling has to convert the RGB data to
    // a single luminance value before averaging over the kernel. This
    // is slightly different to the subsequent down-sampling shader.
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\Luminance.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "GreyScaleDownSample",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       &Luminance::g_pLum1PSConsts
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString(
            L"Luminance::CreateResources() - Compiling of 'GreyScaleDownSample' from 'Luminance.psh' failed!\n" );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ), &Luminance::g_pLum1PS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString(
            L"Luminance::CreateResources() - Could not create a pixel shader object for 'GreyScaleDownSample'.\n" );
        pCode->Release();
        return hr;

    }

    pCode->Release();



    //[ 5 ] CREATE DOWNSAMPLING PIXEL SHADER
    //--------------------------------------
    // This down-sampling shader assumes that the incoming pixels are
    // already in G16R16F or G32R32F format, and of a paired luminance/maximum value.
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\Luminance.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "DownSample",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       &Luminance::g_pLum3x3DSPSConsts
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString( L"Luminance::CreateResources() - Compiling of 'DownSample' from 'Luminance.psh' failed!\n"
                           );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ),
                                   &Luminance::g_pLum3x3DSPS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString( L"Luminance::CreateResources() : Could not create a pixel shader object for 'DownSample'.\n"
                           );
        pCode->Release();
        return hr;

    }

    pCode->Release();


    return hr;

}
Exemple #20
0
//
// Framework functions
//
bool Setup()
{
	HRESULT hr = 0;

	//
	// Create geometry.
	//

	D3DXCreateTeapot(Device, &Teapot, 0);

	//
	// Compile shader.
	//

	ID3DXBuffer* shader      = 0;
	ID3DXBuffer* errorBuffer = 0;

	hr = D3DXCompileShaderFromFile(
		"transform.txt",
		0,
		0,
		"Main",  // entry point function name
		"vs_1_1",// shader version to compile to
		D3DXSHADER_DEBUG, 
		&shader,
		&errorBuffer,
		&TransformConstantTable);

	// output any error messages
	if( errorBuffer )
	{
		::MessageBox(0, (char*)errorBuffer->GetBufferPointer(), 0, 0);
		d3d::Release<ID3DXBuffer*>(errorBuffer);
	}

	if(FAILED(hr))
	{
		::MessageBox(0, "D3DXCreateEffectFromFile() - FAILED", 0, 0);
		return false;
	}

	hr = Device->CreateVertexShader(
		(DWORD*)shader->GetBufferPointer(),
		&TransformShader);

	if(FAILED(hr))
	{
		::MessageBox(0, "CreateVertexShader - FAILED", 0, 0);
		return false;
	}

	d3d::Release<ID3DXBuffer*>(shader);

	// 
	// Get Handles.
	//

	TransformViewProjHandle = TransformConstantTable->GetConstantByName(0, "ViewProjMatrix");

	//
	// Set shader constants:
	//

	TransformConstantTable->SetDefaults(Device);
 
	//
	// Set Projection Matrix.
	//

	D3DXMatrixPerspectiveFovLH(
			&ProjMatrix, D3DX_PI * 0.25f, 
			(float)Width / (float)Height, 1.0f, 1000.0f);

	//
	// Set Misc. States.
	//

	Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);

	return true;
}
// 进入循环之前的设置
bool SetUp()
{
	HRESULT hr = 0;

	hr = D3DXCreateTeapot(g_pDevice, &g_ppMesh[0], NULL);
	if (FAILED(hr))
		return false;
	hr = D3DXCreateSphere(g_pDevice, 1.0f, 20, 20, &g_ppMesh[1], NULL);
	if (FAILED(hr))
		return false;
	hr = D3DXCreateTorus(g_pDevice, 0.5f, 1.0f, 20, 20, &g_ppMesh[2], NULL);
	if (FAILED(hr))
		return false;
	hr = D3DXCreateCylinder(g_pDevice, 0.5f, 1.0f, 2.0f, 20, 20, &g_ppMesh[3], NULL);
	if (FAILED(hr))
		return false;

	D3DXMatrixTranslation(&g_WorldMatrix[0], 0.0f, 2.0f, 0.0f);
	D3DXMatrixTranslation(&g_WorldMatrix[1], 0.0f, -2.0f, 0.0f);
	D3DXMatrixTranslation(&g_WorldMatrix[2], -3.0f, 0.0f, 0.0f);
	D3DXMatrixTranslation(&g_WorldMatrix[3], 3.0f, 0.0f, 0.0f);

	g_Color[0] = D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f);
	g_Color[1] = D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f);
	g_Color[2] = D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f);
	g_Color[3] = D3DXVECTOR4(1.0f, 1.0f, 0.0f, 1.0f);


	if (!d3d9::CheckShaderVersion(g_pDevice))
	{
		MessageBox(0, "Shader version can not support!", 0, 0);
		return false;
	}
	
	ID3DXBuffer *pShaderCache;
	ID3DXBuffer *pErrorMsg;
	hr = D3DXCompileShaderFromFile(
		"Toon.txt",
		NULL,
		NULL,
		"Main",
		"vs_1_1",
		D3DXSHADER_DEBUG,
		&pShaderCache,
		&pErrorMsg,
		&g_pConstTable
		);
	if (pErrorMsg)
	{
		MessageBox(0, (char*)pErrorMsg->GetBufferPointer(), 0, 0);
		d3d9::Release(pErrorMsg);
		return false;
	}
	d3d9::Release(pErrorMsg);

	if (!g_pConstTable)
	{
		MessageBox(0, "Const table is NULL!", 0, 0);
		return false;
	}

	if (FAILED(hr))
	{
		MessageBox(0, "Failed to compile shader from file!", 0, 0);
		return false;
	}

	hr = g_pDevice->CreateVertexShader((DWORD*)pShaderCache->GetBufferPointer(), &g_pVertexShader);

	if (FAILED(hr))
	{
		MessageBox(0, "Failed to create vertex shader!", 0, 0);
		d3d9::Release(pShaderCache);
		return false;
	}
	d3d9::Release(pShaderCache);

	hr = D3DXCreateTextureFromFile(g_pDevice, "toonshade.bmp", &g_pShadeTex);
	if (FAILED(hr))
	{
		MessageBox(0, "Failed to create texture from file!", 0, 0);
		return false;
	}

	g_pDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
	g_pDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
	g_pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);

	g_hWorldViewMatrix = g_pConstTable->GetConstantByName(NULL, "WorldViewMatrix");
	if (!g_hWorldViewMatrix)
	{
		MessageBox(0, "Get WorldViewMatrix failed!", 0, 0);
		return false;
	}

	g_hWorldViewProjMatrix = g_pConstTable->GetConstantByName(NULL, "WorldViewProjMatrix");
	if (!g_hWorldViewProjMatrix)
	{
		MessageBox(0, "Get WorldViewProjMatrix failed!", 0, 0);
		return false;
	}

	g_hColor = g_pConstTable->GetConstantByName(NULL, "Color");
	if (!g_hColor)
	{
		MessageBox(0, "Get Color failed!", 0, 0);
		return false;
	}

	g_hLightDir = g_pConstTable->GetConstantByName(NULL, "DirToLight");
	if (!g_hLightDir)
	{
		MessageBox(0, "Get DirToLight failed!", 0, 0);
		return false;
	}
	g_pConstTable->SetDefaults(g_pDevice);

	D3DXVECTOR4 dirtolight(-0.57f, 0.57f, -0.57f, 0.0f);
	g_pConstTable->SetVector(g_pDevice, g_hLightDir, &dirtolight);


	// 竖直视角,宽/高比,近裁剪面,远裁剪面
	D3DXMatrixPerspectiveFovLH(&g_ProjMatrix, D3DX_PI*0.25f, (float)Width / (float)Height, 1.0f, 100.0f);

	return true;
}
Exemple #22
0
//--------------------------------------------------------------------------------------
//  CreateResources( )
//
//      DESC:
//          This function creates all the necessary resources to produce the post-
//          processing effect for the HDR input. When this function completes successfully
//          rendering can commence. A call to 'DestroyResources()' should be made when
//          the application closes.
//
//      PARAMS:
//          pDevice      : The current device that resources should be created with/from
//          pDisplayDesc : Describes the back-buffer currently in use, can be useful when
//                         creating GUI based resources.
//
//      NOTES:
//          n/a
//--------------------------------------------------------------------------------------
HRESULT CreateResources( IDirect3DDevice9* pDevice, const D3DSURFACE_DESC* pDisplayDesc )
{

    // [ 0 ] GATHER NECESSARY INFORMATION
    //-----------------------------------
    HRESULT hr = S_OK;
    LPD3DXBUFFER pCode = NULL;

    V( HDREnumeration::FindBestHDRFormat( &PostProcess::g_fmtHDR ) );
    if( FAILED( hr ) )
    {
        // High Dynamic Range Rendering is not supported on this device!
        OutputDebugString( L"PostProcess::CreateResources() - Current hardware does not allow HDR rendering!\n" );
        return hr;
    }



    // [ 1 ] CREATE BRIGHT PASS TEXTURE
    //---------------------------------
    // Bright pass texture is 1/2 the size of the original HDR render target.
    // Part of the pixel shader performs a 2x2 downsampling. The downsampling
    // is intended to reduce the number of pixels that need to be worked on - 
    // in general, HDR pipelines tend to be fill-rate heavy.
    V( pDevice->CreateTexture(
       pDisplayDesc->Width / 2, pDisplayDesc->Height / 2,
       1, D3DUSAGE_RENDERTARGET, PostProcess::g_fmtHDR,
       D3DPOOL_DEFAULT, &PostProcess::g_pBrightPassTex, NULL
       ) );
    if( FAILED( hr ) )
    {

        // We couldn't create the texture - lots of possible reasons for this...
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create bright-pass render target. Examine D3D Debug Output for details.\n" );
        return hr;

    }


    // [ 2 ] CREATE BRIGHT PASS PIXEL SHADER
    //--------------------------------------
    WCHAR str[MAX_PATH];
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\PostProcessing.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "BrightPass",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       &PostProcess::g_pBrightPassConstants
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString(
            L"PostProcess::CreateResources() - Compiling of 'BrightPass' from 'PostProcessing.psh' failed!\n" );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ),
                                   &PostProcess::g_pBrightPassPS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create a pixel shader object for 'BrightPass'.\n" );
        pCode->Release();
        return hr;

    }

    pCode->Release();



    // [ 3 ] CREATE DOWNSAMPLED TEXTURE
    //---------------------------------
    // This render target is 1/8th the size of the original HDR image (or, more
    // importantly, 1/4 the size of the bright-pass). The downsampling pixel
    // shader performs a 4x4 downsample in order to reduce the number of pixels
    // that are sent to the horizontal/vertical blurring stages.
    V( pDevice->CreateTexture(
       pDisplayDesc->Width / 8, pDisplayDesc->Height / 8,
       1, D3DUSAGE_RENDERTARGET, PostProcess::g_fmtHDR,
       D3DPOOL_DEFAULT, &PostProcess::g_pDownSampledTex, NULL
       ) );
    if( FAILED( hr ) )
    {

        // We couldn't create the texture - lots of possible reasons for this...
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create downsampling render target. Examine D3D Debug Output for details.\n" );
        return hr;

    }


    // [ 3 ] CREATE DOWNSAMPLING PIXEL SHADER
    //---------------------------------------
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\PostProcessing.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "DownSample",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       &PostProcess::g_pDownSampleConstants
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString(
            L"PostProcess::CreateResources() - Compiling of 'DownSample' from 'PostProcessing.psh' failed!\n" );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ),
                                   &PostProcess::g_pDownSamplePS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create a pixel shader object for 'DownSample'.\n" );
        pCode->Release();
        return hr;

    }

    pCode->Release();



    // [ 4 ] CREATE HORIZONTAL BLOOM TEXTURE
    //--------------------------------------
    // The horizontal bloom texture is the same dimension as the down sample
    // render target. Combining a 4x4 downsample operation as well as a
    // horizontal blur leads to a prohibitively high number of texture reads.
    V( pDevice->CreateTexture(
       pDisplayDesc->Width / 8, pDisplayDesc->Height / 8,
       1, D3DUSAGE_RENDERTARGET, PostProcess::g_fmtHDR,
       D3DPOOL_DEFAULT, &PostProcess::g_pBloomHorizontal, NULL
       ) );
    if( FAILED( hr ) )
    {

        // We couldn't create the texture - lots of possible reasons for this...
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create horizontal bloom render target. Examine D3D Debug Output for details.\n" );
        return hr;

    }

    // [ 5 ] CREATE HORIZONTAL BLOOM PIXEL SHADER
    //-------------------------------------------
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\PostProcessing.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "HorizontalBlur",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       &PostProcess::g_pHBloomConstants
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString(
            L"PostProcess::CreateResources() - Compiling of 'HorizontalBlur' from 'PostProcessing.psh' failed!\n" );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ),
                                   &PostProcess::g_pHBloomPS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create a pixel shader object for 'HorizontalBlur'.\n" );
        pCode->Release();
        return hr;

    }

    pCode->Release();

    // [ 6 ] CREATE VERTICAL BLOOM TEXTURE
    //------------------------------------
    // The vertical blur texture must be the same size as the horizontal blur texture
    // so as to get a correct 2D distribution pattern.
    V( pDevice->CreateTexture(
       pDisplayDesc->Width / 8, pDisplayDesc->Height / 8,
       1, D3DUSAGE_RENDERTARGET, PostProcess::g_fmtHDR,
       D3DPOOL_DEFAULT, &PostProcess::g_pBloomVertical, NULL
       ) );
    if( FAILED( hr ) )
    {

        // We couldn't create the texture - lots of possible reasons for this...
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create vertical bloom render target. Examine D3D Debug Output for details.\n" );
        return hr;

    }


    // [ 7 ] CREATE VERTICAL BLOOM PIXEL SHADER
    //-----------------------------------------
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Shader Code\\PostProcessing.psh" ) );
    V( D3DXCompileShaderFromFile(
       str,
       NULL, NULL,
       "VerticalBlur",
       "ps_2_0",
       0,
       &pCode,
       NULL,
       &PostProcess::g_pVBloomConstants
       ) );
    if( FAILED( hr ) )
    {

        // Couldn't compile the shader, use the 'compile_shaders.bat' script
        // in the 'Shader Code' folder to get a proper compile breakdown.
        OutputDebugString(
            L"PostProcess::CreateResources() - Compiling of 'VerticalBlur' from 'PostProcessing.psh' failed!\n" );
        return hr;

    }

    V( pDevice->CreatePixelShader( reinterpret_cast< DWORD* >( pCode->GetBufferPointer() ),
                                   &PostProcess::g_pVBloomPS ) );
    if( FAILED( hr ) )
    {

        // Couldn't turn the compiled shader into an actual, usable, pixel shader!
        OutputDebugString(
            L"PostProcess::CreateResources() - Could not create a pixel shader object for 'VerticalBlur'.\n" );
        pCode->Release();
        return hr;

    }

    pCode->Release();

    return hr;

}
void D3D9VertexShader::Reset(LPDIRECT3DDEVICE9 Device)
{
    FreeMemory();

    HRESULT hr;

    _Device = Device;
    Assert(Device != NULL, "Device == NULL");

    _Decl.Init(Device);

    // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the 
    // shader debugger. Debugging vertex shaders requires either REF or software vertex 
    // processing, and debugging pixel shaders requires REF.  The 
    // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the 
    // shader debugger.  It enables source level debugging, prevents instruction 
    // reordering, prevents dead code elimination, and forces the compiler to compile 
    // against the next higher available software target, which ensures that the 
    // unoptimized shaders do not exceed the shader model limitations.  Setting these 
    // flags will cause slower rendering since the shaders will be unoptimized and 
    // forced into software.  See the DirectX documentation for more information about 
    // using the shader debugger.
    DWORD dwShaderFlags = 0;
    #ifdef DEBUG_VS
        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG;
    #endif

    LPD3DXBUFFER pCode = NULL;
    LPD3DXBUFFER pErrors = NULL;

    PersistentAssert(Utility::FileExists(_ShaderFile), String(_ShaderFile) + String(" not found."));

    // Assemble the vertex shader from the file
    hr = D3DXCompileShaderFromFile( _ShaderFile.CString(), NULL, NULL, "VShaderEntry",
                                    "vs_3_0", dwShaderFlags, &pCode,
                                    &pErrors, &_ConstantTable );
    
    if(pErrors)
    {
        char *ErrorMessage = (char *)pErrors->GetBufferPointer();
        DWORD ErrorLength = pErrors->GetBufferSize();

        ofstream file("ShaderDebug.txt");
        for(UINT i = 0; i < ErrorLength; i++)
        {
            file << ErrorMessage[i];
        }
        file.close();
    }

    Assert(!FAILED(hr), "D3DXCompileShaderFromFile failed.  See ShaderDebug.txt for details.");

    // Create the vertex shader
    hr = Device->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(),
                                            &_Shader );

    if(pErrors)
    {
        pErrors->Release();
    }
    if(pCode)
    {
        pCode->Release();
    }
    Assert(!FAILED(hr), "CreateVertexShader failed");
}
Exemple #24
0
//=============================================================================
// 初期化
//=============================================================================
HRESULT CMeshField::Init(LPDIRECT3DDEVICE9 pDevice,int nType, D3DXVECTOR3 pos, D3DXVECTOR3 rot,
								int nNumBlockX, int nNumBlockZ, float fSizeBlockX, float fSizeBlockZ)
{
	m_pDevice=pDevice;

	// ブロック数の設定
	m_nNumBlockX = nNumBlockX;
	m_nNumBlockZ = nNumBlockZ;

	// 頂点数の設定
	m_nNumVertex = (nNumBlockX + 1) * (nNumBlockZ + 1);

	// インデックス数の設定
	m_nNumVertexIndex = (nNumBlockX + 1) * 2 * nNumBlockZ + (nNumBlockZ - 1) * 2;

	// ポリゴン数の設定
	m_nNumPolygon = nNumBlockX * nNumBlockZ * 2 + (nNumBlockZ - 1) * 4;

	// ブロックサイズの設定
	m_fSizeBlockX = fSizeBlockX;
	m_fSizeBlockZ = fSizeBlockZ;

	// テクスチャの読み込み
	m_texid = m_apTexture[nType];
	//D3DXCreateTextureFromFile(m_pDevice,m_apTextureName[nType],&m_pD3DTex);

	//フィールドの初期化
	m_Pos = pos;
	m_Rot = rot;
	m_Scl = D3DXVECTOR3(1.0f,1.0f,1.0f);

	// オブジェクトの頂点バッファを生成
	if(FAILED(m_pDevice->CreateVertexBuffer(sizeof(VERTEX_3D)*m_nNumVertex,
											D3DUSAGE_WRITEONLY,
											FVF_VERTEX_3D,
											D3DPOOL_MANAGED,
											&m_pD3DVtxBuff,
											NULL)))
	{
		return E_FAIL;
	}

	// オブジェクトのインデックスバッファを生成
	if(FAILED(m_pDevice->CreateIndexBuffer(sizeof(WORD)*m_nNumVertexIndex,
											D3DUSAGE_WRITEONLY,
											D3DFMT_INDEX16,
											D3DPOOL_MANAGED,
											&m_pD3DIndexBuff,
											NULL)))
	{
		return E_FAIL;
	}

	// 法線算出用バッファ確保
	m_pBuffNormal = new D3DXVECTOR3 [(m_nNumBlockX * 2) * m_nNumBlockZ];

	{//頂点バッファの中身を埋める
		VERTEX_3D *pVtx;
		const float texSizeX = 1.0f;
		const float texSizeZ = 1.0f;

		// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DVtxBuff->Lock(0, 0, (void**)&pVtx, 0);

		for(int nCntVtxZ = 0; nCntVtxZ < (m_nNumBlockZ + 1); nCntVtxZ++)
		{
			for(int nCntVtxX = 0; nCntVtxX < (m_nNumBlockX + 1); nCntVtxX++)
			{
				// 頂点座標の設定
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx.x = -(m_nNumBlockX / 2.0f) * m_fSizeBlockX + nCntVtxX * m_fSizeBlockX;
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx.z = (m_nNumBlockZ / 2.0f) * m_fSizeBlockZ - nCntVtxZ * m_fSizeBlockZ;

				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx.y = HIGHT_MAP[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX];

				// 反射光の設定
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);

				// テクスチャ座標の設定
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].tex.x = texSizeX * nCntVtxX;
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].tex.y = texSizeZ * nCntVtxZ;
			}
		}

		// 頂点データをアンロックする
		m_pD3DVtxBuff->Unlock();
	}

	{// 法線の算出
		VERTEX_3D *pVtx;

		// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DVtxBuff->Lock(0, 0, (void**)&pVtx, 0);

		D3DXVECTOR3 *pNor = m_pBuffNormal;
		for(int nCntVtxZ = 0; nCntVtxZ < m_nNumBlockZ; nCntVtxZ++)
		{
			for(int nCntVtxX = 0; nCntVtxX < m_nNumBlockX; nCntVtxX++)
			{
				// 法線の設定
				D3DXVECTOR3 v0,v1,v2;
				D3DXVECTOR3 normal;
				D3DXVECTOR3 *pVtx0,*pVtx1,*pVtx2;

				pVtx0 = &pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx;
				pVtx1 = &pVtx[(nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX].vtx;
				pVtx2 = &pVtx[(nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX + 1].vtx;

				v0.x = pVtx1->x - pVtx2->x;
				v0.y = pVtx1->y - pVtx2->y;
				v0.z = pVtx1->z - pVtx2->z;
				v1.x = pVtx0->x - pVtx2->x;
				v1.y = pVtx0->y - pVtx2->y;
				v1.z = pVtx0->z - pVtx2->z;

				D3DXVec3Cross(&v2, &v0, &v1);
				D3DXVec3Normalize(&normal, &v2);

				*pNor = normal;
				pNor++;

				pVtx0 = &pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].vtx;
				pVtx1 = &pVtx[(nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX + 1].vtx;
				pVtx2 = &pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX + 1].vtx;

				v0.x = pVtx1->x - pVtx2->x;
				v0.y = pVtx1->y - pVtx2->y;
				v0.z = pVtx1->z - pVtx2->z;
				v1.x = pVtx0->x - pVtx2->x;
				v1.y = pVtx0->y - pVtx2->y;
				v1.z = pVtx0->z - pVtx2->z;
				D3DXVec3Cross(&v2, &v0, &v1);
				D3DXVec3Normalize(&normal, &v2);

				*pNor = normal;
				pNor++;
			}
		}

		// 頂点データをアンロックする
		m_pD3DVtxBuff->Unlock();
	}

	{//頂点バッファの中身を埋める
		VERTEX_3D *pVtx;

		// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DVtxBuff->Lock(0, 0, (void**)&pVtx, 0);

		D3DXVECTOR3 *pNor = m_pBuffNormal;
		for(int nCntVtxZ = 0; nCntVtxZ < (m_nNumBlockZ + 1); nCntVtxZ++)
		{
			for(int nCntVtxX = 0; nCntVtxX < (m_nNumBlockX + 1); nCntVtxX++)
			{
				// 法線の設定
				D3DXVECTOR3 normal;
				D3DXVECTOR3 norAvg0, norAvg1;

				if(nCntVtxZ == 0)
				{
					if(nCntVtxX == 0)
					{
						normal = (pNor[0] + pNor[1]) / 2;
					}
					else if(nCntVtxX == m_nNumBlockX)
					{
						normal = pNor[m_nNumBlockX * 2 - 1];
					}
					else
					{
						norAvg0 = (pNor[nCntVtxX * 2] + pNor[nCntVtxX * 2 + 1]) / 2;
						normal = (pNor[nCntVtxX * 2 - 1] + norAvg0) / 2;
					}
				}
				else if(nCntVtxZ == m_nNumBlockZ)
				{
					if(nCntVtxX == 0)
					{
						normal = pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2];
					}
					else if(nCntVtxX == m_nNumBlockX)
					{
						normal = (pNor[m_nNumBlockZ * m_nNumBlockX * 2 - 2] + pNor[m_nNumBlockZ * m_nNumBlockX * 2 - 1]) / 2;
					}
					else
					{
						norAvg0 = (pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 2] + pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 1]) / 2;
						normal = (norAvg0 + pNor[(m_nNumBlockZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2]) / 2;
					}
				}
				else
				{
					if(nCntVtxX == 0)
					{
						norAvg0 = (pNor[nCntVtxZ * m_nNumBlockX * 2] + pNor[nCntVtxZ * m_nNumBlockX * 2 + 1]) / 2;
						normal = (pNor[(nCntVtxZ - 1) * m_nNumBlockX * 2] + norAvg0) / 2;
					}
					else if(nCntVtxX == m_nNumBlockX)
					{
						norAvg0 = (pNor[(nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 1] + pNor[(nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 2]) / 2;
						normal = (norAvg0 + pNor[nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2 - 1]) / 2;
					}
					else
					{
						int nIdx0 = (nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 2;
						int nIdx1 = (nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2 - 1;
						int nIdx2 = (nCntVtxZ - 1) * m_nNumBlockX * 2 + nCntVtxX * 2;
						int nIdx3 = nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2 - 1;
						int nIdx4 = nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2;
						int nIdx5 = nCntVtxZ * m_nNumBlockX * 2 + nCntVtxX * 2 + 1;

						norAvg0 = (pNor[nIdx0] + pNor[nIdx1]) / 2;
						norAvg1 = (pNor[nIdx4] + pNor[nIdx5]) / 2;
						normal = (norAvg0 + pNor[nIdx2] + pNor[nIdx3] + norAvg1) / 4;
					}
				}

				D3DXVec3Normalize(&normal, &normal);
				pVtx[nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX].nor = normal;
			}
		}

		// 頂点データをアンロックする
		m_pD3DVtxBuff->Unlock();
	}

	{//インデックスバッファの中身を埋める
		WORD *pIdx;

		// インデックスデータの範囲をロックし、頂点バッファへのポインタを取得
		m_pD3DIndexBuff->Lock(0, 0, (void**)&pIdx, 0);

		int nCntIdx = 0;
		for(int nCntVtxZ = 0; nCntVtxZ < m_nNumBlockZ; nCntVtxZ++)
		{
			if(nCntVtxZ > 0)
			{// 縮退ポリゴンのためのダブりの設定
				pIdx[nCntIdx] = (nCntVtxZ + 1) * (m_nNumBlockX + 1) + 0;
				nCntIdx++;
			}

			for(int nCntVtxX = 0; nCntVtxX < (m_nNumBlockX + 1); nCntVtxX++)
			{
				pIdx[nCntIdx] = (nCntVtxZ + 1) * (m_nNumBlockX + 1) + nCntVtxX;
				nCntIdx++;
				pIdx[nCntIdx] = nCntVtxZ * (m_nNumBlockX + 1) + nCntVtxX;
				nCntIdx++;
			}

			if(nCntVtxZ < (m_nNumBlockZ - 1))
			{// 縮退ポリゴンのためのダブりの設定
				pIdx[nCntIdx] = nCntVtxZ * (m_nNumBlockX + 1) + m_nNumBlockX;
				nCntIdx++;
			}
		}

		// インデックスデータをアンロックする
		m_pD3DIndexBuff->Unlock();
	}

	HRESULT hr;
	LPD3DXBUFFER err;
	LPD3DXBUFFER code;

	//ピクセルシェーダー用に変換
	hr = D3DXCompileShaderFromFile("source/shader/basicPS.hlsl", NULL, NULL, "PS_SHADOW", "ps_2_0", 0, &code, &err, &_psc);

	if (FAILED(hr))
	{
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), "D3DXCompileShaderFromFile", MB_OK);
		err->Release();
		return false;
	}
	//シェーダーの登録
	hr = pDevice->CreatePixelShader((DWORD*)code->GetBufferPointer(), &_ps);

	if (FAILED(hr))
	{
		MessageBox(NULL, "FAILED", "CreatePixelShader", MB_OK);
		return false;
	}

	//バーテックスシェーダー用に変換1
	hr = D3DXCompileShaderFromFile("source/shader/basicVS.hlsl", NULL, NULL, "VS_SHADOW", "vs_2_0", 0, &code, &err, &_vsc[0]);
	if (FAILED(hr))
	{
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), "D3DXCompileShaderFromFile", MB_OK);
		err->Release();
		return false;
	}
	//シェーダーの登録
	hr = pDevice->CreateVertexShader((DWORD*)code->GetBufferPointer(), &_vs[0]);
	if (FAILED(hr))
	{
		MessageBox(NULL, "FAILED", "CreateVertexShader", MB_OK);
		return false;
	}

	//バーテックスシェーダー用に変換1
	hr = D3DXCompileShaderFromFile("source/shader/basicVS.hlsl", NULL, NULL, "VS", "vs_2_0", 0, &code, &err, &_vsc[1]);
	if (FAILED(hr))
	{
		MessageBox(NULL, (LPCSTR)err->GetBufferPointer(), "D3DXCompileShaderFromFile", MB_OK);
		err->Release();
		return false;
	}
	//シェーダーの登録
	hr = pDevice->CreateVertexShader((DWORD*)code->GetBufferPointer(), &_vs[1]);
	if (FAILED(hr))
	{
		MessageBox(NULL, "FAILED", "CreateVertexShader", MB_OK);
		return false;
	}

	// マテリアルの設定
	m_material.Ambient = D3DXCOLOR(0.25f, 0.25f, 0.25f, 1.0f);
	m_material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
	m_material.Emissive = D3DXCOLOR(0, 0, 0, 0);
	m_material.Specular = D3DXCOLOR(0, 0, 0, 0);
	m_material.Power = 2.0f;

	return S_OK;
}
Exemple #25
0
void* LcD3D_BuildHLSLFromFile(PDEV pDev, char* sStrFile, char* sFunction, char* sShader, PDCT* pTbl/*Out*/)
{
	HRESULT	hr;

	DWORD dFlag = 0;
	#if defined( _DEBUG ) || defined( DEBUG )
	dFlag |= D3DXSHADER_DEBUG;
	#endif

	LPD3DXBUFFER	pAsm = NULL;
	LPD3DXBUFFER	pErr = NULL;
	void*			pShd = NULL;

	hr = D3DXCompileShaderFromFile(
			sStrFile
		,	NULL
		,	NULL
		,	sFunction
		,	sShader
		,	dFlag
		,	&pAsm
		,	&pErr
		,	pTbl);


	if( FAILED(hr) )
	{
		if(pErr)
		{
			char* sErr = (char*)pErr->GetBufferPointer();
			LcD3D_GetDxError(hr, sErr);
			pErr->Release();
		}
		else
			LcD3D_GetDxError(hr);

		return NULL;
	}

	if( 0 == _strnicmp(sShader, "vs", 2))
	{
		PDVS pVS = NULL;
		hr = pDev->CreateVertexShader( (DWORD*)pAsm->GetBufferPointer() , &pVS);
		pShd = pVS;
	}

	else if( 0 == _strnicmp(sShader, "ps", 2))
	{
		PDPS pPS	= NULL;
		hr = pDev->CreatePixelShader( (DWORD*)pAsm->GetBufferPointer() , &pPS);
		pShd = pPS;
	}

	pAsm->Release();

	if( FAILED(hr) )
	{
		LcD3D_GetDxError(hr);
		return NULL;
	}

	return pShd;
}
Exemple #26
0
// 进入循环之前的设置
bool SetUp()
{

	if (!d3d9::CheckShaderVersion(g_pDevice))
	{
		MessageBox(0, "Shader version can not support!", 0, 0);
		return false;
	}
	HRESULT hr = 0;
	hr = D3DXCreateTeapot(g_pDevice, &g_pTeapot, NULL);
	if (FAILED(hr))
	{
		MessageBox(0, "Create teapot failed!", 0, 0);
		return false;
	}

	ID3DXBuffer *pShaderCache;
	ID3DXBuffer *pErrorMsg;
	hr = D3DXCompileShaderFromFile(
		"Diffuse.txt",
		NULL,
		NULL,
		"Main",
		"vs_1_1",
		D3DXSHADER_DEBUG,
		&pShaderCache,
		&pErrorMsg,
		&g_pConstTable
		);
	if (pErrorMsg)
	{
		MessageBox(0, (char*)pErrorMsg->GetBufferPointer(), 0, 0);
		d3d9::Release(pErrorMsg);
		return false;
	}
	d3d9::Release(pErrorMsg);

	if (!g_pConstTable)
	{
		MessageBox(0, "Const table is NULL!", 0, 0);
		return false;
	}

	if (FAILED(hr))
	{
		MessageBox(0, "Failed to compile shader from file!", 0, 0);
		return false;
	}

	hr = g_pDevice->CreateVertexShader((DWORD*)pShaderCache->GetBufferPointer(), &g_pVertexShader);

	if (FAILED(hr))
	{
		MessageBox(0, "Failed to create vertex shader!", 0, 0);
		d3d9::Release(pShaderCache);
		return false;
	}
	d3d9::Release(pShaderCache);

	g_hViewMatrix = g_pConstTable->GetConstantByName(NULL, "ViewMatrix");
	if (!g_hViewMatrix)
	{
		MessageBox(0, "Get ViewMatrix failed!", 0, 0);
		return false;
	}

	g_hViewProjMatrix = g_pConstTable->GetConstantByName(NULL, "ViewProjMatrix");
	if (!g_hViewProjMatrix)
	{
		MessageBox(0, "Get ViewProjMatrix failed!", 0, 0);
		return false;
	}

	g_hAmbientMtrl = g_pConstTable->GetConstantByName(NULL, "AmbientMtrl");
	if (!g_hAmbientMtrl)
	{
		MessageBox(0, "Get AmbientMtrl failed!", 0, 0);
		return false;
	}

	g_hDiffMtrl = g_pConstTable->GetConstantByName(NULL, "DiffMtrl");
	if (!g_hDiffMtrl)
	{
		MessageBox(0, "Get DiffMtrl failed!", 0, 0);
		return false;
	}

	g_hLightDir = g_pConstTable->GetConstantByName(NULL, "LightDir");
	if (!g_hLightDir)
	{
		MessageBox(0, "Get LightDir failed!", 0, 0);
		return false;
	}
	g_pConstTable->SetDefaults(g_pDevice);

	D3DXVECTOR4 dirtolight(-0.57f, 0.57f, -0.57f, 0.0f);
	g_pConstTable->SetVector(g_pDevice, g_hLightDir, &dirtolight);

	D3DXVECTOR4 ambientmtrl(0.0f, 0.0f, 1.0f, 1.0f);
	D3DXVECTOR4 diffmtrl(0.0f, 0.0f, 1.0f, 1.0f);
	g_pConstTable->SetVector(g_pDevice, g_hAmbientMtrl, &ambientmtrl);
	g_pConstTable->SetVector(g_pDevice, g_hDiffMtrl, &diffmtrl);


	// 竖直视角,宽/高比,近裁剪面,远裁剪面
	D3DXMatrixPerspectiveFovLH(&g_ProjMatrix, D3DX_PI*0.25f, (float)Width / (float)Height, 1.0f, 1000.0f);

	return true;
}