Beispiel #1
0
 HRESULT _stdcall TerminateDevice(DWORD_PTR dwID) {
     if(ptex) {
         ptex->Release();
         ptex=NULL;
     }
     if(surface) {
         surface->Release();
         surface=NULL;
     }
     if(tex) {
         tex->Release();
         tex=NULL;
     }
     return S_OK;
 }
Beispiel #2
0
IDirect3DTexture9 *Blit::copySurfaceToTexture(IDirect3DSurface9 *surface, const RECT &sourceRect)
{
    egl::Display *display = getDisplay();
    IDirect3DDevice9 *device = getDevice();

    D3DSURFACE_DESC sourceDesc;
    surface->GetDesc(&sourceDesc);

    // Copy the render target into a texture
    IDirect3DTexture9 *texture;
    HRESULT result = device->CreateTexture(sourceRect.right - sourceRect.left, sourceRect.bottom - sourceRect.top, 1, D3DUSAGE_RENDERTARGET, sourceDesc.Format, D3DPOOL_DEFAULT, &texture, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
        return error(GL_OUT_OF_MEMORY, (IDirect3DTexture9*)NULL);
    }

    IDirect3DSurface9 *textureSurface;
    result = texture->GetSurfaceLevel(0, &textureSurface);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
        texture->Release();
        return error(GL_OUT_OF_MEMORY, (IDirect3DTexture9*)NULL);
    }

    RECT d3dSourceRect;
    d3dSourceRect.left = sourceRect.left;
    d3dSourceRect.right = sourceRect.right;
    d3dSourceRect.top = sourceRect.top;
    d3dSourceRect.bottom = sourceRect.bottom;

    display->endScene();
    result = device->StretchRect(surface, &d3dSourceRect, textureSurface, NULL, D3DTEXF_NONE);

    textureSurface->Release();

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
        texture->Release();
        return error(GL_OUT_OF_MEMORY, (IDirect3DTexture9*)NULL);
    }

    return texture;
}
void CeguiTextureImage::onRender(const ::bootes::lib::framework::GameTime* gt)
{
   if (_pSceneSeq == NULL) {
      IStageManager* p = g_pGame->getStageManager();
      if (p) { _pSceneSeq = p->getSceneSequencer(); }
   }

   if (_pSceneSeq == NULL) { return; }
   {
      Scene scene = _pSceneSeq->getScene(true);
      if (! scene.isValid()) { return; }

      IDirect3DTexture9* pTex = scene.refTexture();
      _size.d_width  = (float)scene.videoinfo().width;
      _size.d_height = (float)scene.videoinfo().height;
      _time = scene.clock().clock;
      _pCeguiTex->setDirect3D9Texture(pTex);
      _pCeguiTex->setOriginalDataSize(_size);
      if (pTex) {
         pTex->Release();
      }
   }

   CEGUI::Point zero(0,0);
   CEGUI::Imageset& is = CEGUI::ImagesetManager::getSingleton().get(_is_name.c_str());
   t_items::iterator i;
   for (i = _items.begin(); i != _items.end(); ++i) {
      Item* pi = i->second;
      is.undefineImage(pi->im_name.c_str());
      is.defineImage(pi->im_name.c_str(), zero, _size, zero);
   }
}
Beispiel #4
0
void MFTexture_DestroyPlatformSpecific(MFTexture *pTexture)
{
	MFCALLSTACK;

	IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData;
	pTex->Release();
}
Beispiel #5
0
bool Blit::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
{
    IDirect3DTexture9 *texture = copySurfaceToTexture(source, getSurfaceRect(source));
    if (!texture)
    {
        return false;
    }

    IDirect3DDevice9 *device = getDevice();

    saveState();

    device->SetTexture(0, texture);
    device->SetRenderTarget(0, dest);

    setVertexShader(SHADER_VS_STANDARD);
    setPixelShader(SHADER_PS_PASSTHROUGH);

    setCommonBlitState();
    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);

    setViewport(getSurfaceRect(dest), 0, 0);

    render();

    texture->Release();

    restoreState();

    return true;
}
Beispiel #6
0
void RSManager::DoLimbo()
{
	if (!(mainRT && zSurf && doLimbo && limbo)) return;

	IDirect3DSurface9 *oldRenderTarget;
	d3ddev->GetRenderTarget(0, &oldRenderTarget);
	if (oldRenderTarget == mainRT) {
		// final renderbuffer has to be from texture, just making sure here
		if (IDirect3DTexture9* tex = getSurfTexture(oldRenderTarget)) {
			// check size just to make even more sure
			D3DSURFACE_DESC desc;
			oldRenderTarget->GetDesc(&desc);
			if (desc.Width == Settings::get().getRenderWidth() && desc.Height == Settings::get().getRenderHeight()) {
				IDirect3DTexture9 *zTex = getSurfTexture(zSurf);

				storeRenderState();
				d3ddev->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
				d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
				d3ddev->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE);

				/// Draw zbuffer
				limbo->go(zTex, oldRenderTarget, limboZNear, limboZFar);
				SDLOG(0, "ZNear: %g, ZFar: %g\n", limboZNear, limboZFar);
				//d3ddev->StretchRect(zSurf, NULL, oldRenderTarget, NULL, D3DTEXF_NONE);

				restoreRenderState();
				zTex->Release();
			}
			tex->Release();
		}
	}
	oldRenderTarget->Release();
}
Beispiel #7
0
bool Blit::formatConvert(IDirect3DSurface9 *source, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, IDirect3DSurface9 *dest)
{
    IDirect3DTexture9 *texture = copySurfaceToTexture(source, sourceRect);
    if (!texture)
    {
        return false;
    }

    IDirect3DDevice9 *device = getDevice();

    saveState();

    device->SetTexture(0, texture);
    device->SetRenderTarget(0, dest);

    setViewport(sourceRect, xoffset, yoffset);

    setCommonBlitState();
    if (setFormatConvertShaders(destFormat))
    {
        render();
    }

    texture->Release();

    restoreState();

    return true;
}
Beispiel #8
0
/**
*
* @author Jade Abbott
*
*/
bool
CRadialMenu::CreateFinalTexture()
{
	assert(m_pRenderer);

	IDirect3DTexture9* pTexture = 0;
	if (FAILED(m_pRenderer->GetSurfaceManager().CreateTexture(m_uiDiameter,
																m_uiDiameter,
																D3DFMT_A8R8G8B8,
																D3DPOOL_MANAGED,
																&pTexture)))
	{
		return false;
	}

	CTextureManager& rTextureManager = m_pRenderer->GetTextureManager();

	if (m_iFinalTextureID != Utility::INVALID_ID)
	{
		rTextureManager.RemoveTexture(m_iFinalTextureID);
	}

	m_iFinalTextureID = rTextureManager.LoadTextureMemory(pTexture);

	if (m_iFinalTextureID == Utility::INVALID_ID)
	{
		pTexture->Release();
		return false;
	}

	return true;
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void TextureLoader::Unload( void* data )
{
	if( data != NULL )
	{
		IDirect3DTexture9* texture = (IDirect3DTexture9*)data;
		texture->Release();
	}
}
Beispiel #10
0
		void DirectX9::FreeTexture( Gwen::Texture* pTexture )
		{
			IDirect3DTexture9* pImage = ( IDirect3DTexture9* ) pTexture->data;

			if ( !pImage ) { return; }

			pImage->Release();
			pTexture->data = NULL;
			return;
		}
Beispiel #11
0
void RageDisplay_D3D::DeleteTexture( unsigned uTexHandle )
{
	IDirect3DTexture9* pTex = (IDirect3DTexture9*) uTexHandle;
	pTex->Release();

	// Delete palette (if any)
	if( g_TexResourceToPaletteIndex.find(uTexHandle) != g_TexResourceToPaletteIndex.end() )
		g_TexResourceToPaletteIndex.erase( g_TexResourceToPaletteIndex.find(uTexHandle) );
	if( g_TexResourceToTexturePalette.find(uTexHandle) != g_TexResourceToTexturePalette.end() )
		g_TexResourceToTexturePalette.erase( g_TexResourceToTexturePalette.find(uTexHandle) );
}
Beispiel #12
0
void Console::initialize(IDirect3DDevice9* device, int w, int h) {
	SDLOG(0, "Initializing Console on device %p\n", device);
	width = w;
	height = h;
	this->device = device;
	
	// Create font
	SDLOG(2, " - creating console font\n");
	SAFERELEASE(fontTex);
	FILE* ff = fopen(getAssetFileName("font.ttf").c_str(), "rb");
	unsigned char* ttf_buffer = new unsigned char[1<<20];
	unsigned char* temp_bitmap = new unsigned char[BMPSIZE*BMPSIZE];
	fread(ttf_buffer, 1, 1<<20, ff);
	fclose(ff);
	stbtt_BakeFontBitmap(ttf_buffer, 0, 40.0, temp_bitmap, BMPSIZE, BMPSIZE, 32, 96, cdata); // no guarantee this fits!
	device->CreateTexture(BMPSIZE, BMPSIZE, 0, D3DUSAGE_AUTOGENMIPMAP, D3DFMT_A8, D3DPOOL_DEFAULT, &fontTex, NULL);
	IDirect3DTexture9 *tempTex;
	device->CreateTexture(BMPSIZE, BMPSIZE, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_SYSTEMMEM, &tempTex, NULL);
	D3DLOCKED_RECT rect;
	tempTex->LockRect(0, &rect, NULL, 0);
	memcpy(rect.pBits, temp_bitmap, BMPSIZE*BMPSIZE);
	tempTex->UnlockRect(0);
	device->UpdateTexture(tempTex, fontTex);
	tempTex->Release();
	delete ttf_buffer;
	delete temp_bitmap;
	
	// Create vertex decl
	SDLOG(2, " - creating console vertex decl\n");
	SAFERELEASE(vertexDeclaration);
	device->CreateVertexDeclaration(vertexElements , &vertexDeclaration);

	// Load effect from file
	SDLOG(2, " - loading console effect file\n");
	SAFERELEASE(effect);
	vector<D3DXMACRO> defines;
	std::stringstream s;
	D3DXMACRO null = { NULL, NULL };
	defines.push_back(null);
	DWORD flags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_OPTIMIZATION_LEVEL3;

	SDLOG(2, " - actually load effect\n");	
	ID3DXBuffer* errors;
	HRESULT hr = D3DXCreateEffectFromFile(device, getAssetFileName("console.fx").c_str(), &defines.front(), NULL, flags, NULL, &effect, &errors);
	if(hr != D3D_OK) SDLOG(0, "ERRORS:\n %s\n", errors->GetBufferPointer());

	// get handles
	rectColorHandle = effect->GetParameterByName(NULL, "rectColor");
	textTex2DHandle = effect->GetParameterByName(NULL, "textTex2D");

	SDLOG(0, " - done\n");
}
Beispiel #13
0
void RootViewPlay::onRender(const ::bootes::lib::framework::GameTime* gt)
{
   HRESULT hr;
   ::bootes::lib::util::Timer timer;
   int dt[10];
   int ti = 0;

   IDirect3DDevice9* pDev = g_pFnd->getD3D9Device();
   if (pDev == NULL) { return; }
   hr = pDev->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1, 0  );

   timer.start();
   _pGameView->onRender(gt);
   timer.get(NULL, &dt[ti++]);

   timer.start();
   do {
      //IDirect3DTexture9* pTex = scene.refTexture(); //test
      Scene scene = _pGameView->getScene(true);
      IDirect3DTexture9* pTex = scene.refTexture();
      if (pTex == NULL) { break; }
      IDirect3DSurface9* pSrc;
      pTex->GetSurfaceLevel(0, &pSrc);
      
      IDirect3DSurface9* pDst;
      hr = pDev->GetRenderTarget(0, &pDst);

      //hr = pDev->StretchRect(pSrc, NULL, pDst, NULL, D3DTEXF_NONE); //D3DPOOL_DEFUALT
      hr = pDev->UpdateSurface(pSrc, NULL, pDst, NULL); //D3DPOOL_SYSTEM
      if (hr == D3DERR_INVALIDCALL) {
         DbgBreak("");
      }
      pDst->Release();
      pSrc->Release();
      pTex->Release();
   } while(0);
   pDev->EndScene();
   /*
   do {
      ID3DXLine* pLine;
      D3DXCreateLine(pDev, &pLine);
      D3DXVECTOR2 points[] = {
         D3DXVECTOR2(0,0), D3DXVECTOR2(100,100), 
      };
      pLine->Begin();
      pLine->Draw(points, 2, D3DCOLOR_ARGB(255,255,255,255));
      pLine->End();
   } while(0);
   */
   timer.reset();
}
Beispiel #14
0
/// @copydoc Renderer::Shutdown()
void D3D9Renderer::Shutdown()
{
    HELIUM_TRACE( TRACE_INFO, TXT( "Shutting down Direct3D 9 rendering support (D3D9Renderer).\n" ) );

    m_spMainContext.Release();
    m_spImmediateCommandProxy.Release();

    for( size_t mapPoolIndex = 0; mapPoolIndex < HELIUM_ARRAY_COUNT( m_staticTextureMapTargetPools ); ++mapPoolIndex )
    {
        DynArray< IDirect3DTexture9* >* pTextureMapPools = m_staticTextureMapTargetPools[ mapPoolIndex ];

        for( size_t pixelFormatIndex = 0;
            pixelFormatIndex < static_cast< size_t >( RENDERER_PIXEL_FORMAT_MAX );
            ++pixelFormatIndex )
        {
            DynArray< IDirect3DTexture9* >& rPool = pTextureMapPools[ pixelFormatIndex ];

            size_t textureCount = rPool.GetSize();
            for( size_t textureIndex = 0; textureIndex < textureCount; ++textureIndex )
            {
                IDirect3DTexture9* pTexture = rPool[ textureIndex ];
                HELIUM_ASSERT( pTexture );
                pTexture->Release();
            }

            rPool.Clear();
        }
    }

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

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

    m_mainContextWidth = 0;
    m_mainContextHeight = 0;

    m_depthTextureFormat = D3DFMT_UNKNOWN;

    m_featureFlags = 0;

    HELIUM_TRACE( TRACE_INFO, TXT( "Direct3D 9 renderer shutdown complete.\n" ) );
}
Beispiel #15
0
HRESULT APIENTRY hkIDirect3DDevice9::SetTexture(DWORD Stage, IDirect3DBaseTexture9 *pTexture) {
	RSManager::setLatest(rsMan);
	SDLOG(6, "setTexture %d, %p\n", Stage, pTexture);
	if(Settings::get().getLogLevel() > 10 && pTexture) {
		IDirect3DTexture9 *tex;
		if(pTexture->QueryInterface(IID_IDirect3DTexture9, (void**)&tex) == S_OK) {
			D3DSURFACE_DESC desc;
			tex->GetLevelDesc(0, &desc);
			SDLOG(10, " -- size: %dx%d RT? %s\n", desc.Width, desc.Height, (desc.Usage & D3DUSAGE_RENDERTARGET) ? "true" : "false");
			tex->Release();
		}
	}
	return m_pD3Ddev->SetTexture(Stage, pTexture);
}
Beispiel #16
0
void MFTexture_DestroyPlatformSpecific(MFTexture *pTexture)
{
	MFCALLSTACK;

	if(pTexture->flags & TEX_RenderTarget)
	{
		IDirect3DSurface9 *pSurface = (IDirect3DSurface9*)(size_t)pTexture->pSurfaces[0].platformData;
		pSurface->Release();
	}

	if(pTexture->pInternalData)
	{
		IDirect3DTexture9 *pTex = (IDirect3DTexture9*)pTexture->pInternalData;
		pTex->Release();
	}
}
Beispiel #17
0
bool SprConverter::ExportNewFormatFile( const char* pszFileName )
{
	if (!SaveNewSprFile(pszFileName))
	{
		return false;
	}
	for (int  i = 0; i < m_pSprHead->Frames; i++)
	{
		BYTE* pSprExchangeBuffer = NULL;
		pSprExchangeBuffer = new BYTE[m_ppSprFrameList[i]->Width * m_ppSprFrameList[i]->Height * 4]; /* 4? Byte */
		RenderToA8R8G8B8(pSprExchangeBuffer,
			m_ppSprFrameList[i]->Width * sizeof(DWORD),
			m_ppSprFrameList[i]->Sprite,
			m_ppSprFrameList[i]->Width,
			m_ppSprFrameList[i]->Height,
			m_pSprPaList);
		IDirect3DTexture9* pTexture = NULL;
		if (!FAILED(D3DXCreateTexture(g_pd3dDevice, 
			m_ppSprFrameList[i]->Width, 
			m_ppSprFrameList[i]->Height, 
			1, 
			0, 
			D3DFMT_A8R8G8B8,
			D3DPOOL_MANAGED, 
			&pTexture)))
		{
			IDirect3DSurface9* pSurface = NULL;
			RECT rect;
			rect.left = 0;
			rect.top = 0;
			rect.right = m_ppSprFrameList[i]->Width;
			rect.bottom = m_ppSprFrameList[i]->Height;
			pTexture->GetSurfaceLevel(0, &pSurface);
 			D3DXLoadSurfaceFromMemory(pSurface, NULL, NULL, pSprExchangeBuffer,
 				D3DFMT_A8R8G8B8, m_ppSprFrameList[i]->Width * sizeof(DWORD), NULL, &rect,D3DX_DEFAULT, 0);
			SaveDdsFile(pszFileName, i, pTexture);
			pSurface->Release();
			pTexture->Release();
			SAFE_DELETE_ARRAY( pSprExchangeBuffer );
		}
		else
		{
			//Log
		}
	}
	return true;
}
    EGLSurface createPBuffer(size_t width,
                             size_t height,
                             EGLint eglTextureFormat,
                             EGLint eglTextureTarget,
                             UINT sampleCount,
                             UINT sampleQuality)
    {
        if (mD3D11Device)
        {
            return createD3D11PBuffer(
                width, height, eglTextureFormat, eglTextureTarget, sampleCount, sampleQuality,
                D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, DXGI_FORMAT_R8G8B8A8_UNORM);
        }

        if (mD3D9Device)
        {
            EGLWindow *window  = getEGLWindow();
            EGLDisplay display = window->getDisplay();
            EGLConfig config   = window->getConfig();

            EGLint attribs[] = {
                EGL_TEXTURE_FORMAT, eglTextureFormat, EGL_TEXTURE_TARGET,
                eglTextureTarget,   EGL_NONE,         EGL_NONE,
            };

            // Multisampled textures are not supported on D3D9.
            ASSERT(sampleCount <= 1);
            ASSERT(sampleQuality == 0);

            IDirect3DTexture9 *texture = nullptr;
            EXPECT_TRUE(SUCCEEDED(mD3D9Device->CreateTexture(
                static_cast<UINT>(width), static_cast<UINT>(height), 1, D3DUSAGE_RENDERTARGET,
                D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &texture, nullptr)));

            EGLSurface pbuffer = eglCreatePbufferFromClientBuffer(display, EGL_D3D_TEXTURE_ANGLE,
                                                                  texture, config, attribs);

            texture->Release();

            return pbuffer;
        }
        else
        {
            return EGL_NO_SURFACE;
        }
    }
HRESULT CSurfaceQueueDeviceD3D9::CopySurface(IUnknown* pDst, IUnknown* pSrc, UINT width, UINT height)
{
    ASSERT(pDst);
    ASSERT(pSrc);
    ASSERT(m_pDevice);

    HRESULT             hr          = S_OK;
    IDirect3DSurface9*  pSrcSurf    = NULL;
    IDirect3DSurface9*  pDstSurf    = NULL;
    IDirect3DTexture9*  pSrcTex     = NULL;
    RECT                rect        = {0, 0, width, height };
   
    // The source should be a IDirect3DTexture9.  We need to QI for it and then get the
    // top most surface from it.
    if (FAILED(hr = pSrc->QueryInterface(__uuidof(IDirect3DTexture9), (void**)&pSrcTex)))
    {
        goto end;
    }
    if (FAILED(hr = pSrcTex->GetSurfaceLevel(0, &pSrcSurf)))
    {
        goto end;
    }
    // The dst is a IDirect3DSurface9 so we can simply QI for it.
    if (FAILED(hr = pDst->QueryInterface(__uuidof(IDirect3DSurface9), (void**)&pDstSurf)))
    {
        goto end;
    }

    hr = m_pDevice->StretchRect(pSrcSurf, &rect, pDstSurf, &rect, D3DTEXF_NONE);

end:
    if (pSrcTex)
    {
        pSrcTex->Release();
    }
    if (pSrcSurf)
    {
        pSrcSurf->Release();
    }
    if (pDstSurf)
    {
        pDstSurf->Release();
    }
    return hr;
}
static inline bool d3d9_shtex_init_copytex()
{
	uint8_t *patch_addr = get_d3d9_patch_addr(data.d3d9, data.patch);
	uint8_t saved_data[MAX_PATCH_SIZE];
	size_t patch_size = 0;
	IDirect3DTexture9 *tex;
	DWORD protect_val;
	HRESULT hr;

	if (patch_addr) {
		patch_size = patch[data.patch].size;
		VirtualProtect(patch_addr, patch_size, PAGE_EXECUTE_READWRITE,
				&protect_val);
		memcpy(saved_data, patch_addr, patch_size);
		memcpy(patch_addr, patch[data.patch].data, patch_size);
	}

	hr = data.device->CreateTexture(data.cx, data.cy, 1,
			D3DUSAGE_RENDERTARGET, data.d3d9_format,
			D3DPOOL_DEFAULT, &tex, &data.handle);

	if (patch_addr && patch_size) {
		memcpy(patch_addr, saved_data, patch_size);
		VirtualProtect(patch_addr, patch_size, protect_val,
				&protect_val);
	}

	if (FAILED(hr)) {
		hlog_hr("d3d9_shtex_init_copytex: Failed to create shared texture",
				hr);
		return false;
	}

	hr = tex->GetSurfaceLevel(0, &data.d3d9_copytex);
	tex->Release();

	if (FAILED(hr)) {
		hlog_hr("d3d9_shtex_init_copytex: Failed to get surface level", hr);
		return false;
	}

	return true;
}
Beispiel #21
0
HRESULT HEIGHTMAP::LoadFromFile(IDirect3DDevice9* Device, char fileName[])
{
	try
	{
		//Reset the heightMap to 0.0f
		memset(m_pHeightMap, 0, sizeof(float) * m_size.x * m_size.y);

		//Initiate the texture variables
		IDirect3DTexture9 *heightMapTexture = NULL;
		D3DXIMAGE_INFO info;

		//Load the texture (and scale it to our heightMap m_size)
		if(FAILED(D3DXCreateTextureFromFileEx(Device, fileName, m_size.x, m_size.y, 1, D3DUSAGE_DYNAMIC, 
											D3DFMT_L8, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 
											NULL, &info, NULL, &heightMapTexture)))return E_FAIL;

		//Lock the texture
		D3DLOCKED_RECT sRect;
		heightMapTexture->LockRect(0, &sRect, NULL, NULL);
		BYTE *bytes = (BYTE*)sRect.pBits;

		//Extract height values from the texture
		for(int y=0;y<m_size.y;y++)
			for(int x=0;x<m_size.x;x++)
				{
					BYTE *b = bytes + y * sRect.Pitch + x;
					m_pHeightMap[x + y * m_size.x] = (*b / 255.0f) * m_maxHeight;
				}
						
		//Unlock the texture
		heightMapTexture->UnlockRect(0);

		//Release texture
		heightMapTexture->Release();
	}
	catch(...)
	{
		debug.Print("Error in HEIGHTMAP::LoadFromFile()");
	}

	return S_OK;
}
Beispiel #22
0
HRESULT APIENTRY hkIDirect3DDevice9::SetTexture(DWORD Stage, IDirect3DBaseTexture9 *pTexture) {
	RSManager::setLatest(rsMan);
	SDLOG(6, "setTexture %d, %p\n", Stage, pTexture);
	if(pTexture != NULL && Settings::get().getEnableAlternativeTextureDumping()) {
		void *unused;
		if(pTexture->QueryInterface(IID_GedosatoTexture, &unused) == S_OK) {
			pTexture = reinterpret_cast<hkIDirect3DTexture9*>(pTexture)->m_pWrapped;
			SDLOG(6, " - wrapper for %p\n", pTexture);
		}
	}
	if(Settings::get().getLogLevel() > 10 && pTexture) {
		IDirect3DTexture9 *tex;
		if(pTexture->QueryInterface(IID_IDirect3DTexture9, (void**)&tex) == S_OK) {
			D3DSURFACE_DESC desc;
			tex->GetLevelDesc(0, &desc);
			SDLOG(10, " -- size: %dx%d RT? %s\n", desc.Width, desc.Height, (desc.Usage & D3DUSAGE_RENDERTARGET) ? "true" : "false");
			tex->Release();
		}
	}
	return m_pD3Ddev->SetTexture(Stage, pTexture);
}
Beispiel #23
0
void Terrain::Initialize(const char* rawfile, const char* texfile)
{
	std::ifstream heightStream;
	heightStream.open(rawfile, std::ios::binary);
	if (heightStream.fail()) return;

	heightStream.seekg(0, std::ios::end);
	UINT numVertices = (UINT)heightStream.tellg();

	heightStream.seekg(0, std::ios::beg);
	m_spHeightMap.reset(new UCHAR[numVertices]);
	heightStream.read((char*)m_spHeightMap.get(), numVertices);
	heightStream.close();

	IDirect3DTexture9* tex;
	D3DXCreateTextureFromFile(d3dContext->GetDevice().get(), texfile, &tex);
	m_spTexture.reset(tex, [](IDirect3DTexture9* tex){tex->Release(); });

	AlllocateBuffers();
	m_bDirty = true;
	Update(0);
}
HRESULT CSurfaceQueueDeviceD3D9::GetSharedHandle(IUnknown* pUnknown, HANDLE* pHandle)
{
    ASSERT(pUnknown);
    ASSERT(pHandle);
    
    HRESULT hr = S_OK;
    
    *pHandle = NULL;
    IDirect3DTexture9* pTexture;

    if (FAILED(hr = pUnknown->QueryInterface(__uuidof(IDirect3DTexture9), (void**)&pTexture)))
    {
        return hr;
    }

    DWORD size = sizeof(HANDLE);

    hr = pTexture->GetPrivateData(SharedHandleGuid, pHandle, &size);
    pTexture->Release();

    return hr;
}
Beispiel #25
0
//-----------------------------------------------------------------------------
HRESULT CDXUTMesh::CreateMaterials( LPCWSTR strPath, IDirect3DDevice9 *pd3dDevice, D3DXMATERIAL* d3dxMtrls, DWORD dwNumMaterials )
{
    // Get material info for the mesh
    // Get the array of materials out of the buffer
    m_dwNumMaterials = dwNumMaterials;
    if( d3dxMtrls && m_dwNumMaterials > 0 )
    {
        // Allocate memory for the materials and textures
        m_pMaterials = new D3DMATERIAL9[m_dwNumMaterials];
        if( m_pMaterials == NULL )
            return E_OUTOFMEMORY;
        m_pTextures = new LPDIRECT3DBASETEXTURE9[m_dwNumMaterials];
        if( m_pTextures == NULL )
            return E_OUTOFMEMORY;
        m_strMaterials = new CHAR[m_dwNumMaterials][MAX_PATH];
        if( m_strMaterials == NULL )
            return E_OUTOFMEMORY;

        // Copy each material and create its texture
        for( DWORD i=0; i<m_dwNumMaterials; i++ )
        {
            // Copy the material
            m_pMaterials[i]         = d3dxMtrls[i].MatD3D;
            m_pTextures[i]          = NULL;

            // Create a texture
            if( d3dxMtrls[i].pTextureFilename )
            {
                StringCchCopyA( m_strMaterials[i], MAX_PATH, d3dxMtrls[i].pTextureFilename );

                WCHAR strTexture[MAX_PATH];
                WCHAR strTextureTemp[MAX_PATH];
                D3DXIMAGE_INFO ImgInfo;

                // First attempt to look for texture in the same folder as the input folder.
                MultiByteToWideChar( CP_ACP, 0, d3dxMtrls[i].pTextureFilename, -1, strTextureTemp, MAX_PATH );
                strTextureTemp[MAX_PATH-1] = 0;

                StringCchCopy( strTexture, MAX_PATH, strPath );
                StringCchCat( strTexture, MAX_PATH, strTextureTemp );

                // Inspect the texture file to determine the texture type.
                if( FAILED( D3DXGetImageInfoFromFile( strTexture, &ImgInfo ) ) )
                {
                    // Search the media folder
                    if( FAILED( DXUTFindDXSDKMediaFileCch( strTexture, MAX_PATH, strTextureTemp ) ) )
                        continue;  // Can't find. Skip.

                    D3DXGetImageInfoFromFile( strTexture, &ImgInfo );
                }

                // Call the appropriate loader according to the texture type.
                switch( ImgInfo.ResourceType )
                {
                    case D3DRTYPE_TEXTURE:
                    {
                        IDirect3DTexture9 *pTex;
                        if( SUCCEEDED( D3DXCreateTextureFromFile( pd3dDevice, strTexture, &pTex ) ) )
                        {
                            // Obtain the base texture interface
                            pTex->QueryInterface( IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i] );
                            // Release the specialized instance
                            pTex->Release();
                        }
                        break;
                    }
                    case D3DRTYPE_CUBETEXTURE:
                    {
                        IDirect3DCubeTexture9 *pTex;
                        if( SUCCEEDED( D3DXCreateCubeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) )
                        {
                            // Obtain the base texture interface
                            pTex->QueryInterface( IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i] );
                            // Release the specialized instance
                            pTex->Release();
                        }
                        break;
                    }
                    case D3DRTYPE_VOLUMETEXTURE:
                    {
                        IDirect3DVolumeTexture9 *pTex;
                        if( SUCCEEDED( D3DXCreateVolumeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) )
                        {
                            // Obtain the base texture interface
                            pTex->QueryInterface( IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i] );
                            // Release the specialized instance
                            pTex->Release();
                        }
                        break;
                    }
                }
            }
        }
    }
    return S_OK;
}
Beispiel #26
0
void ConvertImageFileToBMPBuffer(string szSrcFileName, LPBYTE * bytes, long* len)
{
	if(!FileExists(szSrcFileName))
		return;

	ATG::Timer m_Timer;

	double timeA = m_Timer.GetAbsoluteTime();

	IDirect3DTexture9 * pTexture;
	HRESULT retVal = D3DXCreateTextureFromFileEx(
		CFreestyleApp::getInstance().m_pd3dDevice,
		szSrcFileName.c_str(),
		D3DX_DEFAULT_NONPOW2,
		D3DX_DEFAULT_NONPOW2,
		1,
		D3DUSAGE_CPU_CACHED_MEMORY,
		D3DFMT_LIN_A8R8G8B8,
		D3DPOOL_DEFAULT,
		D3DX_FILTER_NONE,
		D3DX_FILTER_NONE,
		0,
		NULL,
		NULL,
		&pTexture
	);


	float timeB = m_Timer.GetAbsoluteTime();
	DebugMsg("Test", "Texture Creation:  %4.2f", (timeB- timeA));

	if(retVal == S_OK) {
		timeA = m_Timer.GetAbsoluteTime();

		// Get our level desc
		D3DSURFACE_DESC desc;
		pTexture->GetLevelDesc(0, &desc);

		// Now lock our data
		D3DLOCKED_RECT lock;
		RECT rect = {0, 0, desc.Width, desc.Height};
		pTexture->LockRect(0, &lock, &rect, D3DLOCK_READONLY);
	
		//Read our data
		DWORD headerSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
		DWORD dataLen = lock.Pitch * desc.Height;
		DWORD * dataBuffer = (DWORD*)malloc( dataLen + headerSize );
		DWORD * address = (DWORD*)lock.pBits;

		// Create file our header
		BITMAPFILEHEADER* fHead = (BITMAPFILEHEADER*)dataBuffer;
		fHead->bfType = 0x424D; // "BM"
		fHead->bfSize = SwapDWORD(dataLen + headerSize);
		fHead->bfReserved1 = 0;
		fHead->bfReserved2 = 0;
		fHead->bfOffBits = SwapDWORD(headerSize);

		// Create our info header
		BITMAPINFOHEADER* iHead = (BITMAPINFOHEADER*)(fHead + 1);
		ZeroMemory(iHead, sizeof(BITMAPINFOHEADER));
		iHead->biSize = SwapDWORD(sizeof(BITMAPINFOHEADER));
		iHead->biWidth = SwapDWORD(desc.Width);
		iHead->biHeight = SwapDWORD(desc.Height);
		iHead->biPlanes = SwapWORD(1);
		iHead->biBitCount = SwapWORD(32);
		iHead->biSizeImage = SwapDWORD(dataLen);

		// Copy over our raw (BGRA)
		DWORD* rawPtr = (DWORD*)(iHead + 1);
		for(int y = desc.Height - 1; y >= 0; y--) {
			for(DWORD x = 0; x < desc.Width; x++) {

				DWORD cp = (y * lock.Pitch) + (x * 4);
				DWORD * temp = (DWORD*)(address + (cp / 4));
				*rawPtr = SwapDWORD(*temp);				
				rawPtr++;
			}
		}
		
		// Unlock our texture
		pTexture->UnlockRect(0);

		timeB = m_Timer.GetAbsoluteTime();
		DebugMsg("Test", "Texture Lock Time:  %4.2f", (timeB- timeA));
		
		*len = (headerSize + dataLen);
		*bytes = (BYTE*)dataBuffer;
	}else {
		DebugMsg("ConvertImageInMemoryToBMPBuffer", 
			"Conversion To BMP From Memory Failed. [%X]", retVal);		
	}

	// Release our Texture
	if(pTexture != NULL)
		pTexture->Release();
}
Beispiel #27
0
//-------------------------------------------------------------------------------
void CMaterialManager::HMtoNMIfNecessary(
    IDirect3DTexture9* piTexture,
    IDirect3DTexture9** piTextureOut,
    bool bWasOriginallyHM)
{
    ai_assert(NULL != piTexture);
    ai_assert(NULL != piTextureOut);

    bool bMustConvert = false;
    uintptr_t iElement = 3;

    *piTextureOut = piTexture;

    // Lock the input texture and try to determine its type.
    // Criteria:
    // - If r,g,b channel are identical it MUST be a height map
    // - If one of the rgb channels is used and the others are empty it
    //   must be a height map, too.
    // - If the average color of the whole image is something inside the
    //   purple range we can be sure it is a normal map
    //
    // - Otherwise we assume it is a normal map
    // To increase performance we take not every pixel

    D3DLOCKED_RECT sRect;
    D3DSURFACE_DESC sDesc;
    piTexture->GetLevelDesc(0,&sDesc);
    if (FAILED(piTexture->LockRect(0,&sRect,NULL,D3DLOCK_READONLY)))
    {
        return;
    }
    const int iPitchDiff = (int)sRect.Pitch - (int)(sDesc.Width * 4);

    struct SColor
    {
        union
        {
            struct {unsigned char b,g,r,a;};
            char _array[4];
        };
    };
    const SColor* pcData = (const SColor*)sRect.pBits;

    union
    {
        const SColor* pcPointer;
        const unsigned char* pcCharPointer;
    };
    pcPointer = pcData;

    // 1. If r,g,b channel are identical it MUST be a height map
    bool bIsEqual = true;
    for (unsigned int y = 0; y <  sDesc.Height;++y)
    {
        for (unsigned int x = 0; x <  sDesc.Width;++x)
        {
            if (pcPointer->b != pcPointer->r || pcPointer->b != pcPointer->g)
            {
                bIsEqual = false;
                break;
            }
            pcPointer++;
        }
        pcCharPointer += iPitchDiff;
    }
    if (bIsEqual)bMustConvert = true;
    else
    {
        // 2. If one of the rgb channels is used and the others are empty it
        //    must be a height map, too.
        pcPointer = pcData;
        while (*pcCharPointer == 0)pcCharPointer++;

        iElement = (uintptr_t)(pcCharPointer - (unsigned char*)pcData) % 4;
        unsigned int aiIndex[3] = {0,1,2};
        if (3 != iElement)aiIndex[iElement] = 3;

        pcPointer = pcData;

        bIsEqual = true;
        if (3 != iElement)
        {
            for (unsigned int y = 0; y <  sDesc.Height;++y)
            {
                for (unsigned int x = 0; x <  sDesc.Width;++x)
                {
                    for (unsigned int ii = 0; ii < 3;++ii)
                    {
                        // don't take the alpha channel into account.
                        // if the texture was stored n RGB888 format D3DX has
                        // converted it to ARGB8888 format with a fixed alpha channel
                        if (aiIndex[ii] != 3 && pcPointer->_array[aiIndex[ii]] != 0)
                        {
                            bIsEqual = false;
                            break;
                        }
                    }
                    pcPointer++;
                }
                pcCharPointer += iPitchDiff;
            }
            if (bIsEqual)bMustConvert = true;
            else
            {
                // If the average color of the whole image is something inside the
                // purple range we can be sure it is a normal map

                // (calculate the average color line per line to prevent overflows!)
                pcPointer = pcData;
                aiColor3D clrColor;
                for (unsigned int y = 0; y <  sDesc.Height;++y)
                {
                    aiColor3D clrColorLine;
                    for (unsigned int x = 0; x <  sDesc.Width;++x)
                    {
                        clrColorLine.r += pcPointer->r;
                        clrColorLine.g += pcPointer->g;
                        clrColorLine.b += pcPointer->b;
                        pcPointer++;
                    }
                    clrColor.r += clrColorLine.r /= (float)sDesc.Width;
                    clrColor.g += clrColorLine.g /= (float)sDesc.Width;
                    clrColor.b += clrColorLine.b /= (float)sDesc.Width;
                    pcCharPointer += iPitchDiff;
                }
                clrColor.r /= (float)sDesc.Height;
                clrColor.g /= (float)sDesc.Height;
                clrColor.b /= (float)sDesc.Height;

                if (!(clrColor.b > 215 &&
                    clrColor.r > 100 && clrColor.r < 140 &&
                    clrColor.g > 100 && clrColor.g < 140))
                {
                    // Unable to detect. Believe the original value obtained from the loader
                    if (bWasOriginallyHM)
                    {
                        bMustConvert = true;
                    }
                }
            }
        }
    }

    piTexture->UnlockRect(0);

    // if the input data is assumed to be a height map we'll
    // need to convert it NOW
    if (bMustConvert)
    {
        D3DSURFACE_DESC sDesc;
        piTexture->GetLevelDesc(0, &sDesc);

        IDirect3DTexture9* piTempTexture;
        if(FAILED(g_piDevice->CreateTexture(
            sDesc.Width,
            sDesc.Height,
            piTexture->GetLevelCount(),
            sDesc.Usage,
            sDesc.Format,
            sDesc.Pool, &piTempTexture, NULL)))
        {
            CLogDisplay::Instance().AddEntry(
                "[ERROR] Unable to create normal map texture",
                D3DCOLOR_ARGB(0xFF,0xFF,0x0,0x0));
            return;
        }

        DWORD dwFlags;
        if (3 == iElement)dwFlags = D3DX_CHANNEL_LUMINANCE;
        else if (2 == iElement)dwFlags = D3DX_CHANNEL_RED;
        else if (1 == iElement)dwFlags = D3DX_CHANNEL_GREEN;
        else /*if (0 == iElement)*/dwFlags = D3DX_CHANNEL_BLUE;

        if(FAILED(D3DXComputeNormalMap(piTempTexture,
            piTexture,NULL,0,dwFlags,1.0f)))
        {
            CLogDisplay::Instance().AddEntry(
                "[ERROR] Unable to compute normal map from height map",
                D3DCOLOR_ARGB(0xFF,0xFF,0x0,0x0));

            piTempTexture->Release();
            return;
        }
        *piTextureOut = piTempTexture;
        piTexture->Release();
    }
}
Beispiel #28
0
// TexturedSquare
TexturedSquare::TexturedSquare(LPDIRECT3DDEVICE9 device, const D3DXVECTOR3& vect, const D3DXVECTOR3& shift, float size, std::vector<LPCWSTR> mipmapFilenames)
: TexturedObject(device) {

    std::vector<TEXTURE_VERTEX_WITH_NORMAL> vertices;
    D3DXVECTOR3 normal = vect;
    D3DXVec3Normalize(&normal, &normal);

    const int n = 10;
    const float min = -size / 2;
    const float max = size / 2;
    const float step = size / n;

    for (float u = min; u < max; u += step)
    {
        for (float v = min; v < max; v += step)
        {
            D3DXVECTOR3 u1, u2, u3, u4;
            if (normal.y != 0) {
                u1 = { u + shift.x, -(normal.x * u + normal.z * v) / normal.y + shift.y, v + shift.z };
                u2 = { u + step + shift.x, -(normal.x * (u + step) + normal.z * v) / normal.y + shift.y, v + shift.z };
                u3 = { u + shift.x, -(normal.x * u + normal.z * (v + step)) / normal.y + shift.y, v + step + shift.z };
                u4 = { u + step + shift.x, -(normal.x * (u + step) + normal.z * (v + step)) / normal.y + shift.y, v + step + shift.z };
            }
            else if (normal.z != 0) {
                u1 = { u + shift.x, v + shift.y, -(normal.x * u + normal.y * v) / normal.z + shift.z };
                u2 = { u + step + shift.x, v + shift.y, -(normal.x * (u + step) + normal.y * v) / normal.z + shift.z };
                u3 = { u + shift.x, v + step + shift.y, -(normal.x * u + normal.y * (v + step)) / normal.z + shift.z };
                u4 = { u + step + shift.x, v + step + shift.y, -(normal.x * (u + step) + normal.y * (v + step)) / normal.z + shift.z };
            }
            else if (normal.x != 0) {
                u1 = { -(normal.y * u + normal.z * v) / normal.x + shift.x, u + shift.y, v + shift.z };
                u2 = { -(normal.y * (u + step) + normal.z * v) / normal.x + shift.x, u + step + shift.y, v + shift.z };
                u3 = { -(normal.y * u + normal.z * (v + step)) / normal.x + shift.x, u + shift.y, v + step + shift.z };
                u4 = { -(normal.y * (u + step) + normal.z * (v + step)) / normal.x + shift.x, u + step + shift.y, v + step + shift.z };
            }

            TEXTURE_VERTEX_WITH_NORMAL v1 = { u1.x, u1.y, u1.z, normal, u / size + 0.5f, v / size + 0.5f};
            TEXTURE_VERTEX_WITH_NORMAL v2 = { u2.x, u2.y, u2.z, normal, (u + step) / size + 0.5f, v / size + 0.5f };
            TEXTURE_VERTEX_WITH_NORMAL v3 = { u3.x, u3.y, u3.z, normal, u / size + 0.5f, (v + step) / size + 0.5f };
            TEXTURE_VERTEX_WITH_NORMAL v4 = { u4.x, u4.y, u4.z, normal, (u + step) / size + 0.5f, (v + step) / size + 0.5f };

            vertices.push_back(v1);
            vertices.push_back(v2);
            vertices.push_back(v3);

            vertices.push_back(v3);
            vertices.push_back(v2);
            vertices.push_back(v4);
        }
    }
    const UINT width = D3DX_DEFAULT;
    const UINT height = D3DX_DEFAULT;
    IDirect3DTexture9* prevTexture = NULL;

    D3DXCreateTexture(d3dDevice, width, height, mipmapFilenames.size(), 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &this->pTexture);
    D3DXCreateTexture(d3dDevice, width, height, mipmapFilenames.size(), 0, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &prevTexture);

    for (int i = 0; i < (int) mipmapFilenames.size(); ++i)
    {
        IDirect3DSurface9 *pSurf;
        prevTexture->GetSurfaceLevel(i, &pSurf);
        D3DXLoadSurfaceFromFile(pSurf, NULL, NULL, mipmapFilenames[i], NULL, D3DX_DEFAULT, 0, NULL);
        pSurf->Release();
    }

    d3dDevice->UpdateTexture(prevTexture, pTexture);
    prevTexture->Release();

    setVertices(vertices);
}
Beispiel #29
0
//----------------------------------------------------------------------------
void PdrRenderTarget::ReadColor (int i, Renderer* renderer,
    Texture2D*& texture)
{
    if (i < 0 || i >= mNumTargets)
    {
        assertion(false, "Invalid target index.\n");
        return;
    }

    IDirect3DDevice9* device = renderer->mData->mDevice;
    HRESULT hr;
    WM5_UNUSED(hr);

    // Enable the input render target surface.
    if (i == 0)
    {
        hr = device->GetRenderTarget(0, &mSaveColorSurface);
        assertion(hr == D3D_OK, "Failed to get old rt 0 color surface: %s\n",
            DXGetErrorString(hr));
    }

    hr = device->SetRenderTarget((DWORD)i, mColorSurfaces[i]);
    assertion(hr == D3D_OK,
        "Failed to set new rt %d color surface: %s\n", i,
        DXGetErrorString(hr));

    // Make a duplicate in system memory.
    IDirect3DTexture9* copyTexture = 0;
    hr = D3DXCreateTexture
    (
        device,
        (UINT)mWidth,
        (UINT)mHeight,
        0,
        0,
        gDX9TextureFormat[mFormat],
        D3DPOOL_SYSTEMMEM,
        &copyTexture
    );
    assertion(hr == D3D_OK,
        "Failed to create copy texture: %s\n",
        DXGetErrorString(hr));

    // Get the surface associated with the copy.
    IDirect3DSurface9* copySurface = 0;
    hr = copyTexture->GetSurfaceLevel(0, &copySurface);
    assertion(hr == D3D_OK,
        "Failed to get surface level for copy texture: %s\n",
        DXGetErrorString(hr));

    // Copy the render target surface.
    hr = device->GetRenderTargetData(mColorSurfaces[i], copySurface);
    assertion(hr == D3D_OK,
        "Failed to copy the rt %d surface: %s\n", i,
        DXGetErrorString(hr));

    // Get the data to write to disk.
    D3DLOCKED_RECT rect;
    hr = copySurface->LockRect(&rect, 0, 0);
    assertion(hr == D3D_OK,
        "Failed to lock copy surface: %s\n",
        DXGetErrorString(hr));

    if (texture)
    {
        if (texture->GetFormat() != mFormat ||
            texture->GetWidth() != (int)mWidth ||
            texture->GetHeight() != (int)mHeight)
        {
            assertion(false, "Incompatible texture.\n");
            delete0(texture);
            texture = new0 Texture2D(mFormat, mWidth, mHeight, 1);
        }
    }
    else
    {
        texture = new0 Texture2D(mFormat, mWidth, mHeight, 1);
    }
    memcpy(texture->GetData(0), rect.pBits, texture->GetNumLevelBytes(0));

    hr = copySurface->UnlockRect();
    assertion(hr == D3D_OK,
        "Failed to unlock copy surface: %s\n",
        DXGetErrorString(hr));

    copySurface->Release();
    copyTexture->Release();

    // Restore the previous render target surface.
    if (i == 0)
    {
        hr = device->SetRenderTarget(0, mSaveColorSurface);
        assertion(hr == D3D_OK,
            "Failed to set old rt 0 color surface: %s\n",
            DXGetErrorString(hr));

        mSaveColorSurface->Release();
    }
}
Beispiel #30
0
bool CAXModel::Load(const char* strFileName)
{
	this->Unload();

	m_strFile = strFileName;

	LPD3DXBUFFER pAdjacencyBuffer = NULL;
	LPD3DXBUFFER pMtrlBuffer = NULL;
	if (FAILED(D3DXLoadMeshFromXA(m_strFile.c_str(), D3DXMESH_MANAGED, APROJECT_WINDOW->GetD3DDevice(), &pAdjacencyBuffer, &pMtrlBuffer, NULL, &m_dwNumMaterials, &m_pMeshObject)))
		return false;

	// Optimize the mesh for performance
	if (FAILED(m_pMeshObject->OptimizeInplace(D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL)))
	{
		SAFE_RELEASE(pAdjacencyBuffer);
		SAFE_RELEASE(pMtrlBuffer);
		return false;
	}

	D3DXMATERIAL* d3dxMtrls = (D3DXMATERIAL*)pMtrlBuffer->GetBufferPointer();
	do
	{
		if (d3dxMtrls && m_dwNumMaterials > 0)
		{
			// Allocate memory for the materials and textures
			m_pMaterials = new D3DMATERIAL9[m_dwNumMaterials];
			if (m_pMaterials == NULL)
				break;

			m_pTextures = new LPDIRECT3DBASETEXTURE9[m_dwNumMaterials];
			if (m_pTextures == NULL)
				break;

			m_strMaterials = new CHAR[m_dwNumMaterials][MAX_PATH];
			if (m_strMaterials == NULL)
				break;

			// Copy each material and create its texture
			for (DWORD i = 0; i < m_dwNumMaterials; i++)
			{
				// Copy the material
				m_pMaterials[i] = d3dxMtrls[i].MatD3D;
				m_pTextures[i] = NULL;

				// Create a texture
				if (d3dxMtrls[i].pTextureFilename)
				{
					strcpy_s(m_strMaterials[i], MAX_PATH, d3dxMtrls[i].pTextureFilename);

					CHAR strTexture[MAX_PATH];
					D3DXIMAGE_INFO ImgInfo;

					// First attempt to look for texture in the same folder as the input folder.
					int p = 0;
					strcpy_s(strTexture, MAX_PATH, m_strFile.c_str());
					for (DWORD j = 0; j < strlen(strTexture); j++)
					{
						if (strTexture[j] == '/')
							p = j;
					}
					strTexture[p + 1] = 0;
					strcat_s(strTexture, MAX_PATH, d3dxMtrls[i].pTextureFilename);

					// Inspect the texture file to determine the texture type.
					if (FAILED(D3DXGetImageInfoFromFileA(strTexture, &ImgInfo)))
						continue;

					// Call the appropriate loader according to the texture type.
					switch (ImgInfo.ResourceType)
					{
						case D3DRTYPE_TEXTURE:
						{
							IDirect3DTexture9* pTex;
							if (SUCCEEDED(D3DXCreateTextureFromFileA(APROJECT_WINDOW->GetD3DDevice(), strTexture, &pTex)))
							{
								pTex->QueryInterface(IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i]);
								pTex->Release();
							}
							break;
						}

						case D3DRTYPE_CUBETEXTURE:
						{
							IDirect3DCubeTexture9* pTex;
							if (SUCCEEDED(D3DXCreateCubeTextureFromFileA(APROJECT_WINDOW->GetD3DDevice(), strTexture, &pTex)))
							{
								pTex->QueryInterface(IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i]);
								pTex->Release();
							}
							break;
						}

						case D3DRTYPE_VOLUMETEXTURE:
						{
							IDirect3DVolumeTexture9* pTex;
							if (SUCCEEDED(D3DXCreateVolumeTextureFromFileA(APROJECT_WINDOW->GetD3DDevice(), strTexture, &pTex)))
							{
								pTex->QueryInterface(IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i]);
								pTex->Release();
							}
							break;
						}
					}
				}
			}
		}
	} while (0);

	// Extract data from m_pMesh for easy access
	D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
	m_dwNumVertices = m_pMeshObject->GetNumVertices();
	m_dwNumFaces = m_pMeshObject->GetNumFaces();
	m_dwBytesPerVertex = m_pMeshObject->GetNumBytesPerVertex();
	m_pMeshObject->GetIndexBuffer(&m_pIB);
	m_pMeshObject->GetVertexBuffer(&m_pVB);
	m_pMeshObject->GetDeclaration(decl);
	APROJECT_WINDOW->GetD3DDevice()->CreateVertexDeclaration(decl, &m_pDecl);

	SAFE_RELEASE(pAdjacencyBuffer);
	SAFE_RELEASE(pMtrlBuffer);

	return true;
}