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;
}
void AtlasTexChunk::writeDDS(Stream *s)
{
    // Load the DDS into a texture, then use D3DX to write it out.
    GFXTexHandle tex;
    tex.set(dds, &GFXDefaultStaticDiffuseProfile, false, avar("%s - %s", __FUNCTION__, ( const char* ) dds->mSourcePath.getFullPath() ) );
    GFXD3D9TextureObject *gdto = (GFXD3D9TextureObject *)tex.getPointer();

    // Write to buffer.
    ID3DXBuffer *buffer = NULL;
    GFXD3DX.D3DXSaveTextureToFileInMemory(&buffer, D3DXIFF_DDS, gdto->getTex(), NULL);

    // And write that buffer... to a stream. Ho ho ho!
    s->write(buffer->GetBufferSize(), buffer->GetBufferPointer());
}
Exemple #3
0
static sBool sCompileDX9(sCompileResult &result, sInt stype, sInt dtype, sInt flags, const sChar8 *src, sInt len, const sChar8 *name)
{
#if sCOMP_DX9_ENABLE
  ID3DXBuffer *bytecode;

  sRelease(result.D3D9.CTable);
  sRelease(result.D3D9.Errors);

  sU32 d3dflags = 0;
  if(flags&sSCF_DEBUG)
    d3dflags |= D3DXSHADER_DEBUG;
  //if (sGetShellSwitch(L"n"))
  //  flags |= D3DXSHADER_SKIPOPTIMIZATION; // only use in case of emergency

  const sChar8 *profile8 = GetProfile(dtype);
  sChar profile[16];
  sCopyString(profile,profile8,16);

  // use old compiler for generating shader model 1_* code
#ifdef D3DXSHADER_USE_LEGACY_D3DX9_31_DLL
  if(sMatchWildcard(L"ps_1_*",profile))
    d3dflags |= D3DXSHADER_USE_LEGACY_D3DX9_31_DLL;
#endif

  if(D3DXCompileShader(src,len,0,0,name,profile8,d3dflags,&bytecode,&result.D3D9.Errors,&result.D3D9.CTable)!=D3D_OK)
    result.Valid = sFALSE;
  else
    result.Valid = sTRUE;

  // print errors and warnings
  if(result.D3D9.Errors)
  {
    ID3DXBuffer *buffer = result.D3D9.Errors;
    //sInt size = buffer->GetBufferSize();
    sCopyString(result.Errors,(sChar8*)buffer->GetBufferPointer(),result.Errors.Size());
  }

  if(!result.Valid)
  {
    sRelease(bytecode);
    return sFALSE;
  }

  // get source code
  sAddShaderBlob(result.ShaderBlobs,dtype,bytecode->GetBufferSize(),(const sU8*)bytecode->GetBufferPointer());
  return result.Valid;
#else
  return sFALSE;
#endif // sCOMP_DX9_ENABLE
}
fResult f2dRenderDeviceImpl::SaveScreen(f2dStream* pStream)
{
    if(m_bDevLost)
        return FCYERR_ILLEGAL;

    if(!pStream || !pStream->CanWrite() || !pStream->CanResize())
        return FCYERR_INVAILDPARAM;

    IDirect3DSurface9* pSurface = NULL;

    HRESULT tHR = m_pDev->CreateOffscreenPlainSurface(GetBufferWidth(), GetBufferHeight(),
                  D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pSurface, NULL);

    if(FAILED(tHR))
    {
        m_pEngine->ThrowException(fcyWin32COMException("f2dRenderDeviceImpl::SaveScreen", "CreateOffscreenPlainSurface Failed.", tHR));
        return FCYERR_INTERNALERR;
    }

    if(FAILED(m_pDev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pSurface)))
    {
        FCYSAFEKILL(pSurface);
        return FCYERR_INTERNALERR;
    }

    ID3DXBuffer* pDataBuffer = NULL;
    tHR = m_API.DLLEntry_D3DXSaveSurfaceToFileInMemory(&pDataBuffer, D3DXIFF_PNG, pSurface, NULL, NULL);
    FCYSAFEKILL(pSurface);
    if(FAILED(tHR))
    {
        m_pEngine->ThrowException(fcyWin32COMException("f2dRenderDeviceImpl::SaveScreen", "D3DXSaveSurfaceToFileInMemory Failed.", tHR));
        return FCYERR_INTERNALERR;
    }

    // 保存到流
    if(FCYFAILED(pStream->WriteBytes((fcData)pDataBuffer->GetBufferPointer(), pDataBuffer->GetBufferSize(), NULL)))
    {
        FCYSAFEKILL(pDataBuffer);
        return FCYERR_INTERNALERR;
    }

    FCYSAFEKILL(pDataBuffer);

    return FCYERR_OK;
}
Exemple #5
0
HRESULT MyCreateEffectFromFile(TCHAR *fName, DWORD dwShaderFlags, ID3D11Device *pDevice, ID3DX11Effect **pEffect)
{
    char fNameChar[1024];
	CharToOem(fName, fNameChar);
	ID3DXBuffer *pShader;
	HRESULT hr;
	ID3DXBuffer *pErrors;
	if (FAILED(D3DXCompileShaderFromFileA(fNameChar, NULL, NULL, NULL, "fx_5_0", 0, &pShader, &pErrors, NULL)))
	{
		MessageBoxA(NULL, (char *)pErrors->GetBufferPointer(), "Error", MB_OK);
		return E_FAIL;
	}
    V_RETURN(D3DX11CreateEffectFromMemory(pShader->GetBufferPointer(), pShader->GetBufferSize(), dwShaderFlags, pDevice, pEffect));

	SAFE_RELEASE(pErrors);
	SAFE_RELEASE(pShader);

    return S_OK;
}
int l_Image_Save( lua_State* L )
{
	ImageData* imgData = lua_checkimage( L, 1 );
	const char* fileName = lua_tostring( L, 2 );

	if( !imgData || !fileName )
	{
		lua_pushstring( L, "Wrong parameters to Image_Save functions" );
		lua_error( L );
		return 0;
	}

	LPDIRECT3DTEXTURE9 texture;
	D3DLOCKED_RECT rect;

	D3DFORMAT dxFormat = (D3DFORMAT)imgData->format->d3dformat;

	if( dxFormat == D3DFMT_DXT1 || dxFormat == D3DFMT_DXT3 || dxFormat == D3DFMT_DXT5 )
		dxFormat = D3DFMT_A8R8G8B8;

	g_pd3dDevice->CreateTexture( imgData->width, imgData->height, 1, 0, dxFormat, D3DPOOL_MANAGED, &texture, 0 );
	texture->LockRect(0, &rect, 0, 0 );
	memcpy( rect.pBits, imgData->imgData, imgData->width * imgData->height * imgData->format->bytesPerPixel );
	texture->UnlockRect( 0 );

	if( imgData->format->d3dformat == D3DFMT_DXT1 || imgData->format->d3dformat == D3DFMT_DXT3 || imgData->format->d3dformat == D3DFMT_DXT5 )
	{
		ID3DXBuffer* dxBuffer;
		LPDIRECT3DTEXTURE9 outTexture; 
		D3DXSaveTextureToFileInMemory( &dxBuffer, D3DXIFF_BMP, texture, 0 );
		D3DXCreateTextureFromFileInMemoryEx( g_pd3dDevice, dxBuffer->GetBufferPointer(), dxBuffer->GetBufferSize(), imgData->width, imgData->height, 0, 0, (D3DFORMAT)imgData->format->d3dformat, D3DPOOL_SCRATCH, D3DX_DEFAULT, D3DX_DEFAULT, 0, 0, 0, &outTexture );

		D3DXSaveTextureToFile( fileName, extToFormat(fileName), outTexture, 0 );
		outTexture->Release();
	}else
	{
		D3DXSaveTextureToFile( fileName, extToFormat(fileName), texture, 0 );
	}

	texture->Release();

	return 0;
}
fResult f2dRenderDeviceImpl::SaveTexture(f2dStream* pStream, f2dTexture2D* pTex)
{
    if(m_bDevLost)
        return FCYERR_ILLEGAL;

    if(!pStream || !pTex || !pStream->CanWrite() || !pStream->CanResize())
        return FCYERR_INVAILDPARAM;

    IDirect3DSurface9* pSurface = NULL;
    if(pTex->IsDynamic())
        ((IDirect3DTexture9*)((f2dTexture2DDynamic*)pTex)->GetHandle())->GetSurfaceLevel(0, &pSurface);
    else if(pTex->IsRenderTarget())
    {
        pSurface = ((f2dTexture2DRenderTarget*)pTex)->GetSurface();
        pSurface->AddRef();
    }
    else
        ((IDirect3DTexture9*)((f2dTexture2DStatic*)pTex)->GetHandle())->GetSurfaceLevel(0, &pSurface);

    if(!pSurface)
        return FCYERR_INTERNALERR;

    ID3DXBuffer* pDataBuffer = NULL;
    HRESULT tHR = m_API.DLLEntry_D3DXSaveSurfaceToFileInMemory(&pDataBuffer, D3DXIFF_PNG, pSurface, NULL, NULL);
    FCYSAFEKILL(pSurface);
    if(FAILED(tHR))
    {
        m_pEngine->ThrowException(fcyWin32COMException("f2dRenderDeviceImpl::SaveTexture", "D3DXSaveSurfaceToFileInMemory Failed.", tHR));
        return FCYERR_INTERNALERR;
    }

    // 保存到流
    if(FCYFAILED(pStream->WriteBytes((fcData)pDataBuffer->GetBufferPointer(), pDataBuffer->GetBufferSize(), NULL)))
    {
        FCYSAFEKILL(pDataBuffer);
        return FCYERR_INTERNALERR;
    }

    FCYSAFEKILL(pDataBuffer);

    return FCYERR_OK;
}
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 #9
0
bool StripifyMeshSubset(ID3DXMesh* mesh,
                        DWORD attribId,
                        ostream& meshfile)
{
    // TODO: Fall back to tri lists if the strip size is too small
    // TODO: Detect when a tri fan should be used instead of a tri list

    // Convert to tri strips
    IDirect3DIndexBuffer9* indices = NULL;
    DWORD numIndices = 0;
    ID3DXBuffer* strips = NULL;
    DWORD numStrips = 0;
    HRESULT hr;
    hr = D3DXConvertMeshSubsetToStrips(mesh,
                                       attribId,
                                       0,
                                       &indices,
                                       &numIndices,
                                       &strips,
                                       &numStrips);
    if (FAILED(hr))
    {
        cout << "Stripify failed\n";
        return false;
    }

    cout << "Converted to " << numStrips << " strips\n";
    cout << "Strip buffer size: " << strips->GetBufferSize() << '\n';
    if (numStrips != strips->GetBufferSize() / 4) 
    {
        cout << "Strip count is incorrect!\n";
        return false;
    }

    bool index32 = false;
    {
        D3DINDEXBUFFER_DESC desc;
        indices->GetDesc(&desc);
        if (desc.Format == D3DFMT_INDEX32)
        {
            index32 = true;
        }
        else if (desc.Format == D3DFMT_INDEX16)
        {
            index32 = false;
        }
        else
        {
            cout << "Bad index format.  Strange.\n";
            return false;
        }
    }

    void* indexData = NULL;
    hr = indices->Lock(0, 0, &indexData, D3DLOCK_READONLY);
    if (FAILED(hr))
    {
        cout << "Failed to lock index buffer: " << D3DErrorString(hr) << '\n';
        return false;
    }

    {
        DWORD* stripLengths = reinterpret_cast<DWORD*>(strips->GetBufferPointer());
        int k = 0;
        for (int i = 0; i < numStrips; i++)
        {
            if (stripLengths[i] == 0)
            {
                cout << "Bad triangle strip (length == 0) in mesh!\n";
                return false;
            }

            if (index32)
            {
                DWORD* indices = reinterpret_cast<DWORD*>(indexData) + k;
                int fanStart = checkForFan(stripLengths[i], indices);
                if (fanStart != 1)
                {
                    DumpTriStrip(stripLengths[i], indices, (int) attribId,
                                 meshfile);
                }
                else
                {
                    DumpTriStripAsFan(stripLengths[i], indices, (int) attribId,
                                      fanStart, meshfile);
                }
            }
            else
            {
                WORD* indices = reinterpret_cast<WORD*>(indexData) + k;
                int fanStart = checkForFan(stripLengths[i], indices);
                if (fanStart != 1)
                {
                    DumpTriStrip(stripLengths[i], indices, (int) attribId,
                                 meshfile);
                }
                else
                {
                    DumpTriStripAsFan(stripLengths[i], indices, (int) attribId,
                                      fanStart, meshfile);
                }
            }

            k += stripLengths[i] + 2;
        }

        cout << "k=" << k << ", numIndices=" << numIndices;
        if (index32)
            cout << ", 32-bit indices\n";
        else
            cout << ", 16-bit indices\n";
    }

    return true;
}
Exemple #10
0
bool DevEffect::GetPrecompiledBinary(
		vector<char> &data, const char *id, const char *path, const char *bpath,
		vector<D3DXMACRO> &macros, byte hash[16], vector<byte> &bin)
{
	ID3DXEffectCompiler *fxc = NULL;
	ID3DXBuffer *binbuff = NULL;
	ID3DXBuffer *errors = NULL;


	if(_load_scrambled(bpath,*(vector<byte>*)&bin) && bin.size()>16)
	{
		if(memcmp(&bin[0],hash,16)==0)
		{
			bin.erase(bin.begin(),bin.begin()+16);
			return true;
		}
	}

	for(int pass=0;pass<2;pass++)
	{
		HRESULT r;
		bool error;
		
		if( pass == 0 )
		{
			r = D3DXCreateEffectCompiler(&data[0],(DWORD)data.size(),&macros[0],NULL,
					compile_flags,&fxc,&errors);
			error = !fxc;
		}
		else
		{
			r = fxc->CompileEffect(compile_flags,&binbuff,&errors);
			error = !binbuff;
		}

		if(FAILED(r) || errors || error)
		{
			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();
				if(fxc) fxc->Release();
				if(binbuff) binbuff->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);
				if(fxc) fxc->Release();
				if(binbuff) binbuff->Release();
				return false;
			}
		}
	}

	bin.clear();
	bin.insert(bin.end(),hash,hash+16);
	bin.insert(bin.end(),(byte*)binbuff->GetBufferPointer(),((byte*)binbuff->GetBufferPointer())+binbuff->GetBufferSize());

	fxc->Release();
	binbuff->Release();

	_save_scrambled(bpath,bin);

	bin.erase(bin.begin(),bin.begin()+16);

	return true;
}
Exemple #11
0
int Dx9Effect::create( gd::GraphicsDevice* device, const void* data, int size ) 
{
	assert( device );

	destroy();

	m_dev = static_cast<Dx9GraphicsDevice*>( device );
	m_dev->resetRenderState();

	// compile effect description
	ID3DXBuffer* xerr = 0;
	D3DXMACRO* defines = 0;
	ID3DXInclude* includeLoader = 0;
	ID3DXEffectPool* effectPool = 0;
	DWORD flags = D3DXSHADER_PACKMATRIX_COLUMNMAJOR;
//#ifdef _DEBUG
	flags |= D3DXSHADER_DEBUG;
//#endif
	HRESULT hr = D3DXCreateEffect( m_dev->d3dDevice(), data, size, defines, includeLoader, flags, effectPool, &m_fx, &xerr );

	// get compilation errors
	if ( xerr )
	{
		if ( hr != D3D_OK )
		{
			char* xerrmsg = (char*)xerr->GetBufferPointer();
			int xerrmsglen = xerr->GetBufferSize();
			delete[] m_err; m_err = 0;
			m_err = new char[xerrmsglen+1];
			m_err[xerrmsglen] = 0;
			strncpy( m_err, xerrmsg, xerrmsglen );
		}
		xerr->Release();
		xerr = 0;
	}

	// report errors
	if ( hr != D3D_OK )
	{
		error( "Failed to compile effect description: %s", m_err );
		return gd::ERROR_EFFECTCOMPILATIONERROR;
	}

	// select technique to be used
	D3DXHANDLE tech;
	hr = m_fx->FindNextValidTechnique( 0, &tech );
	if ( hr != D3D_OK )
	{
		error( "Dx9Effect.FindNextValidTechnique failed: %s", toString(hr) );
		setError( "Effect is not supported by the graphics device." );
		return gd::ERROR_EFFECTUNSUPPORTED;
	}

	// select the technique
	hr = m_fx->SetTechnique( tech );
	if ( hr != D3D_OK )
	{
		error( "Dx9Effect.SetTechnique failed: %s", toString(hr) );
		setError( "Effect is not supported by the graphics device." );
		return gd::ERROR_EFFECTUNSUPPORTED;
	}

	// enum parameters
	D3DXEFFECT_DESC fxDesc;
	hr = m_fx->GetDesc( &fxDesc );
	m_params = fxDesc.Parameters;

	return gd::ERROR_NONE;
}
Exemple #12
0
HRESULT KG3DGraphicsEngine::ScreenShotImpl()
{
    HRESULT hResult  = E_FAIL;
    HRESULT hRetCode = E_FAIL;

    IDirect3DSurface9* pFrameSurface = NULL;
    IDirect3DTexture9* pTextureSys = NULL;
    ID3DXBuffer* pBuffer = NULL;
    D3DVIEWPORT9 ViewPort;
    RECT RectView;

    ASSERT(m_eShotImageType != D3DXIFF_FORCE_DWORD);

    hRetCode = g_pd3dDevice->GetRenderTarget(0, &pFrameSurface);
    KG_COM_PROCESS_ERROR(hRetCode);

    g_pd3dDevice->GetViewport(&ViewPort);
    SetRect(&RectView, ViewPort.X, ViewPort.Y, ViewPort.X + ViewPort.Width, ViewPort.Y + ViewPort.Height);

    if (m_eShotImageType == D3DXIFF_JPG)
    {
        D3DSURFACE_DESC SurfaceDesc;
        D3DLOCKED_RECT LockRect;
        
        hRetCode = D3DXSaveSurfaceToFileInMemory(&pBuffer, D3DXIFF_BMP, pFrameSurface, NULL, &RectView);
        KG_COM_PROCESS_ERROR(hRetCode);

        hRetCode = D3DXCreateTextureFromFileInMemoryEx(g_pd3dDevice, 
            pBuffer->GetBufferPointer(), 
            pBuffer->GetBufferSize(),
            ViewPort.Width,
            ViewPort.Height,
            1,
            0,
            D3DFMT_A8R8G8B8,
            D3DPOOL_SCRATCH,
            D3DX_DEFAULT,
            D3DX_DEFAULT,
            0,
            NULL,
            NULL,
            &pTextureSys);
        KG_COM_PROCESS_ERROR(hRetCode);


        /*
        hRetCode = D3DXSaveSurfaceToFile(TEXT("__temp_shot.bmp"), D3DXIFF_BMP, pFrameSurface, NULL, &RectView);
        KG_COM_PROCESS_ERROR(hRetCode);

        hRetCode = D3DXCreateTextureFromFileEx(g_pd3dDevice, 
            TEXT("__temp_shot.bmp"), 
            ViewPort.Width,
            ViewPort.Height,
            1,
            0,
            D3DFMT_A8R8G8B8,
            D3DPOOL_SCRATCH,
            D3DX_DEFAULT,
            D3DX_DEFAULT,
            0,
            NULL,
            NULL,
            &pTextureSys);
        KG_COM_PROCESS_ERROR(hRetCode); */

        pTextureSys->GetLevelDesc(0, &SurfaceDesc);

        if (SUCCEEDED(pTextureSys->LockRect(0, &LockRect, NULL, D3DLOCK_NOSYSLOCK)))
        {
            struct _Rgba { BYTE r; BYTE g; BYTE b; BYTE a;};
            struct _Rgb  { BYTE b; BYTE g; BYTE r; };
            _Rgb* pRgb = new _Rgb[SurfaceDesc.Height * SurfaceDesc.Width];

            for (UINT v = 0; v < SurfaceDesc.Height; ++v)
            {
                _Rgba* pRgba = (_Rgba*)((BYTE*)LockRect.pBits + LockRect.Pitch * v);

                for (UINT u = 0; u < SurfaceDesc.Width; ++u)
                {
                    pRgb[v * SurfaceDesc.Width + u].r = pRgba[u].r;
                    pRgb[v * SurfaceDesc.Width + u].g = pRgba[u].g;
                    pRgb[v * SurfaceDesc.Width + u].b = pRgba[u].b;
                }
            }

            JpegFile::RGBToJpegFile(m_szShotPath, (BYTE*)pRgb, SurfaceDesc.Width, SurfaceDesc.Height, TRUE, m_nShotImageQuty);

            delete[] pRgb;
            pTextureSys->UnlockRect(0);
        }
        else
        {
            KG_PROCESS_ERROR(FALSE);
        }
    }
    else
    {
        hRetCode = D3DXSaveSurfaceToFile(m_szShotPath, m_eShotImageType, pFrameSurface, NULL, &RectView);
        KG_COM_PROCESS_ERROR(hRetCode);
    }

    hResult = S_OK;
Exit0 :
    SAFE_RELEASE(pBuffer);
    SAFE_RELEASE(pTextureSys);
    SAFE_RELEASE(pFrameSurface);
    return hResult;
}
Exemple #13
0
/*
extern "C"
{
	LPCSTR WINAPI	D3DXGetPixelShaderProfile	(LPDIRECT3DDEVICE9  pDevice);
	LPCSTR WINAPI	D3DXGetVertexShaderProfile	(LPDIRECT3DDEVICE9	pDevice);
};
*/
HRESULT	CRender::shader_compile			(
    LPCSTR							name,
    LPCSTR                          pSrcData,
    UINT                            SrcDataLen,
    void*							_pDefines,
    void*							_pInclude,
    LPCSTR                          pFunctionName,
    LPCSTR                          pTarget,
    DWORD                           Flags,
    void*							_ppShader,
    void*							_ppErrorMsgs,
    void*							_ppConstantTable)
{
    D3DXMACRO						defines			[128];
    int								def_it			= 0;
    CONST D3DXMACRO*                pDefines		= (CONST D3DXMACRO*)	_pDefines;
    char							c_smapsize		[32];
    char							c_gloss			[32];

//	Msg("%s.%s", name, pTarget);

    if (pDefines)	{
        // transfer existing defines
        for (;; def_it++)	{
            if (0==pDefines[def_it].Name)	break;
            defines[def_it]			= pDefines[def_it];
        }
    }
    // options
    {
        sprintf						(c_smapsize,"%d",u32(o.smapsize));
        defines[def_it].Name		=	"SMAP_size";
        defines[def_it].Definition	=	c_smapsize;
        def_it						++	;
    }
    if (o.fp16_filter)		{
        defines[def_it].Name		=	"FP16_FILTER";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.fp16_blend)		{
        defines[def_it].Name		=	"FP16_BLEND";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.HW_smap)			{
        defines[def_it].Name		=	"USE_HWSMAP";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.HW_smap_PCF)			{
        defines[def_it].Name		=	"USE_HWSMAP_PCF";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.HW_smap_FETCH4)			{
        defines[def_it].Name		=	"USE_FETCH4";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.sjitter)			{
        defines[def_it].Name		=	"USE_SJITTER";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (HW.Caps.raster_major >= 3)	{
        defines[def_it].Name		=	"USE_BRANCHING";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (HW.Caps.geometry.bVTF)	{
        defines[def_it].Name		=	"USE_VTF";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.Tshadows)			{
        defines[def_it].Name		=	"USE_TSHADOWS";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.mblur)			{
        defines[def_it].Name		=	"USE_MBLUR";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.sunfilter)		{
        defines[def_it].Name		=	"USE_SUNFILTER";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.sunstatic)		{
        defines[def_it].Name		=	"USE_R2_STATIC_SUN";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (o.forcegloss)		{
        sprintf						(c_gloss,"%f",o.forcegloss_v);
        defines[def_it].Name		=	"FORCE_GLOSS";
        defines[def_it].Definition	=	c_gloss;
        def_it						++	;
    }
    if (o.forceskinw)		{
        defines[def_it].Name		=	"SKIN_COLOR";
        defines[def_it].Definition	=	"1";
        def_it						++;
    }

    // skinning
    if (m_skinning<0)		{
        defines[def_it].Name		=	"SKIN_NONE";
        defines[def_it].Definition	=	"1";
        def_it						++	;
    }
    if (0==m_skinning)		{
        defines[def_it].Name		=	"SKIN_0";
        defines[def_it].Definition	=	"1";
        def_it						++;
    }
    if (1==m_skinning)		{
        defines[def_it].Name		=	"SKIN_1";
        defines[def_it].Definition	=	"1";
        def_it						++;
    }
    if (2==m_skinning)		{
        defines[def_it].Name		=	"SKIN_2";
        defines[def_it].Definition	=	"1";
        def_it						++;
    }

    // finish
    defines[def_it].Name			=	0;
    defines[def_it].Definition		=	0;
    def_it							++;

    //
    if (0==xr_strcmp(pFunctionName,"main"))	{
        if ('v'==pTarget[0])			pTarget = D3DXGetVertexShaderProfile	(HW.pDevice);	// vertex	"vs_2_a"; //
        else							pTarget = D3DXGetPixelShaderProfile		(HW.pDevice);	// pixel	"ps_2_a"; //
    }

    LPD3DXINCLUDE                   pInclude		= (LPD3DXINCLUDE)		_pInclude;
    LPD3DXBUFFER*                   ppShader		= (LPD3DXBUFFER*)		_ppShader;
    LPD3DXBUFFER*                   ppErrorMsgs		= (LPD3DXBUFFER*)		_ppErrorMsgs;
    LPD3DXCONSTANTTABLE*            ppConstantTable	= (LPD3DXCONSTANTTABLE*)_ppConstantTable;

#ifdef	D3DXSHADER_USE_LEGACY_D3DX9_31_DLL	//	December 2006 and later
    HRESULT		_result	= D3DXCompileShader(pSrcData,SrcDataLen,defines,pInclude,pFunctionName,pTarget,Flags|D3DXSHADER_USE_LEGACY_D3DX9_31_DLL,ppShader,ppErrorMsgs,ppConstantTable);
#else
    HRESULT		_result	= D3DXCompileShader(pSrcData,SrcDataLen,defines,pInclude,pFunctionName,pTarget,Flags,ppShader,ppErrorMsgs,ppConstantTable);
#endif
    if (SUCCEEDED(_result) && o.disasm)
    {
        ID3DXBuffer*		code	= *((LPD3DXBUFFER*)_ppShader);
        ID3DXBuffer*		disasm	= 0;
        D3DXDisassembleShader		(LPDWORD(code->GetBufferPointer()), FALSE, 0, &disasm );
        string_path			dname;
        strconcat			(dname,"disasm\\",name,('v'==pTarget[0])?".vs":".ps" );
        IWriter*			W		= FS.w_open("$logs$",dname);
        W->w				(disasm->GetBufferPointer(),disasm->GetBufferSize());
        FS.w_close			(W);
        _RELEASE			(disasm);
    }
    return		_result;
}
Exemple #14
0
static HRESULT create_shader				(
		LPCSTR const	pTarget,
		DWORD const*	buffer,
		u32	const		buffer_size,
		LPCSTR const	file_name,
		void*&			result,
		bool const		disasm
	)
{
	HRESULT		_result = E_FAIL;
	if (pTarget[0] == 'p') {
		SPS* sps_result = (SPS*)result;
		_result			= HW.pDevice->CreatePixelShader(buffer, &sps_result->ps);
		if ( !SUCCEEDED(_result) ) {
			Log			("! PS: ", file_name);
			Msg			("! CreatePixelShader hr == 0x%08x", _result);
			return		E_FAIL;
		}

		LPCVOID			data		= NULL;
		_result			= D3DXFindShaderComment	(buffer,MAKEFOURCC('C','T','A','B'),&data,NULL);
		if (SUCCEEDED(_result) && data)
		{
			LPD3DXSHADER_CONSTANTTABLE	pConstants	= LPD3DXSHADER_CONSTANTTABLE(data);
			sps_result->constants.parse	(pConstants,0x1);
		} 
		else
		{
			Log			("! PS: ", file_name);
			Msg			("! D3DXFindShaderComment hr == 0x%08x", _result);
		}
	}
	else {
		SVS* svs_result = (SVS*)result;
		_result			= HW.pDevice->CreateVertexShader(buffer, &svs_result->vs);
		if ( !SUCCEEDED(_result) ) {
			Log			("! VS: ", file_name);
			Msg			("! CreatePixelShader hr == 0x%08x", _result);
			return		E_FAIL;
		}

		LPCVOID			data		= NULL;
		_result			= D3DXFindShaderComment	(buffer,MAKEFOURCC('C','T','A','B'),&data,NULL);
		if (SUCCEEDED(_result) && data)
		{
			LPD3DXSHADER_CONSTANTTABLE	pConstants	= LPD3DXSHADER_CONSTANTTABLE(data);
			svs_result->constants.parse	(pConstants,0x2);
		} 
		else
		{
			Log			("! VS: ", file_name);
			Msg			("! D3DXFindShaderComment hr == 0x%08x", _result);
		}
	}

	if (disasm)
	{
		ID3DXBuffer*	disasm	= 0;
		D3DXDisassembleShader(LPDWORD(buffer), FALSE, 0, &disasm );
		string_path		dname;
		strconcat		(sizeof(dname),dname,"disasm\\",file_name,('v'==pTarget[0])?".vs":".ps" );
		IWriter*		W = FS.w_open("$logs$",dname);
		W->w			(disasm->GetBufferPointer(),disasm->GetBufferSize());
		FS.w_close		(W);
		_RELEASE		(disasm);
	}

	return				_result;
}
Exemple #15
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    WNDCLASS wc;

    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc = (WNDPROC) MainWindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
    wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "xtocmod";
    if (RegisterClass(&wc) == 0)
    {
	MessageBox(NULL,
                   "Failed to register the window class.", "Fatal Error",
                   MB_OK | MB_ICONERROR);
	return NULL;
    }

    DWORD windowStyle = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU |
                         WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
    g_mainWindow = CreateWindow("xtocmod",
                                "xtocmod",
                                windowStyle,
                                CW_USEDEFAULT,
                                CW_USEDEFAULT,
                                300, 300,
                                NULL,
                                NULL,
                                hInstance,
                                NULL);
    if (g_mainWindow == NULL)
    {
        MessageBox(NULL,
                   "Error creating application window.", "Fatal Error",
                   MB_OK | MB_ICONERROR);
    }

    //ShowWindow(g_mainWindow, SW_SHOW);
    SetForegroundWindow(g_mainWindow);
    SetFocus(g_mainWindow);

    // Initialize D3D
    g_d3d = Direct3DCreate9(D3D_SDK_VERSION);
    if (g_d3d == NULL)
    {
        ShowD3DErrorMessage("Initializing D3D", 0);
        return 1;
    }

    D3DPRESENT_PARAMETERS presentParams;
    ZeroMemory(&presentParams, sizeof(presentParams));
    presentParams.Windowed = TRUE;
    presentParams.SwapEffect = D3DSWAPEFFECT_COPY;
#if 0
    presentParams.BackBufferWidth = 300;
    presentParams.BackBufferHeight = 300;
    presentParams.BackBufferCount = 1;
    presentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    presentParams.Windowed = TRUE;
#endif
    
    HRESULT hr = g_d3d->CreateDevice(D3DADAPTER_DEFAULT,
                                     D3DDEVTYPE_HAL,
                                     g_mainWindow,
                                     D3DCREATE_HARDWARE_VERTEXPROCESSING,
                                     &presentParams,
                                     &g_d3dDev);
    if (FAILED(hr))
    {
        ShowD3DErrorMessage("Creating D3D device", hr);
        //return 1;
    }

    string inputFilename(lpCmdLine);
    string outputFilename(inputFilename, 0, inputFilename.rfind('.'));
    outputFilename += ".cmod";

    ID3DXMesh* mesh = NULL;
    ID3DXBuffer* adjacency = NULL;
    ID3DXBuffer* materialBuf = NULL;
    ID3DXBuffer* effects = NULL;
    DWORD numMaterials;
    
    hr = D3DXLoadMeshFromX(inputFilename.c_str(),
                           0,
                           g_d3dDev,
                           &adjacency,
                           &materialBuf,
                           &effects,
                           &numMaterials,
                           &mesh);
    if (FAILED(hr))
    {
        ShowD3DErrorMessage("Loading mesh from X file", hr);
        return 1;
    }


    DWORD numVertices = mesh->GetNumVertices();
    DWORD numFaces = mesh->GetNumFaces();

    cout << "vertices: " << numVertices << '\n';
    cout << "faces: " << numFaces << '\n';

    cout << "adjacency buffer size: " << adjacency->GetBufferSize() << '\n';

    ofstream meshfile(outputFilename.c_str());

    // Output the header
    meshfile << "#celmodel__ascii\n\n";

    cout << "numMaterials=" << numMaterials << '\n';
    D3DXMATERIAL* materials = reinterpret_cast<D3DXMATERIAL*>(materialBuf->GetBufferPointer());
    for (DWORD mat = 0; mat < numMaterials; mat++)
    {
        meshfile << "material\n";
        meshfile << "diffuse " << materials[mat].MatD3D.Diffuse << '\n';
        //meshfile << "emissive " << materials[mat].MatD3D.Emissive << '\n';
        meshfile << "specular " << materials[mat].MatD3D.Specular << '\n';
        meshfile << "specpower " << materials[mat].MatD3D.Power << '\n';
        meshfile << "opacity " << materials[mat].MatD3D.Diffuse.a << '\n';
        meshfile << "end_material\n\n";
    }

    // Vertex format
    D3DVERTEXELEMENT9 declElements[MAX_FVF_DECL_SIZE];
    hr = mesh->GetDeclaration(declElements);
    if (FAILED(hr))
    {
        ShowD3DErrorMessage("Checking vertex declaration", hr);
        return 1;
    }

    DWORD stride = D3DXGetDeclVertexSize(declElements, 0);

    VertexAttribute vertexMap[VertexAttribute::MaxAttribute];
    CreateVertexAttributeMap(declElements, vertexMap);

    meshfile << "mesh\n\n";

    DumpVertexDescription(vertexMap, meshfile);

    ID3DXMesh* optMesh = NULL;
    ID3DXBuffer* vertexRemap = NULL;
    DWORD* faceRemap = new DWORD[numFaces];
    DWORD* optAdjacency = new DWORD[numFaces * 3];
    hr = mesh->Optimize(D3DXMESHOPT_COMPACT | D3DXMESHOPT_STRIPREORDER,
                        //D3DXMESHOPT_VERTEXCACHE |
                        reinterpret_cast<DWORD*>(adjacency->GetBufferPointer()),
                        optAdjacency,
                        faceRemap,
                        &vertexRemap,
                        &optMesh);
    if (FAILED(hr))
    {
        ShowD3DErrorMessage("Optimize failed: ", hr);
        return 1;
    }
    
    // Attribute table
    DWORD attribTableSize = 0;
    hr = optMesh->GetAttributeTable(NULL, &attribTableSize);
    if (FAILED(hr))
    {
        ShowD3DErrorMessage("Querying attribute table size", hr);
        return 1;
    }

    D3DXATTRIBUTERANGE* attribTable = NULL;
    if (attribTableSize > 0)
    {
        attribTable = new D3DXATTRIBUTERANGE[attribTableSize];
        hr = optMesh->GetAttributeTable(attribTable, &attribTableSize);
        if (FAILED(hr))
        {
            ShowD3DErrorMessage("Getting attribute table", hr);
            return 1;
        }
    }

    cout << "Attribute table size: " << attribTableSize << '\n';
    if (attribTableSize == 1)
    {
        cout << "Attribute id: " << attribTable[0].AttribId << '\n';
    }

    if (!DumpMeshVertices(optMesh, vertexMap, stride, meshfile))
        return 1;
    
    // output the indices
    for (DWORD attr = 0; attr < attribTableSize; attr++)
    {
        StripifyMeshSubset(optMesh, attr, meshfile);
    }
    meshfile << "\nend_mesh\n";

#if 0
    IDirect3DIndexBuffer9* indices = NULL;
    hr = mesh->GetIndexBuffer(&indices);
#endif

#if 0
    // No message loop required for this app
    MSG msg;
    GetMessage(&msg, NULL, 0u, 0u);
    while (msg.message != WM_QUIT)
    {
        GetMessage(&msg, NULL, 0u, 0u);
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
#endif

    return 0;
}
Exemple #16
0
	bool CShaderHLSL::Create(P3D::sShaderDesc &desc)
	{
		const char *pData;
		ULONG fsize;
		IFileSystem* pFS = CRenderer::mEngine()->mFilesystem();
		wchar path[P3DMAX_PATH];
		wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get());
		FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true);
		if (!fp)
		{
			CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get());
			return false;
		}

		ID3DXBuffer *pShaderBlob = NULL;
		ID3DXBuffer *pErrors = NULL;
		DWORD flags = D3DXSHADER_DEBUG;  //D3DXSHADER_OPTIMIZATION_LEVEL3

		char profile[128];
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			strcpy(profile, D3DXGetVertexShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			strcpy(profile, D3DXGetPixelShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_GEOMETRY_SHADER:
			CON(MSG_ERR, _W("DX9 does not support geometry shaders."));
			return false;
		default:
			CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given."));
			return false;
		}

		CIncludeHandler includeHandler;
		
		D3DXMACRO Shader_Macros[] = 
		{
			{ "DX9", NULL },
			{ "SM3", NULL },
			NULL
		};

		if(FAILED(D3DXCompileShader(
			pData, 
			fsize, 
			Shader_Macros, 
			&includeHandler, 
			_W2A(desc.EntryFunction.Get()), 
			profile, 
			flags,
			&pShaderBlob, 
			&pErrors,
			&m_pConstTable
			)))
		{
			if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer()));
			else CON(MSG_ERR, _W("Error description not given"));
			CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get());
			SAFE_RELEASE(pErrors);
			return false;
		}

		pFS->UnLoad(fp, (BYTE *)pData);

		//save to cache
		fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb"));
		const char* cs = (const char*)pShaderBlob->GetBufferPointer();
		pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp);
		pFS->Close(fp);

		bool shaderCreated = false;
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			shaderCreated = SUCCEEDED(g_pD3ddev->CreateVertexShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pVS));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			shaderCreated = SUCCEEDED(g_pD3ddev->CreatePixelShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pPS));
			break;
		}

		if(!shaderCreated)
		{
			CON(MSG_ERR, _W("Shader creation error"));
			return false;
		}

		//set constant to their default values 
		m_pConstTable->SetDefaults(g_pD3ddev);

		//create vertex declaration
		if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER)
			m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob);

		SAFE_RELEASE(pShaderBlob);

		m_desc = desc;

		CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile);

		return true;
	}
Exemple #17
0
HRESULT	CRender::shader_compile			(
		LPCSTR							name,
		LPCSTR                          pSrcData,
		UINT                            SrcDataLen,
		void*							_pDefines,
		void*							_pInclude,
		LPCSTR                          pFunctionName,
		LPCSTR                          pTarget,
		DWORD                           Flags,
		void*							_ppShader,
		void*							_ppErrorMsgs,
		void*							_ppConstantTable)
{
	D3DXMACRO						defines			[128];
	int								def_it			= 0;
	CONST D3DXMACRO*                pDefines		= (CONST D3DXMACRO*)	_pDefines;
	if (pDefines)	{
		// transfer existing defines
		for (;;def_it++)	{
			if (0==pDefines[def_it].Name)	break;
			defines[def_it]			= pDefines[def_it];
		}
	}
	// options
	if (o.forceskinw)		{
		defines[def_it].Name		=	"SKIN_COLOR";
		defines[def_it].Definition	=	"1";
		def_it						++;
	}
	if (m_skinning<0)		{
		defines[def_it].Name		=	"SKIN_NONE";
		defines[def_it].Definition	=	"1";
		def_it						++;
	}
	if (0==m_skinning)		{
		defines[def_it].Name		=	"SKIN_0";
		defines[def_it].Definition	=	"1";
		def_it						++;
	}
	if (1==m_skinning)		{
		defines[def_it].Name		=	"SKIN_1";
		defines[def_it].Definition	=	"1";
		def_it						++;
	}
	if (2==m_skinning)		{
		defines[def_it].Name		=	"SKIN_2";
		defines[def_it].Definition	=	"1";
		def_it						++;
	}
	// finish
	defines[def_it].Name			=	0;
	defines[def_it].Definition		=	0;
	def_it							++;
	R_ASSERT						(def_it<128);

	LPD3DXINCLUDE                   pInclude		= (LPD3DXINCLUDE)		_pInclude;
	LPD3DXBUFFER*                   ppShader		= (LPD3DXBUFFER*)		_ppShader;
	LPD3DXBUFFER*                   ppErrorMsgs		= (LPD3DXBUFFER*)		_ppErrorMsgs;
	LPD3DXCONSTANTTABLE*            ppConstantTable	= (LPD3DXCONSTANTTABLE*)_ppConstantTable;
#ifdef	D3DXSHADER_USE_LEGACY_D3DX9_31_DLL	//	December 2006 and later
	HRESULT		_result	= D3DXCompileShader(pSrcData,SrcDataLen,defines,pInclude,pFunctionName,pTarget,Flags|D3DXSHADER_USE_LEGACY_D3DX9_31_DLL,ppShader,ppErrorMsgs,ppConstantTable);
#else
	HRESULT		_result	= D3DXCompileShader(pSrcData,SrcDataLen,defines,pInclude,pFunctionName,pTarget,Flags,ppShader,ppErrorMsgs,ppConstantTable);
#endif

	if (SUCCEEDED(_result) && o.disasm)
	{
		ID3DXBuffer*		code	= *((LPD3DXBUFFER*)_ppShader);
		ID3DXBuffer*		disasm	= 0;
		D3DXDisassembleShader		(LPDWORD(code->GetBufferPointer()), FALSE, 0, &disasm );
		string_path			dname;
		strconcat			(sizeof(dname),dname,"disasm\\",name,('v'==pTarget[0])?".vs":".ps" );
		IWriter*			W		= FS.w_open("$logs$",dname);
		W->w				(disasm->GetBufferPointer(),disasm->GetBufferSize());
		FS.w_close			(W);
		_RELEASE			(disasm);
	}
	return		_result;
}