Exemple #1
0
//初始化像素着色器
bool InitEffect()
{
	HRESULT rlt;
	ID3DXBuffer* shader      = NULL;
	ID3DXBuffer* errorBuffer = NULL;

/*	
	rlt = D3DXCompileShaderFromFileW(
		L"effect.txt",0,0,
		"effect","ps_2_0",0,&shader,&errorBuffer,&MultiTexCT);//*/


	rlt = D3DXCompileShaderFromResource(hmod,MAKEINTRESOURCEW(IDR_RCDATA1),0,0,"effect","ps_2_0",0,&shader,&errorBuffer,&MultiTexCT);
	

	if( errorBuffer )
	{
		MessageBoxA(0, (char*)errorBuffer->GetBufferPointer(), 0, 0);
		errorBuffer->Release();
		return false;
	}
	if(FAILED(rlt))
	{
		MessageBoxA(0,"执行D3DXCompileShader失败!", "错误", 0);
		return false;
	}


	if(FAILED(g_pd3dD->CreatePixelShader((DWORD*)shader->GetBufferPointer(),&MultiTexPS)))
	{
		MessageBoxA(0,"执行CreatePixelShader失败!", "错误", 0);
		return false;
	}
	shader->Release();


	MultiTexCT->SetDefaults(g_pd3dD);

	alphaHandle		= MultiTexCT->GetConstantByName(0, "alpha");
	alpha_oldHandle	= MultiTexCT->GetConstantByName(0, "alpha_old");
	alpha_newHandle	= MultiTexCT->GetConstantByName(0, "alpha_new");
	typeHandle		= MultiTexCT->GetConstantByName(0, "type");
	sample0Handle	= MultiTexCT->GetConstantByName(0, "Samp0");
	sample1Handle	= MultiTexCT->GetConstantByName(0, "Samp1");
	sample2Handle	= MultiTexCT->GetConstantByName(0, "Samp2");

	UINT count;
	MultiTexCT->GetConstantDesc(sample0Handle, &sample0Desc, &count);
	MultiTexCT->GetConstantDesc(sample1Handle, &sample1Desc, &count);
	MultiTexCT->GetConstantDesc(sample2Handle, &sample2Desc, &count);

	return true;
}
Exemple #2
0
HRESULT MESH::Load(char fName[], IDirect3DDevice9* Dev)
{
	m_pDevice = Dev;

	//Set m_white material
	m_white.Ambient = m_white.Specular = m_white.Diffuse  = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
	m_white.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
	m_white.Power = 1.0f;

	Release();

	//Load new m_pMesh
	ID3DXBuffer * adjacencyBfr = NULL;
	ID3DXBuffer * materialBfr = NULL;
	DWORD noMaterials = NULL;

	if(FAILED(D3DXLoadMeshFromX(fName, D3DXMESH_MANAGED, m_pDevice,	
								&adjacencyBfr, &materialBfr, NULL, 
								&noMaterials, &m_pMesh)))
		return E_FAIL;

	D3DXMATERIAL *mtrls = (D3DXMATERIAL*)materialBfr->GetBufferPointer();

	for(int i=0;i<(int)noMaterials;i++)
	{
		//mtrls[i].MatD3D.Ambient = mt[i].MatD3D.Diffuse;
		m_materials.push_back(mtrls[i].MatD3D);

		if(mtrls[i].pTextureFilename != NULL)
		{
			char textureFileName[90];
			strcpy(textureFileName, "meshes/");
			strcat(textureFileName, mtrls[i].pTextureFilename);
			IDirect3DTexture9 * newTexture = NULL;
			D3DXCreateTextureFromFile(m_pDevice, textureFileName, &newTexture);			
			m_textures.push_back(newTexture);
		}
		else m_textures.push_back(NULL);
	}

	m_pMesh->OptimizeInplace(D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE,
							(DWORD*)adjacencyBfr->GetBufferPointer(), NULL, NULL, NULL);

	adjacencyBfr->Release();
	materialBfr->Release();

	return S_OK;
}
Exemple #3
0
bool MGEhud::init(IDirect3DDevice9 *d)
{
    device = d;
    device->GetViewport(&vp);

    LOG::logline(">> HUD init");

    HRESULT hr = device->CreateVertexBuffer(max_elements * 4 * 32, D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY, fvfHUD, D3DPOOL_DEFAULT, &vbHUD, 0);
    if(hr != D3D_OK)
    {
        LOG::logline("!! Failed to create HUD verts");
        return false;
    }

    ID3DXBuffer *errors;
	hr = D3DXCreateEffectFromFile(device, "Data Files\\shaders\\XE HUD.fx", 0, 0, 0, 0, &effectStandard, &errors);
	if(hr != D3D_OK)
	{
        LOG::logline("!! HUD Shader errors: %s", errors->GetBufferPointer());
        errors->Release();
        return false;
	}

    if(element_names.empty())
        reset();
    else
        reload();

    LOG::logline("<< HUD init");
    return true;
}
Model Model::createFromFile(const GraphicsDevice& device, const std::string& filename)
{
	Model model;

	ID3DXBuffer* materialBuffer;
	unsigned long numMaterials;

	D3DXLoadMeshFromXA(filename.c_str(), D3DXMESH_MANAGED, device, 0, &materialBuffer, 0, &numMaterials, &model.mesh);

	model.materials = MaterialCollection(numMaterials);
	model.textures = TextureCollection(numMaterials);

	D3DXMATERIAL* materials = (D3DXMATERIAL*)materialBuffer->GetBufferPointer();

	std::string path = filename.substr(0, filename.find_last_of('/') + 1);

	for (unsigned i = 0; i < numMaterials; ++i)
	{
		if (materials[i].pTextureFilename)
			model.textures[i] = Texture::createFromFile(device, path + materials[i].pTextureFilename);

		model.materials[i] = materials[i].MatD3D;
	}

	materialBuffer->Release();

	return model;
}
Exemple #5
0
Mesh::Mesh(LPCWSTR file)
: _mesh(NULL)
, _meshMaterials(NULL)
, _meshTextures(NULL)
, _meshMaterialCount(0)
{
	ID3DXBuffer * meshMaterialBuffer = NULL;
	HRESULT hr = D3DXLoadMeshFromX(file, 0, dxr->device, NULL, &meshMaterialBuffer, NULL, &_meshMaterialCount, &_mesh);
	_ASSERT(SUCCEEDED(hr));
	if (meshMaterialBuffer && _meshMaterialCount > 0)
	{
		D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)meshMaterialBuffer->GetBufferPointer();
		_meshMaterials = new D3DMATERIAL9[_meshMaterialCount];
		_meshTextures = new IDirect3DTexture9 * [_meshMaterialCount];
		for (unsigned long i = 0; i < _meshMaterialCount; i++)
		{
			_meshMaterials[i] = d3dxMaterials[i].MatD3D;
			if (D3DXCOLOR(0xff000000) == _meshMaterials[i].Ambient)
				_meshMaterials[i].Ambient = D3DXCOLOR(0.75,0.75,0.75,0.75);
			_meshTextures[i] = NULL;
			if (d3dxMaterials[i].pTextureFilename)
			{
				QString texturePath = native(QFileInfo(QString::fromUtf16((const ushort *)file)).dir() / QFileInfo(d3dxMaterials[i].pTextureFilename).fileName());
				hr = D3DXCreateTextureFromFileW(dxr->device, (LPCWSTR)texturePath.utf16(), &_meshTextures[i]);
				_ASSERT(SUCCEEDED(hr));
			}
		}
	}
	meshMaterialBuffer->Release();	
}
Exemple #6
0
void AssetLoader::loadEffect(LPCSTR path)
{
	ID3DXEffect * tempFX;
	ID3DXBuffer *errors = NULL;

	string tech = path;
	
	while (tech.back() != '.')
		tech.pop_back();
	
	tech.pop_back(); //.
	tech += string("Technique");

	int rc = D3DXCreateEffectFromFile(d3dDev, 
		path, 
		0, 0, D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION, 0, 
		&tempFX, 
		&errors);
	
	if (errors != NULL) 
	{
		MessageBox(0, (char*) errors->GetBufferPointer(),0,0);
		errors->Release();
	}
	else
	{
		Effect * tempEffect = new Effect();
		tempEffect->name = path;
		tempEffect->techniqueName = tech;
		tempEffect->inUse = false;
		tempEffect->effect = tempFX;
		peffects->push_back(tempEffect);
	}
}
GBitmap *AtlasTexChunk::loadDDSIntoGBitmap(const U8 *ddsBuffer, U32 ddsBufferSize)
{
    D3DXIMAGE_INFO info;
    D3D9Assert(GFXD3DX.D3DXGetImageInfoFromFileInMemory(ddsBuffer, ddsBufferSize, &info),
               "AtlasTexChunk::loadDDSIntoGBitmap - failed to get image info.");

    IDirect3DSurface9 *surf = NULL;
    D3D9Assert(((GFXD3D9Device*)GFX)->getDevice()->CreateOffscreenPlainSurface(
                   info.Width, info.Height, info.Format, D3DPOOL_SCRATCH, &surf, NULL),
               "AtlasTexChunk::loadDDSIntoGBitmap - failed to allocate scratch surface.");

    // We want JPEGs, let's convert it in a klunky way...
    D3D9Assert(GFXD3DX.D3DXLoadSurfaceFromFileInMemory(surf, NULL, NULL,
               ddsBuffer, ddsBufferSize, NULL,
               D3DX_DEFAULT, 0, NULL),
               "AtlasTexChunk::loadDDSIntoGBitmap - D3DX failed to load from buffer.");

    ID3DXBuffer *buff = NULL;
    D3D9Assert(GFXD3DX.D3DXSaveSurfaceToFileInMemory(&buff, D3DXIFF_PNG, surf, NULL, NULL),
               "AtlasTexChunk::loadDDSIntoGBitmap - D3DX failed to save back to buffer.");
    MemStream ms(buff->GetBufferSize(), buff->GetBufferPointer(), true, false);

    GBitmap *bitmap = new GBitmap[1];
    bitmap->readBitmap( "png", ms );

    // Cleanup!
    buff->Release();
    surf->Release();

    return bitmap;
}
//--------------------------------------------------------------------------------------
//LoadShader
//--------------------------------------------------------------------------------------
HRESULT CEffect::LoadShader(WCHAR *a_Filename, IDirect3DDevice9 *a_pDevice)
{
   HRESULT hr;
   ID3DXBuffer *errorBuffer;
   WCHAR str[MAX_PATH];

   m_pDevice = a_pDevice;

   //delete old effect if multiple calls to load shader are made
   SAFE_RELEASE(m_pEffect);

   // 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_FORCE_VS_SOFTWARE_NOOPT;
   #endif
   #ifdef DEBUG_PS
       dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
   #endif

   // Read the D3DX effect file
   hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, a_Filename );

   // search DX search paths for .fx file
   if(FAILED(hr))
   {  
      _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Error: Can't Find Shader %s in any search paths.", a_Filename);
      return STG_E_FILENOTFOUND;
   }


   //load and compile .fx file
   // If this fails, there should be debug output as to 
   // why the .fx file failed to compile
   hr = D3DXCreateEffectFromFile( m_pDevice, str, NULL, NULL, 
       dwShaderFlags, NULL, &m_pEffect, &errorBuffer );

   //return failure and record error message if failure
   if(FAILED(hr))
   {  //error is in 8-bit character format, so for swprintf to use the string, %S (capital S) is used.
      _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: %S.", errorBuffer->GetBufferPointer() );
      errorBuffer->Release();
      return hr;
   }

   _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"FX file %s Compiled Successfully.", a_Filename);

   return S_OK;
}
Exemple #9
0
bool Blit::setShader(ShaderId source, const char *profile,
                     HRESULT (WINAPI IDirect3DDevice9::*createShader)(const DWORD *, D3DShaderType**),
                     HRESULT (WINAPI IDirect3DDevice9::*setShader)(D3DShaderType*))
{
    IDirect3DDevice9 *device = getDevice();

    D3DShaderType *shader;

    if (mCompiledShaders[source] != NULL)
    {
        shader = static_cast<D3DShaderType*>(mCompiledShaders[source]);
    }
    else
    {
        ID3DXBuffer *shaderCode;
        HRESULT hr = D3DXCompileShader(mShaderSource[source], strlen(mShaderSource[source]), NULL, NULL, "main", profile, 0, &shaderCode, NULL, NULL);

        if (FAILED(hr))
        {
            ERR("Failed to compile %s shader for blit operation %d, error 0x%08X.", profile, (int)source, hr);
            return false;
        }

        hr = (device->*createShader)(static_cast<const DWORD*>(shaderCode->GetBufferPointer()), &shader);
        if (FAILED(hr))
        {
            shaderCode->Release();
            ERR("Failed to create %s shader for blit operation %d, error 0x%08X.", profile, (int)source, hr);
            return false;
        }

        shaderCode->Release();

        mCompiledShaders[source] = shader;
    }

    HRESULT hr = (device->*setShader)(shader);

    if (FAILED(hr))
    {
        ERR("Failed to set %s shader for blit operation %d, error 0x%08X.", profile, (int)source, hr);
        return false;
    }

    return true;
}
Exemple #10
0
bool NavigationLine::CreateDeviceObjects()
{
	if (!m_visible)
		return true;

	ID3DXBuffer* errors = 0;
	HRESULT hr;

	hr = D3DXCreateTextureFromFileA(g_pDevice, m_textureFile.c_str(), &m_lineTexture);
	if (FAILED(hr))
	{
		DebugSpewAlways("Failed to load texture!");

		InvalidateDeviceObjects();
		return false;
	}

	hr = D3DXCreateEffectFromFileA(g_pDevice, m_shaderFile.c_str(),
		NULL, NULL, 0, NULL, &m_effect, &errors);
	if (FAILED(hr))
	{
		if (errors)
		{
			DebugSpewAlways("Effect error: %s", errors->GetBufferPointer());

			errors->Release();
			errors = nullptr;
		}

		InvalidateDeviceObjects();
		return false;
	}

	D3DVERTEXELEMENT9 vertexElements[] =
	{
		{ 0,  0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION,  0 },
		{ 0, 12,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,  0 },
		{ 0, 24,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,  0 },
		{ 0, 40,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,  1 },
		D3DDECL_END()
	};

	hr = g_pDevice->CreateVertexDeclaration(vertexElements, &m_vDeclaration);
	if (FAILED(hr))
	{
		InvalidateDeviceObjects();
		return false;
	}

	m_effect->SetTexture("lineTexture", m_lineTexture);
	m_loaded = true;

	return true;
}
void VertexShader::Create(IDirect3DDevice9* device, const char* fileName, const char* entryPoint, const char* macroDefinition)
{
	Destroy();

	ID3DXBuffer* shaderCode = Shader::CreateFromFile(fileName, "vs_3_0", entryPoint, macroDefinition);
	if (shaderCode)
	{
		device->CreateVertexShader( ( DWORD* )shaderCode->GetBufferPointer(), &vertexShader );
		shaderCode->Release();
	}
}
Exemple #12
0
bool CompileVertexShader(const char *code, LPDIRECT3DVERTEXSHADER9 *pShader, LPD3DXCONSTANTTABLE *pShaderTable, std::string &errorMessage) {
	ID3DXBuffer *pShaderCode = nullptr;
	ID3DXBuffer *pErrorMsg = nullptr;

	// Compile pixel shader.
	HRESULT hr = dyn_D3DXCompileShader(code,
		(UINT)strlen(code),
		nullptr,
		nullptr,
		"main",
		"vs_2_0",
		0,
		&pShaderCode,
		&pErrorMsg,
		pShaderTable);

	if (pErrorMsg) {
		errorMessage = (CHAR *)pErrorMsg->GetBufferPointer();
		pErrorMsg->Release();
	} else if (FAILED(hr)) {
		errorMessage = GetStringErrorMsg(hr);
	} else {
		errorMessage = "";
	}

	if (FAILED(hr) || !pShaderCode) {
		if (pShaderCode)
			pShaderCode->Release();
		return false;
	}

	// Create pixel shader.
	pD3Ddevice->CreateVertexShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		pShader );

	pShaderCode->Release();

	return true;
}
Exemple #13
0
bool CompilePixelShader(const char *code, LPDIRECT3DPIXELSHADER9 *pShader, LPD3DXCONSTANTTABLE *pShaderTable, std::string &errorMessage) {
	ID3DXBuffer* pShaderCode = NULL;
	ID3DXBuffer* pErrorMsg = NULL;

	HRESULT hr = -1;

	// Compile pixel shader.
	hr = dyn_D3DXCompileShader(code,
		(UINT)strlen(code),
		NULL,
		NULL,
		"main",
		"ps_2_0",
		0,
		&pShaderCode,
		&pErrorMsg,
		pShaderTable);

	if (pErrorMsg) {
		errorMessage = (CHAR *)pErrorMsg->GetBufferPointer();
		pErrorMsg->Release();
	} else {
		errorMessage = "";
	}

	if (FAILED(hr)) {
		if (pShaderCode)
			pShaderCode->Release();
		return false;
	}

	// Create pixel shader.
	pD3Ddevice->CreatePixelShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		pShader );

	pShaderCode->Release();

	return true;
}
Exemple #14
0
bool PrepareShader() 
{ 
	ID3DXBuffer *shader ; 
	ID3DXBuffer *errorBuffer ; 

	// Compile shader from file, Shader.txt must exist in current directory, and it must contain
	// the "Main" function
	HRESULT hr = D3DXCompileShaderFromFileA("torus.fx", 0, 0, "Main", "ps_2_0",  
		D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, &shader, &errorBuffer, NULL) ; 

	// output any error messages 
	if( errorBuffer ) 
	{ 
		MessageBoxA(0, (char*)errorBuffer->GetBufferPointer(), 0, 0); 
		errorBuffer->Release() ; 
	} 

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

	// Create pixel shader 
	hr = g_pd3dDevice->CreatePixelShader((DWORD*)shader->GetBufferPointer(), &g_pPixelShader) ; 

	// handling error 
	if(FAILED(hr)) 
	{ 
		MessageBox(0, L"CreatePixelShader - FAILED", 0, 0); 
		return false; 
	} 

	// Release DX buffer
	shader->Release() ; 

	return true ;
} 
Exemple #15
0
HRESULT CMesh3D::InitialMesh(LPCSTR Name, FILE *FileLog )
{
	m_pMesh         = 0;
	m_pMeshMaterial = 0;
	m_pMeshTextura  = 0;
	m_SizeFVF       = 0;
	m_Alpha         = 1.0f;	
	ID3DXBuffer *pMaterialBuffer  = 0;
	if ( FAILED( D3DXLoadMeshFromX( Name, D3DXMESH_SYSTEMMEM, g_pD3DDevice, 0, &pMaterialBuffer, 0, &m_TexturCount, &m_pMesh ) ) )
	{
		if ( m_pMesh == 0 )
		{		
			if ( FileLog ) 
				fprintf( FileLog, "error load x file '%s'\n", Name );
			return E_FAIL;
		}
	}

	if ( m_pMesh->GetFVF() & D3DFVF_XYZ ) 
		m_SizeFVF += sizeof(float)*3;
	if ( m_pMesh->GetFVF() & D3DFVF_NORMAL ) 
		m_SizeFVF += sizeof(float)*3;
	if ( m_pMesh->GetFVF() & D3DFVF_TEX1 )
		m_SizeFVF += sizeof(float)*2;

	m_pMesh->GetVertexBuffer( &m_VertexBuffer );
	m_pMesh->GetIndexBuffer(  &m_IndexBuffer  );
	// Извлекаем свойства материала и названия{имена} структуры
	D3DXMATERIAL *D3DXMeshMaterial = (D3DXMATERIAL *)pMaterialBuffer->GetBufferPointer();
	m_pMeshMaterial  = new D3DMATERIAL9[m_TexturCount];
	m_pMeshTextura   = new IDirect3DTexture9*[m_TexturCount];
	for ( DWORD i = 0; i < m_TexturCount; i++ )
	{
		// Копируем материал
		m_pMeshMaterial[i] = D3DXMeshMaterial[i].MatD3D;
		// Установить окружающего свет
		m_pMeshMaterial[i].Ambient = m_pMeshMaterial[i].Diffuse;
		// Загружаем текстуру
		string FileName = string( "model//" ) + string( D3DXMeshMaterial[i].pTextureFilename );
		if ( FAILED( D3DXCreateTextureFromFile( g_pD3DDevice, FileName.c_str(), &m_pMeshTextura[i] )))
		{
			fprintf( FileLog, "error load texture '%s'\n", D3DXMeshMaterial[i].pTextureFilename );
			m_pMeshTextura[i] = 0;
		}
	}
	// Уничтожаем буфер материала
	pMaterialBuffer->Release();

	return S_OK;
}
Exemple #16
0
MeshObject::MeshObject( const char *name, const char *path, const char *file_name, bool lighten ) : 
   Object(std::string(name))
{
   ID3DXBuffer *pMat = NULL;

   _isLightenUp = lighten;

   _mesh = 0;
   _materials = 0;
   _textures = 0;

   std::string full_name = std::string(path) + std::string("\\") + std::string(file_name);

   HRESULT hr = D3DXLoadMeshFromX(full_name.c_str(), D3DXMESH_SYSTEMMEM, getDevice(),
      NULL, &pMat, NULL, &_numMaterials, &_mesh);

   if (SUCCEEDED(hr))
   {
      D3DXMATERIAL* pD3DXMaterials=(D3DXMATERIAL*)pMat->GetBufferPointer();

      _materials = new D3DMATERIAL9[_numMaterials];
      _textures = new LPDIRECT3DTEXTURE9[_numMaterials];

      for (DWORD i = 0; i < _numMaterials; ++i)
      {
         _materials[i] = pD3DXMaterials[i].MatD3D;
         _materials[i].Ambient = _materials[i].Diffuse;

         if (pD3DXMaterials[i].pTextureFilename != 0)
         {
            std::string full_tex_name = std::string(path) + 
               "\\" + std::string(pD3DXMaterials[i].pTextureFilename);
            hr = D3DXCreateTextureFromFile(getDevice(), 
                  full_tex_name.c_str(), &(_textures[i]));

            if (FAILED(hr))
               _textures[i] = 0;
         }
         else
            _textures[i] = 0;
      }

      if (pMat)
         pMat->Release();

      _mesh->OptimizeInplace(D3DXMESHOPT_COMPACT |
         D3DXMESHOPT_ATTRSORT, NULL, NULL, NULL, NULL);
   }
}
Exemple #17
0
Teapot::Teapot()
{
	D3DXCreateTeapot(theDevice, &m_mesh, nullptr);
	
	ID3DXBuffer* errorBuffer;
	D3DXCreateEffectFromFile(theDevice, "Teapot.fx", 0, 0,
		D3DXSHADER_DEBUG, 0, &m_effect, &errorBuffer);

	if (errorBuffer)
	{
		Error((char*)errorBuffer->GetBufferPointer());
		errorBuffer->Release();
	}

	m_hWorldViewProj = m_effect->GetParameterByName(0, "matWorldViewProj");
}
void initEffect()
{
	ID3DXBuffer* errorBuffer = 0;
	D3DXCreateEffectFromFile(
		device,
		L"effect.fx",
		NULL, // CONST D3DXMACRO* pDefines,
		NULL, // LPD3DXINCLUDE pInclude,
		D3DXSHADER_USE_LEGACY_D3DX9_31_DLL,
		NULL, // LPD3DXEFFECTPOOL pPool,
		&effect,
		&errorBuffer);

	if(errorBuffer)
	{
		MessageBoxA(hMainWnd, (char*)errorBuffer->GetBufferPointer(), 0, 0);
		errorBuffer->Release();
		terminate();
	}

	D3DXMATRIX W, V, P, Result;
	D3DXMatrixIdentity(&Result);
	device->GetTransform(D3DTS_WORLD, &W);
	device->GetTransform(D3DTS_VIEW, &V);
	device->GetTransform(D3DTS_PROJECTION, &P);
	D3DXMatrixMultiply(&Result, &W, &V);
	D3DXMatrixMultiply(&Result, &Result, &P);

	effect->SetMatrix(effect->GetParameterByName(0, "WorldViewProj"), &Result);

	effect->SetTechnique(effect->GetTechnique(0));

	auto hr = effect->SetTexture(effect->GetParameterByName(NULL, "Overlay"), overlayTexture);
	hr |= effect->SetTexture(effect->GetParameterByName(NULL, "Base"), particleTexture);
	hr |= effect->SetTexture(effect->GetParameterByName(NULL, "PreRender"), renderTexture);

	if(hr != 0)
	{
		MessageBox(hMainWnd, L"Unable to set effect textures.", L"", MB_ICONHAND);
	}
}
bool TerrainLodMap2::save( DataSectionPtr parentSection, const std::string& name ) const
{
	BW_GUARD;
	bool ok = false;

	// copy texture to a file buffer in memory
	ID3DXBuffer* pBuffer = NULL;
	HRESULT hr = D3DXSaveTextureToFileInMemory( &pBuffer, D3DXIFF_DDS, 
										   pLodMap_.pComObject(), NULL  );

	if (SUCCEEDED(hr))
	{
		// copy buffer to binary block
		BinaryPtr pBlock = new BinaryBlock( pBuffer->GetBufferPointer(), 
			pBuffer->GetBufferSize(), "BinaryBlock/TerrainPhotographer" );
		pBuffer->Release();

		// write binary block to data section
		ok = parentSection->writeBinary( name, pBlock );
	}

	return ok;
}
Exemple #20
0
void MGEhud::setEffect(hud_id hud, const char *effect)
{
    Element *e = &elements[hud];
    char path[MAX_PATH];
    ID3DXBuffer *errors;

    // Clear current effect
    if(e->effect)
        e->effect->Release();

    e->effect = 0;
    e->effectFilename.clear();

    // Load new effect if string is not empty
    if(*effect)
    {
        sprintf_s(path, MAX_PATH, "Data Files\\shaders\\%s.fx", effect);
        HRESULT hr = D3DXCreateEffectFromFile(device, path, 0, 0, 0, 0, &e->effect, &errors);

        if(hr == D3D_OK)
        {
            LOG::logline("-- HUD shader %s loaded", path);
            e->effectFilename = effect;
        }
        else
        {
            e->effect = 0;

            LOG::logline("!! HUD shader %s failed to load/compile", path);
            if(errors)
            {
                LOG::logline("!! Shader errors: %s", errors->GetBufferPointer());
                errors->Release();
            }
        }
    }
}
void mini3d::D3D9VertexShader::LoadResource(void)
{
	IDirect3DDevice9* pDevice = pGraphicsService->GetDevice();
	if (pDevice == 0)
		return;

	// If the buffer exists tear it down.
	if (pShaderBuffer != 0)
	{
		UnloadResource();
	}

	// compile the shader source
	ID3DXBuffer* buffer;

	LPD3DXBUFFER ppErroMessage;
	D3DXCompileShader((LPCSTR)pShaderBytes, sizeInBytes, 0, 0, "main", "vs_2_0", 0, &buffer, &ppErroMessage, 0);
	
	if (ppErroMessage != 0)
	{
		OutputDebugStringA((char*)(ppErroMessage->GetBufferPointer()));
		isDirty = true;
		return;
	}

	if( FAILED( pDevice->CreateVertexShader((DWORD*)buffer->GetBufferPointer(), &pShaderBuffer)))
	{
		isDirty = true;
		return;
	}

	buffer->Release();
	isDirty = false;

	// load the vertex declaration into the pool
	pGraphicsService->PoolVertexDeclaration(vertexDeclaration, vertexDataCount);
}
Exemple #22
0
bool DevEffect::CompileVersion(
			const char *id, const char *path, vector<byte> &bin,
			vector<D3DXMACRO> &macros, const char *skip_list )
{
	ID3DXEffect *fx = NULL;
	ID3DXBuffer *errors = NULL;

	HRESULT r = D3DXCreateEffectEx(Dev.GetDevice(),&bin[0],(DWORD)bin.size(),&macros[0],NULL,skip_list,
		compile_flags,pool,&fx,&errors);

	if(FAILED(r) || errors)
	{
		if(errors)
		{
			last_error = format("%s:%s: %s",path,id,(char*)errors->GetBufferPointer());
			if(!(flags&FXF_NO_ERROR_POPUPS))
				if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
					ExitProcess(0);
			errors->Release();
			return false;
		}
		else
		{
			last_error = format("%s:%s: Unknown error!",path,id);
			if(!(flags&FXF_NO_ERROR_POPUPS))
				if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
					ExitProcess(0);
			return false;
		}
	}

	version_index[id] = (int)fx_list.size();
	fx_list.push_back(fx);

	return true;
}
Exemple #23
0
bool CompilePixelShader(const char * code, LPDIRECT3DPIXELSHADER9 * pShader, LPD3DXCONSTANTTABLE * pShaderTable) {
	LPD3DXCONSTANTTABLE shaderTable = *pShaderTable;

	ID3DXBuffer* pShaderCode = NULL;
	ID3DXBuffer* pErrorMsg = NULL;

	HRESULT hr = -1;

#ifdef _XBOX
	// Compile pixel shader.
	hr = D3DXCompileShader( code, 
		(UINT)strlen( code ),
		NULL, 
		NULL, 
		"main", 
		"ps_3_0", 
		0, 
		&pShaderCode, 
		&pErrorMsg,
		pShaderTable );
#endif
	if( FAILED(hr) )
	{
		OutputDebugStringA((CHAR*)pErrorMsg->GetBufferPointer());
		DebugBreak();
		return false;
	}

	// Create pixel shader.
	pD3Ddevice->CreatePixelShader( (DWORD*)pShaderCode->GetBufferPointer(), 
		pShader );

	pShaderCode->Release();

	return true;
}
Exemple #24
0
bool Setup()
{
	HRESULT hr;

	ID3DXBuffer* mtrlBuffer = 0;
	DWORD numMtrl = 0;
	hr = D3DXLoadMeshFromX(
		L"mountain.x",
		D3DXMESH_MANAGED,
		Device,
		0,
		&mtrlBuffer,
		0,
		&numMtrl,
		&pMesh);

	if (FAILED(hr))
	{
		::MessageBoxA(0, "D3DXLoadMeshFromX() - Failed!", 0, 0);
		return false;
	}

	if (mtrlBuffer != 0 && numMtrl != 0)
	{
		D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer();
		for (DWORD i = 0; i < numMtrl; ++i)
		{
			mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse;
			Mtrls.push_back(mtrls[i].MatD3D);

			if (mtrls[i].pTextureFilename != 0)
			{
				IDirect3DTexture9* tex = 0;
				D3DXCreateTextureFromFileA(
					Device,
					mtrls[i].pTextureFilename,
					&tex);
				Textures.push_back(tex);
			}
			else
			{
				Textures.push_back(0);
			}
		}
	}

	mtrlBuffer->Release();
	ID3DXBuffer* pError;
	hr = D3DXCreateEffectFromFile(
		Device,
		L"light_tex.txt",
		0,
		0,
		D3DXSHADER_DEBUG,
		0,
		&pLightTexEffect,
		&pError);
	if (FAILED(hr))
	{
		::MessageBoxA(0, (char*)pError->GetBufferPointer(), 0, 0);
		return false;
	}

	hWorldMatrix = pLightTexEffect->GetParameterByName(0, "WorldMatrix");
	hViewMatrix = pLightTexEffect->GetParameterByName(0, "ViewMatrix");
	hProjMatrix = pLightTexEffect->GetParameterByName(0, "ProjMatrix");
	hTex = pLightTexEffect->GetParameterByName(0, "Tex");

	hLightTexTech = pLightTexEffect->GetTechniqueByName("LightAndTexture");

	D3DXMATRIX W, P;

	D3DXMatrixIdentity(&W);
	pLightTexEffect->SetMatrix(hWorldMatrix, &W);

	D3DXMatrixPerspectiveFovLH(
		&P,
		D3DX_PI*0.25f,
		(float)Width / Height,
		1.0f, 1000.0f);
	pLightTexEffect->SetMatrix(hProjMatrix, &P);

	IDirect3DTexture9* tex = 0;
	D3DXCreateTextureFromFile(Device, L"Terrain_3x_diffcol.jpg", &tex);

	pLightTexEffect->SetTexture(hTex, tex);
	tex->Release();

	return true;
}
	bool SPPixelShaderCore::Load( SPString path )
	{
		name = path;

		SPFilePtr file = SPFileManager::GetSingleton().OpenFile(path);

		if (!file)
		{
			SPLogHelper::WriteLog(L"[SPShader] WARNING: Failed to open shader file: " + path);
			return false;
		}

		ID3DXBuffer* shaderBuffer = NULL;
		ID3DXBuffer* errorBuffer = NULL;
		LONGLONG length = file->GetFileLength();
		char* pData = new char[(UINT)length];

		if(!file->Read(pData, (DWORD)length))
		{
			SPLogHelper::WriteLog(L"[SPShader] WARNING: Failed to read shader file: " + path);
			return false;
		}

		// Compile shader files.
		HRESULT hr = D3DXCompileShader(
			pData, (UINT)length, 0, 0, "Main", "ps_2_0", D3DXSHADER_DEBUG,
			&shaderBuffer, &errorBuffer, &constantTable);

		delete [] pData;
		SPFileManager::GetSingleton().CloseFile(path);

		if (errorBuffer)
		{
			SPLogHelper::WriteLog(L"[SPShader] WARNING: There is error in shader file: " + path);
			SPLogHelper::WriteLog("[SPShader] Message: " + string((char*)errorBuffer->GetBufferPointer()));
			errorBuffer->Release();
		}

		if (FAILED(hr))
		{
			SPLogHelper::WriteLog(L"[SPShader] WARNING: Failed to compile shader file: " + path);
			return false;
		}

		// Create pixel shader.
		hr = SPDevice::GetSingleton().GetD3DDevice()->CreatePixelShader(
			(DWORD*)shaderBuffer->GetBufferPointer(), &pixelShader);

		if (FAILED(hr))
		{
			SPLogHelper::WriteLog(L"[SPShader] WARNING: Failed to create pixel shader");

			if (shaderBuffer)
			{
				shaderBuffer->Release();
				shaderBuffer = NULL;
			}

			return false;
		}

		shaderBuffer->Release();
		shaderBuffer = NULL;

		return true;
	}
bool U2D3DXEffectShader::LoadResource()
{
	U2ASSERT(0 == m_pD3DEffect);

	HRESULT hr;
	
	IDirect3DDevice9* pD3DDev = m_pRenderer->GetD3DDevice();
	U2ASSERT(pD3DDev);

	U2FilePath fPath;		
	TCHAR fullPath[MAX_PATH];
	// StackString Memory Leak...
	U2DynString includePath(FX_SHADER_PATH);
	includePath += _T("\\2.0");

	fPath.ConvertToAbs(fullPath, MAX_PATH * sizeof(TCHAR) , m_szFilename.Str(), includePath);		

	U2File* pFile = U2File::GetFile(fullPath, U2File::READ_ONLY);
	if(!pFile)
	{
		U2_DELETE pFile;
		return false;
	}

	uint32 uBuffLen = pFile->GetfileSize();
	if(uBuffLen == 0)
	{
		U2_DELETE pFile;
		return false;
	}

	unsigned char* pBuffer = U2_ALLOC(unsigned char, uBuffLen);
	pFile->Read(pBuffer, uBuffLen);

	U2_DELETE pFile;

	ID3DXBuffer* pErrorBuffer = NULL;

#ifdef DEBUG_SHADER
	DWORD compileFlags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_USE_LEGACY_D3DX9_31_DLL
		| D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT | D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT ;	
#else
	DWORD compileFlags = D3DXSHADER_USE_LEGACY_D3DX9_31_DLL;
#endif

	//U2DynString includePath(FX_SHADER_PATH);
	//includePath += _T("\\2.0");
	
	U2D3DXEffectShaderInclude includeHandler(includePath);

	ID3DXEffectPool* pEffectPool = m_pRenderer->GetD3DEffectPool();
	U2ASSERT(pEffectPool);

	// get the highest supported shader profiles
//	LPCSTR vsProfile, psProfile;
//#ifdef UNICODE 
//	 vsProfile = ToUnicode( D3DXGetVertexShaderProfile(pD3DDev) );
//	 psProfile = ToUnicode( D3DXGetPixelShaderProfile(pD3DDev) );
//#else 
//	vsProfile = D3DXGetVertexShaderProfile(pD3DDev);
//	psProfile = D3DXGetPixelShaderProfile(pD3DDev);
//#endif
	LPCSTR vsProfile = D3DXGetVertexShaderProfile(pD3DDev);
	LPCSTR psProfile = D3DXGetPixelShaderProfile(pD3DDev);

	if (0 == vsProfile)
	{
		FDebug("Invalid Vertex Shader profile! Fallback to vs_2_0!\n");
		vsProfile = "vs_2_0";
	}

	if (0 == psProfile)
	{
		FDebug("Invalid Pixel Shader profile! Fallback to ps_2_0!\n");
		psProfile = "ps_2_0";
	}

	// create macro definitions for shader compiler
	D3DXMACRO defines[] = {
		{ "VS_PROFILE", vsProfile },
		{ "PS_PROFILE", psProfile },
		{ 0, 0 },
	};

	// create effect
	if (compileFlags)
	{
		hr = D3DXCreateEffectFromFile(
			pD3DDev,            // pDevice
			fullPath,   // File name
			defines,            // pDefines
			&includeHandler,    // pInclude
			compileFlags,       // Flags
			pEffectPool,         // pPool
			&m_pD3DEffect,    // ppEffect
			&pErrorBuffer);      // ppCompilationErrors
	}
	else
	{
		hr = D3DXCreateEffect(
			pD3DDev,            // pDevice
			pBuffer,             // pFileData
			uBuffLen,           // DataSize
			defines,            // pDefines
			&includeHandler,    // pInclude
			compileFlags,       // Flags
			pEffectPool,         // pPool
			&(m_pD3DEffect),    // ppEffect
			&pErrorBuffer);      // ppCompilationErrors
	}

	U2_FREE(pBuffer);
	pBuffer = NULL;

	if (FAILED(hr))
	{
		FDebug("nD3D9Shader: failed to load fx file '%s' with:\n\n%s\n",
			fullPath,
			pErrorBuffer ? pErrorBuffer->GetBufferPointer() : "No D3DX error message.");
		if (pErrorBuffer)
		{
			pErrorBuffer->Release();
		}
		return false;
	}
	U2ASSERT(m_pD3DEffect);

	m_bValidated = false;
	m_bNotValidate = false;

	this->ValidateEffect();

	return true;
}
Exemple #27
0
//-------------------------------------------------------------------------------
int CMaterialManager::CreateMaterial(
    AssetHelper::MeshHelper* pcMesh,const aiMesh* pcSource)
{
    ai_assert(NULL != pcMesh);
    ai_assert(NULL != pcSource);

    ID3DXBuffer* piBuffer;

    D3DXMACRO sMacro[64];

    // extract all properties from the ASSIMP material structure
    const aiMaterial* pcMat = g_pcAsset->pcScene->mMaterials[pcSource->mMaterialIndex];

    //
    // DIFFUSE COLOR --------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_DIFFUSE,
        (aiColor4D*)&pcMesh->vDiffuseColor))
    {
        pcMesh->vDiffuseColor.x = 1.0f;
        pcMesh->vDiffuseColor.y = 1.0f;
        pcMesh->vDiffuseColor.z = 1.0f;
        pcMesh->vDiffuseColor.w = 1.0f;
    }
    //
    // SPECULAR COLOR --------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_SPECULAR,
        (aiColor4D*)&pcMesh->vSpecularColor))
    {
        pcMesh->vSpecularColor.x = 1.0f;
        pcMesh->vSpecularColor.y = 1.0f;
        pcMesh->vSpecularColor.z = 1.0f;
        pcMesh->vSpecularColor.w = 1.0f;
    }
    //
    // AMBIENT COLOR --------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_AMBIENT,
        (aiColor4D*)&pcMesh->vAmbientColor))
    {
        pcMesh->vAmbientColor.x = 0.0f;
        pcMesh->vAmbientColor.y = 0.0f;
        pcMesh->vAmbientColor.z = 0.0f;
        pcMesh->vAmbientColor.w = 1.0f;
    }
    //
    // EMISSIVE COLOR -------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_EMISSIVE,
        (aiColor4D*)&pcMesh->vEmissiveColor))
    {
        pcMesh->vEmissiveColor.x = 0.0f;
        pcMesh->vEmissiveColor.y = 0.0f;
        pcMesh->vEmissiveColor.z = 0.0f;
        pcMesh->vEmissiveColor.w = 1.0f;
    }

    //
    // Opacity --------------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_OPACITY,&pcMesh->fOpacity))
    {
        pcMesh->fOpacity = 1.0f;
    }

    //
    // Shading Model --------------------------------------------------
    //
    bool bDefault = false;
    if(AI_SUCCESS != aiGetMaterialInteger(pcMat,AI_MATKEY_SHADING_MODEL,(int*)&pcMesh->eShadingMode ))
    {
        bDefault = true;
        pcMesh->eShadingMode = aiShadingMode_Gouraud;
    }


    //
    // Shininess ------------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_SHININESS,&pcMesh->fShininess))
    {
        // assume 15 as default shininess
        pcMesh->fShininess = 15.0f;
    }
    else if (bDefault)pcMesh->eShadingMode  = aiShadingMode_Phong;


    //
    // Shininess strength ------------------------------------------------------
    //
    if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_SHININESS_STRENGTH,&pcMesh->fSpecularStrength))
    {
        // assume 1.0 as default shininess strength
        pcMesh->fSpecularStrength = 1.0f;
    }

    aiString szPath;

    aiTextureMapMode mapU(aiTextureMapMode_Wrap),mapV(aiTextureMapMode_Wrap);

    bool bib =false;
    if (pcSource->mTextureCoords[0])
    {

        //
        // DIFFUSE TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_DIFFUSE(0),&szPath))
        {
            LoadTexture(&pcMesh->piDiffuseTexture,&szPath);

            aiGetMaterialInteger(pcMat,AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0),(int*)&mapU);
            aiGetMaterialInteger(pcMat,AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0),(int*)&mapV);
        }

        //
        // SPECULAR TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_SPECULAR(0),&szPath))
        {
            LoadTexture(&pcMesh->piSpecularTexture,&szPath);
        }

        //
        // OPACITY TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_OPACITY(0),&szPath))
        {
            LoadTexture(&pcMesh->piOpacityTexture,&szPath);
        }
        else
        {
            int flags = 0;
            aiGetMaterialInteger(pcMat,AI_MATKEY_TEXFLAGS_DIFFUSE(0),&flags);

            // try to find out whether the diffuse texture has any
            // non-opaque pixels. If we find a few, use it as opacity texture
            if (pcMesh->piDiffuseTexture && !(flags & aiTextureFlags_IgnoreAlpha) && HasAlphaPixels(pcMesh->piDiffuseTexture))
            {
                int iVal;

                // NOTE: This special value is set by the tree view if the user
                // manually removes the alpha texture from the view ...
                if (AI_SUCCESS != aiGetMaterialInteger(pcMat,"no_a_from_d",0,0,&iVal))
                {
                    pcMesh->piOpacityTexture = pcMesh->piDiffuseTexture;
                    pcMesh->piOpacityTexture->AddRef();
                }
            }
        }

        //
        // AMBIENT TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_AMBIENT(0),&szPath))
        {
            LoadTexture(&pcMesh->piAmbientTexture,&szPath);
        }

        //
        // EMISSIVE TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_EMISSIVE(0),&szPath))
        {
            LoadTexture(&pcMesh->piEmissiveTexture,&szPath);
        }

        //
        // Shininess TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_SHININESS(0),&szPath))
        {
            LoadTexture(&pcMesh->piShininessTexture,&szPath);
        }

        //
        // Lightmap TEXTURE ------------------------------------------------
        //
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_LIGHTMAP(0),&szPath))
        {
            LoadTexture(&pcMesh->piLightmapTexture,&szPath);
        }


        //
        // NORMAL/HEIGHT MAP ------------------------------------------------
        //
        bool bHM = false;
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_NORMALS(0),&szPath))
        {
            LoadTexture(&pcMesh->piNormalTexture,&szPath);
        }
        else
        {
            if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_HEIGHT(0),&szPath))
            {
                LoadTexture(&pcMesh->piNormalTexture,&szPath);
            }
            else bib = true;
            bHM = true;
        }

        // normal/height maps are sometimes mixed up. Try to detect the type
        // of the texture automatically
        if (pcMesh->piNormalTexture)
        {
            HMtoNMIfNecessary(pcMesh->piNormalTexture, &pcMesh->piNormalTexture,bHM);
        }
    }

    // check whether a global background texture is contained
    // in this material. Some loaders set this value ...
    if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_GLOBAL_BACKGROUND_IMAGE,&szPath))
    {
        CBackgroundPainter::Instance().SetTextureBG(szPath.data);
    }

    // BUGFIX: If the shininess is 0.0f disable phong lighting
    // This is a workaround for some meshes in the DX SDK (e.g. tiny.x)
    // FIX: Added this check to the x-loader, but the line remains to
    // catch other loader doing the same ...
    if (0.0f == pcMesh->fShininess){
        pcMesh->eShadingMode = aiShadingMode_Gouraud;
    }

    int two_sided = 0;
    aiGetMaterialInteger(pcMat,AI_MATKEY_TWOSIDED,&two_sided);
    pcMesh->twosided = (two_sided != 0);

    // check whether we have already a material using the same
    // shader. This will decrease loading time rapidly ...
    for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes;++i)
    {
        if (g_pcAsset->pcScene->mMeshes[i] == pcSource)
        {
            break;
        }
        AssetHelper::MeshHelper* pc = g_pcAsset->apcMeshes[i];

        if  ((pcMesh->piDiffuseTexture != NULL ? true : false) !=
            (pc->piDiffuseTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piSpecularTexture != NULL ? true : false) !=
            (pc->piSpecularTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piAmbientTexture != NULL ? true : false) !=
            (pc->piAmbientTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piEmissiveTexture != NULL ? true : false) !=
            (pc->piEmissiveTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piNormalTexture != NULL ? true : false) !=
            (pc->piNormalTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piOpacityTexture != NULL ? true : false) !=
            (pc->piOpacityTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piShininessTexture != NULL ? true : false) !=
            (pc->piShininessTexture != NULL ? true : false))
            continue;
        if  ((pcMesh->piLightmapTexture != NULL ? true : false) !=
            (pc->piLightmapTexture != NULL ? true : false))
            continue;
        if ((pcMesh->eShadingMode != aiShadingMode_Gouraud ? true : false) !=
            (pc->eShadingMode != aiShadingMode_Gouraud ? true : false))
            continue;

        if ((pcMesh->fOpacity != 1.0f ? true : false) != (pc->fOpacity != 1.0f ? true : false))
            continue;

        if (pcSource->HasBones() != g_pcAsset->pcScene->mMeshes[i]->HasBones())
            continue;

        // we can reuse this material
        if (pc->piEffect)
        {
            pcMesh->piEffect = pc->piEffect;
            pc->bSharedFX = pcMesh->bSharedFX = true;
            pcMesh->piEffect->AddRef();
            return 2;
        }
    }
    m_iShaderCount++;

    // build macros for the HLSL compiler
    unsigned int iCurrent = 0;
    if (pcMesh->piDiffuseTexture)
    {
        sMacro[iCurrent].Name = "AV_DIFFUSE_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        if (mapU == aiTextureMapMode_Wrap)
            sMacro[iCurrent].Name = "AV_WRAPU";
        else if (mapU == aiTextureMapMode_Mirror)
            sMacro[iCurrent].Name = "AV_MIRRORU";
        else // if (mapU == aiTextureMapMode_Clamp)
            sMacro[iCurrent].Name = "AV_CLAMPU";

        sMacro[iCurrent].Definition = "1";
        ++iCurrent;


        if (mapV == aiTextureMapMode_Wrap)
            sMacro[iCurrent].Name = "AV_WRAPV";
        else if (mapV == aiTextureMapMode_Mirror)
            sMacro[iCurrent].Name = "AV_MIRRORV";
        else // if (mapV == aiTextureMapMode_Clamp)
            sMacro[iCurrent].Name = "AV_CLAMPV";

        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piSpecularTexture)
    {
        sMacro[iCurrent].Name = "AV_SPECULAR_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piAmbientTexture)
    {
        sMacro[iCurrent].Name = "AV_AMBIENT_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piEmissiveTexture)
    {
        sMacro[iCurrent].Name = "AV_EMISSIVE_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    char buff[32];
    if (pcMesh->piLightmapTexture)
    {
        sMacro[iCurrent].Name = "AV_LIGHTMAP_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        int idx;
        if(AI_SUCCESS == aiGetMaterialInteger(pcMat,AI_MATKEY_UVWSRC_LIGHTMAP(0),&idx) && idx >= 1 && pcSource->mTextureCoords[idx])    {
            sMacro[iCurrent].Name = "AV_TWO_UV";
            sMacro[iCurrent].Definition = "1";
            ++iCurrent;

            sMacro[iCurrent].Definition = "IN.TexCoord1";
        }
        else sMacro[iCurrent].Definition = "IN.TexCoord0";
        sMacro[iCurrent].Name = "AV_LIGHTMAP_TEXTURE_UV_COORD";

        ++iCurrent;float f= 1.f;
        aiGetMaterialFloat(pcMat,AI_MATKEY_TEXBLEND_LIGHTMAP(0),&f);
        sprintf(buff,"%f",f);

        sMacro[iCurrent].Name = "LM_STRENGTH";
        sMacro[iCurrent].Definition = buff;
        ++iCurrent;
    }
    if (pcMesh->piNormalTexture && !bib)
    {
        sMacro[iCurrent].Name = "AV_NORMAL_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    if (pcMesh->piOpacityTexture)
    {
        sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        if (pcMesh->piOpacityTexture == pcMesh->piDiffuseTexture)
        {
            sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE_REGISTER_MASK";
            sMacro[iCurrent].Definition = "a";
            ++iCurrent;
        }
        else
        {
            sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE_REGISTER_MASK";
            sMacro[iCurrent].Definition = "r";
            ++iCurrent;
        }
    }

    if (pcMesh->eShadingMode  != aiShadingMode_Gouraud  && !g_sOptions.bNoSpecular)
    {
        sMacro[iCurrent].Name = "AV_SPECULAR_COMPONENT";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;

        if (pcMesh->piShininessTexture)
        {
            sMacro[iCurrent].Name = "AV_SHININESS_TEXTURE";
            sMacro[iCurrent].Definition = "1";
            ++iCurrent;
        }
    }
    if (1.0f != pcMesh->fOpacity)
    {
        sMacro[iCurrent].Name = "AV_OPACITY";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }

    if( pcSource->HasBones())
    {
        sMacro[iCurrent].Name = "AV_SKINNING";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }

    // If a cubemap is active, we'll need to lookup it for calculating
    // a physically correct reflection
    if (CBackgroundPainter::TEXTURE_CUBE == CBackgroundPainter::Instance().GetMode())
    {
        sMacro[iCurrent].Name = "AV_SKYBOX_LOOKUP";
        sMacro[iCurrent].Definition = "1";
        ++iCurrent;
    }
    sMacro[iCurrent].Name = NULL;
    sMacro[iCurrent].Definition = NULL;

    // compile the shader
    if(FAILED( D3DXCreateEffect(g_piDevice,
        g_szMaterialShader.c_str(),(UINT)g_szMaterialShader.length(),
        (const D3DXMACRO*)sMacro,NULL,0,NULL,&pcMesh->piEffect,&piBuffer)))
    {
        // failed to compile the shader
        if( piBuffer)
        {
            MessageBox(g_hDlg,(LPCSTR)piBuffer->GetBufferPointer(),"HLSL",MB_OK);
            piBuffer->Release();
        }
        // use the default material instead
        if (g_piDefaultEffect)
        {
            pcMesh->piEffect = g_piDefaultEffect;
            g_piDefaultEffect->AddRef();
        }

        // get the name of the material and use it in the log message
        if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_NAME,&szPath) &&
            '\0' != szPath.data[0])
        {
            std::string sz = "[ERROR] Unable to load material: ";
            sz.append(szPath.data);
            CLogDisplay::Instance().AddEntry(sz);
        }
        else
        {
            CLogDisplay::Instance().AddEntry("Unable to load material: UNNAMED");
        }
        return 0;
    } else
    {
        // use Fixed Function effect when working with shaderless cards
        if( g_sCaps.PixelShaderVersion < D3DPS_VERSION(2,0))
            pcMesh->piEffect->SetTechnique( "MaterialFX_FF");
    }

    if( piBuffer) piBuffer->Release();


    // now commit all constants to the shader
    //
    // This is not necessary for shared shader. Shader constants for
    // shared shaders are automatically recommited before the shader
    // is being used for a particular mesh

    if (1.0f != pcMesh->fOpacity)
        pcMesh->piEffect->SetFloat("TRANSPARENCY",pcMesh->fOpacity);
    if (pcMesh->eShadingMode  != aiShadingMode_Gouraud && !g_sOptions.bNoSpecular)
    {
        pcMesh->piEffect->SetFloat("SPECULARITY",pcMesh->fShininess);
        pcMesh->piEffect->SetFloat("SPECULAR_STRENGTH",pcMesh->fSpecularStrength);
    }

    pcMesh->piEffect->SetVector("DIFFUSE_COLOR",&pcMesh->vDiffuseColor);
    pcMesh->piEffect->SetVector("SPECULAR_COLOR",&pcMesh->vSpecularColor);
    pcMesh->piEffect->SetVector("AMBIENT_COLOR",&pcMesh->vAmbientColor);
    pcMesh->piEffect->SetVector("EMISSIVE_COLOR",&pcMesh->vEmissiveColor);

    if (pcMesh->piDiffuseTexture)
        pcMesh->piEffect->SetTexture("DIFFUSE_TEXTURE",pcMesh->piDiffuseTexture);
    if (pcMesh->piOpacityTexture)
        pcMesh->piEffect->SetTexture("OPACITY_TEXTURE",pcMesh->piOpacityTexture);
    if (pcMesh->piSpecularTexture)
        pcMesh->piEffect->SetTexture("SPECULAR_TEXTURE",pcMesh->piSpecularTexture);
    if (pcMesh->piAmbientTexture)
        pcMesh->piEffect->SetTexture("AMBIENT_TEXTURE",pcMesh->piAmbientTexture);
    if (pcMesh->piEmissiveTexture)
        pcMesh->piEffect->SetTexture("EMISSIVE_TEXTURE",pcMesh->piEmissiveTexture);
    if (pcMesh->piNormalTexture)
        pcMesh->piEffect->SetTexture("NORMAL_TEXTURE",pcMesh->piNormalTexture);
    if (pcMesh->piShininessTexture)
        pcMesh->piEffect->SetTexture("SHININESS_TEXTURE",pcMesh->piShininessTexture);
    if (pcMesh->piLightmapTexture)
        pcMesh->piEffect->SetTexture("LIGHTMAP_TEXTURE",pcMesh->piLightmapTexture);

    if (CBackgroundPainter::TEXTURE_CUBE == CBackgroundPainter::Instance().GetMode()){
        pcMesh->piEffect->SetTexture("lw_tex_envmap",CBackgroundPainter::Instance().GetTexture());
    }

    return 1;
}
Exemple #28
0
HRESULT CMesh3D::InitMesh( LPCSTR Name, IDirect3DDevice9* pD3DDevice )
{
	if( !pD3DDevice )
	{
		Log( "Error pointer x-file" );
		return E_FAIL;
	}

	m_pD3DDevice = pD3DDevice;	
	ID3DXBuffer* pMaterialBuffer  = 0;

	if ( FAILED( D3DXLoadMeshFromX( Name, D3DXMESH_SYSTEMMEM, m_pD3DDevice, 0, &pMaterialBuffer, 0, &m_TexturCount, &m_pMesh ) ) )
	{				
		Log( "error load x-file" );
		return E_FAIL;		
	}

	Log( "Load x-file" );
	DWORD i = m_pMesh->GetNumFaces();// — Возвращает количество граней (треугольных ячеек) в сетке.

	m_pMesh->GetVertexBuffer( &m_VertexBuffer );
	m_pMesh->GetIndexBuffer(  &m_IndexBuffer  );

	// Извлекаем свойства материала и названия{имена} структуры
	D3DXMATERIAL * MaterialMesh = (D3DXMATERIAL*)pMaterialBuffer->GetBufferPointer();
	m_pMeshMaterial = new D3DMATERIAL9[ m_TexturCount ];

	std::string FilePath( Name );

	size_t f = FilePath.find_last_of( "\\" );
	if( f != -1 )
		FilePath.erase( f + 1, FilePath.size() );

	for ( DWORD i = 0; i < m_TexturCount; i++ )
	{
		// Копируем материал
		m_pMeshMaterial[i] = MaterialMesh[i].MatD3D;

		// Установить окружающего свет
		m_pMeshMaterial[i].Ambient = m_pMeshMaterial[i].Diffuse;

		// Загружаем текстуру
		if( MaterialMesh[i].pTextureFilename )
		{		
			IDirect3DTexture9* Tex = 0;
			std::string FileName = FilePath + std::string( MaterialMesh[i].pTextureFilename );
			if( FAILED( D3DXCreateTextureFromFileEx( m_pD3DDevice, FileName.c_str(), 0, 0, 0, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0xff000000, 0, 0, &Tex ) ) )
			{
				Log( "error load texture Mesh" );
				m_pMeshTextura.push_back(0);
			}

			// Сохраняем загруженную текстуру
			m_pMeshTextura.push_back(Tex);
		}
		else 
		{
			// Нет текстуры для i-ой подгруппы
			m_pMeshTextura.push_back(0);
		}
	}

	// Уничтожаем буфер материала
	pMaterialBuffer->Release();

	return S_OK;
}
bool DX9VertexShaderConstantsCompiler::compile( const std::string& shaderCode, const char* entryFunction, std::vector< ShaderConstantDesc >& outConstants )
{
   // create a renderer
   IDirect3D9* d3d9 = Direct3DCreate9( D3D_SDK_VERSION );
   DX9Initializer initializer( *d3d9 );

   IDirect3DDevice9* compileDevice = initializer.createNullDevice();
   const char* shaderProfile = D3DXGetVertexShaderProfile( compileDevice );

   DWORD flags = D3DXSHADER_DEBUG;

   ID3DXBuffer* shaderBuf = NULL;
   ID3DXBuffer* errorsBuf = NULL;
   ID3DXConstantTable* shaderConstants = NULL;
   DX9ShaderIncludeLoader includesLoader;
   HRESULT res = D3DXCompileShader( shaderCode.c_str(), shaderCode.length(), NULL, &includesLoader, entryFunction, shaderProfile, flags, &shaderBuf, &errorsBuf, &shaderConstants );

   // interpret the results
   bool result = true;
   if ( FAILED(res) || shaderBuf == NULL )
   {
      if ( errorsBuf != NULL )
      {
         std::string compilationErrors = ( const char* )errorsBuf->GetBufferPointer();
         errorsBuf->Release();
         m_errorMsg = std::string( "Shader compilation error: " ) + compilationErrors;
      }
      else
      {
         m_errorMsg = translateDxError( "Error while compiling a shader", res );
      }

      result = false;
   }
   else
   {
      std::vector< D3DXCONSTANT_DESC > constants;
      ShaderConstantDesc newConstant;
      result = ShaderCompilerUtils::parseConstants( shaderConstants, m_errorMsg, constants );
      if ( result )
      {
         unsigned int constantsCount = constants.size();
         for ( unsigned int i = 0; i < constantsCount; ++i )
         {
            if ( createConstant( constants[i], newConstant ) )
            {
               outConstants.push_back( newConstant );
            }
         }
      }
   }

   // cleanup
   if ( shaderConstants )
   {
      shaderConstants->Release();
   }
   compileDevice->Release();
   d3d9->Release();

   return result;
}
Exemple #30
0
//--------------------------------------------------------------------------------------
// Name: Create()
// Desc: Creates the help class' internal objects
//--------------------------------------------------------------------------------------
HRESULT Help::Create( const PackedResource* pResource )
{
    // Get access to the gamepad texture
    m_pGamepadTexture = pResource->GetTexture( "GamepadTexture" );

    // Load the texture used for pointing help text at specific buttons
    m_pLineTexture = pResource->GetTexture( "HelpCalloutTexture" );

    // Create vertex declaration
    if( NULL == g_pHelpVertexDecl )
    {
        static const D3DVERTEXELEMENT9 decl[] =
        {
            { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
            { 0, 8, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
            D3DDECL_END()
        };

        if( FAILED( g_pd3dDevice->CreateVertexDeclaration( decl, &g_pHelpVertexDecl ) ) )
            return E_FAIL;
    }

    // Create vertex shader
    ID3DXBuffer* pShaderCode;
    if( NULL == g_pHelpVertexShader )
    {
        if( FAILED( D3DXCompileShader( g_strHelpShader, strlen( g_strHelpShader ),
                                       NULL, NULL, "HelpVertexShader", "vs.2.0", 0,
                                       &pShaderCode, NULL, NULL ) ) )
            return E_FAIL;

        if( FAILED( g_pd3dDevice->CreateVertexShader( ( DWORD* )pShaderCode->GetBufferPointer(),
                                                      &g_pHelpVertexShader ) ) )
            return E_FAIL;

        pShaderCode->Release();
    }

    // Create pixel shader.
    if( NULL == g_pHelpPixelShader )
    {
        if( FAILED( D3DXCompileShader( g_strHelpShader, strlen( g_strHelpShader ),
                                       NULL, NULL, "HelpPixelShader", "ps.2.0", 0,
                                       &pShaderCode, NULL, NULL ) ) )
            return E_FAIL;

        if( FAILED( g_pd3dDevice->CreatePixelShader( ( DWORD* )pShaderCode->GetBufferPointer(),
                                                     &g_pHelpPixelShader ) ) )
            return E_FAIL;

        pShaderCode->Release();
    }

    if( NULL == g_pDarkPixelShader )
    {
        if( FAILED( D3DXCompileShader( g_strHelpShader, strlen( g_strHelpShader ),
                                       NULL, NULL, "DarkPixelShader", "ps.2.0", 0,
                                       &pShaderCode, NULL, NULL ) ) )
            return E_FAIL;

        if( FAILED( g_pd3dDevice->CreatePixelShader( ( DWORD* )pShaderCode->GetBufferPointer(),
                                                     &g_pDarkPixelShader ) ) )
            return E_FAIL;

        pShaderCode->Release();
    }

    return S_OK;
}