softparticles.cpp

来自「声音和图片的加载功能,不过运行起来有点卡」· C++ 代码 · 共 990 行 · 第 1/3 页

CPP
990 行
字号
// Release D3D10 resources created in OnD3D10ResizedSwapChain 
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext )
{
    g_DialogResourceManager.OnD3D10ReleasingSwapChain();

    SAFE_RELEASE( g_pDepthStencilTexture );
    SAFE_RELEASE( g_pDepthStencilDSV );
    SAFE_RELEASE( g_pDepthStencilSRV );
}


//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnD3D10CreateDevice 
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10DestroyDevice( void* pUserContext )
{
    g_DialogResourceManager.OnD3D10DestroyDevice();
    g_D3DSettingsDlg.OnD3D10DestroyDevice();
    DXUTGetGlobalResourceCache().OnDestroyDevice();
    SAFE_RELEASE( g_pFont10 );
    SAFE_RELEASE( g_pSprite10 );
    SAFE_DELETE( g_pTxtHelper );
    SAFE_RELEASE( g_pEffect10 );
    SAFE_RELEASE( g_pSceneVertexLayout );
    SAFE_RELEASE( g_pParticleVertexLayout );
    SAFE_RELEASE( g_pParticleVB );
    SAFE_RELEASE( g_pParticleIB );
    SAFE_RELEASE( g_pParticleTexRV );
    SAFE_RELEASE( g_pNoiseVolume );
    SAFE_RELEASE( g_pNoiseVolumeRV );
    SAFE_RELEASE( g_pColorGradTexRV );

    g_ObjectMesh.Destroy();
    g_SkyMesh.Destroy();
    SAFE_DELETE_ARRAY( g_pCPUParticles );
    SAFE_DELETE_ARRAY( g_pCPUParticleIndices );
    SAFE_DELETE_ARRAY( g_pParticleDepthArray );
}

//--------------------------------------------------------------------------------------
float RPercent()
{
    float ret = (float)((rand()%20000) - 10000 );
    return ret/10000.0f;
}

//--------------------------------------------------------------------------------------
void EmitParticle( PARTICLE_VERTEX* pParticle )
{
    pParticle->Pos.x = 0.0f;
    pParticle->Pos.y = 0.7f;
    pParticle->Pos.z = 3.0f;

    pParticle->Vel.x = 1.0f;
    pParticle->Vel.y = 0.3f*RPercent();
    pParticle->Vel.z = 0.3f*RPercent();

    D3DXVec3Normalize( &pParticle->Vel, &pParticle->Vel );
    pParticle->Vel *= g_ParticleVel;

    pParticle->Life = 0.0f;
    pParticle->Size = 0.0f;
}

//--------------------------------------------------------------------------------------
// Create a VB for particles
//--------------------------------------------------------------------------------------
HRESULT CreateParticleBuffers( ID3D10Device* pd3dDevice )
{
    HRESULT hr = S_OK;

    D3D10_BUFFER_DESC vbdesc;
    vbdesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    vbdesc.ByteWidth = MAX_PARTICLES*sizeof(PARTICLE_VERTEX);
    vbdesc.CPUAccessFlags = 0;
    vbdesc.MiscFlags = 0;
    vbdesc.Usage = D3D10_USAGE_DEFAULT;
    V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pParticleVB ) );

    vbdesc.BindFlags = D3D10_BIND_INDEX_BUFFER;
    vbdesc.ByteWidth = MAX_PARTICLES*sizeof(DWORD);
    V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pParticleIB ) );

    g_pCPUParticles = new PARTICLE_VERTEX[ MAX_PARTICLES ];
    if( !g_pCPUParticles )
        return E_OUTOFMEMORY;

    for( UINT i=0; i<MAX_PARTICLES; i++ )
    {
        g_pCPUParticles[i].Life = -1;	//kill all particles
    }

    g_pCPUParticleIndices = new DWORD[ MAX_PARTICLES ];
    if( !g_pCPUParticleIndices )
        return E_OUTOFMEMORY;
    g_pParticleDepthArray = new float[ MAX_PARTICLES ]; 
    if( !g_pParticleDepthArray )
        return E_OUTOFMEMORY;

    return hr;
}

struct CHAR4
{
    char x,y,z,w;
};

//--------------------------------------------------------------------------------------
float GetDensity( int x, int y, int z, CHAR4* pTexels, UINT VolumeSize )
{
    if( x < 0 )
        x += VolumeSize;
    if( y < 0 )
        y += VolumeSize;
    if( z < 0 )
        z += VolumeSize;

    x = x%VolumeSize;
    y = y%VolumeSize;
    z = z%VolumeSize;

    int index = x + y*VolumeSize + z*VolumeSize*VolumeSize;

    return (float)pTexels[index].w / 128.0f;
}

void SetNormal( D3DXVECTOR3 Normal, int x, int y, int z, CHAR4* pTexels, UINT VolumeSize )
{
    if( x < 0 )
        x += VolumeSize;
    if( y < 0 )
        y += VolumeSize;
    if( z < 0 )
        z += VolumeSize;

    x = x%VolumeSize;
    y = y%VolumeSize;
    z = z%VolumeSize;

    int index = x + y*VolumeSize + z*VolumeSize*VolumeSize;

    pTexels[index].x = (char)(Normal.x * 128.0f);
    pTexels[index].y = (char)(Normal.y * 128.0f);
    pTexels[index].z = (char)(Normal.z * 128.0f);
}

//--------------------------------------------------------------------------------------
// Create and blur a noise volume texture
//--------------------------------------------------------------------------------------
HRESULT CreateNoiseVolume( ID3D10Device* pd3dDevice, UINT VolumeSize )
{
    HRESULT hr = S_OK;

    D3D10_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = new CHAR4[ VolumeSize*VolumeSize*VolumeSize ];
    InitData.SysMemPitch = VolumeSize*sizeof(CHAR4);
    InitData.SysMemSlicePitch = VolumeSize*VolumeSize*sizeof(CHAR4);

    // Gen a bunch of random values
    CHAR4* pData = (CHAR4*)InitData.pSysMem;
    for( UINT i=0; i<VolumeSize*VolumeSize*VolumeSize; i++ )
    {
        pData[i].w = (char)(RPercent() * 128.0f);
    }

    // Generate normals from the density gradient
    float heightAdjust = 0.5f;
    D3DXVECTOR3 Normal;
    D3DXVECTOR3 DensityGradient;
    for( UINT z=0; z<VolumeSize; z++ )
    {
        for( UINT y=0; y<VolumeSize; y++ )
        {
            for( UINT x=0; x<VolumeSize; x++ )
            {
                DensityGradient.x = GetDensity( x+1, y, z, pData, VolumeSize ) - GetDensity( x-1, y, z, pData, VolumeSize )/heightAdjust;
                DensityGradient.y = GetDensity( x, y+1, z, pData, VolumeSize ) - GetDensity( x, y-1, z, pData, VolumeSize )/heightAdjust;
                DensityGradient.z = GetDensity( x, y, z+1, pData, VolumeSize ) - GetDensity( x, y, z-1, pData, VolumeSize )/heightAdjust;

                D3DXVec3Normalize( &Normal, &DensityGradient );
                SetNormal( Normal, x,y,z, pData, VolumeSize );
            }
        }
    }

    D3D10_TEXTURE3D_DESC desc;
    desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = 0;
    desc.Depth = desc.Height = desc.Width = VolumeSize;
    desc.Format = DXGI_FORMAT_R8G8B8A8_SNORM;
    desc.MipLevels = 1;
    desc.MiscFlags = 0;
    desc.Usage = D3D10_USAGE_IMMUTABLE;
    V_RETURN( pd3dDevice->CreateTexture3D( &desc, &InitData, &g_pNoiseVolume ) );

    D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
    ZeroMemory( &SRVDesc, sizeof(SRVDesc) );
    SRVDesc.Format = desc.Format;
    SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE3D;
    SRVDesc.Texture3D.MipLevels = desc.MipLevels;
    SRVDesc.Texture3D.MostDetailedMip = 0;
    V_RETURN(pd3dDevice->CreateShaderResourceView( g_pNoiseVolume, &SRVDesc, &g_pNoiseVolumeRV ));
    
    SAFE_DELETE_ARRAY( InitData.pSysMem );
    return hr;
}

//--------------------------------------------------------------------------------------
// Update the particle VB using UpdateSubresource
//--------------------------------------------------------------------------------------
void QuickDepthSort(DWORD* indices, float* depths, int lo, int hi)
{
//  lo is the lower index, hi is the upper index
//  of the region of array a that is to be sorted
    int i=lo, j=hi;
    float h;
    int index;
    float x=depths[(lo+hi)/2];

    //  partition
    do
    {    
        while (depths[i] > x) i++; 
        while (depths[j] < x) j--;
        if (i<=j)
        {
            h=depths[i]; depths[i]=depths[j]; depths[j]=h;
            index = indices[i]; indices[i] = indices[j]; indices[j] = index;
            i++; j--;
        }
    } while (i<=j);

    //  recursion
    if (lo<j) QuickDepthSort(indices, depths, lo, j);
    if (i<hi) QuickDepthSort(indices, depths, i, hi);
}

//--------------------------------------------------------------------------------------
// Sort the particle buffer
//--------------------------------------------------------------------------------------
void SortParticleBuffer( D3DXVECTOR3 vEye, D3DXVECTOR3 vDir )
{
    if( !g_pParticleDepthArray || !g_pCPUParticleIndices )
        return;

    // assume vDir is normalized
    D3DXVECTOR3 vToParticle;
    //init indices and depths
    for( UINT i=0; i<MAX_PARTICLES; i++ )
    {
        g_pCPUParticleIndices[i] = i;
        vToParticle = g_pCPUParticles[i].Pos - vEye;
        g_pParticleDepthArray[i] = D3DXVec3Dot( &vDir, &vToParticle );
    }

    // Sort
    QuickDepthSort(g_pCPUParticleIndices, g_pParticleDepthArray, 0, MAX_PARTICLES-1);
}

//--------------------------------------------------------------------------------------
// Create a VB for particles
//--------------------------------------------------------------------------------------
void AdvanceParticles( ID3D10Device* pd3dDevice, double fTime, float fTimeDelta )
{
    //emit new particles
    static double fLastEmitTime = 0;
    static UINT iLastParticleEmitted = 0;

    if( !g_bAnimateParticles )
    {
        fLastEmitTime = fTime;
        return;
    }

    float fEmitRate = g_fEmitRate;
    float fParticleMaxSize = g_fParticleMaxSize;
    float fParticleMinSize = g_fParticleMinSize;

    if( PT_VOLUME_HARD == g_ParticleTechnique ||
        PT_VOLUME_SOFT == g_ParticleTechnique )
    {
        fEmitRate *= 3.0f;	//emit 1/3 less particles if we're doing volume
        fParticleMaxSize *= 1.5f;	//1.5x the max radius
        fParticleMinSize *= 1.5f;	//1.5x the min radius
    }

    UINT NumParticlesToEmit = (UINT)( (fTime - fLastEmitTime)/fEmitRate );
    if( NumParticlesToEmit > 0 )
    {
        for( UINT i=0; i<NumParticlesToEmit; i++ )
        {
            EmitParticle( &g_pCPUParticles[iLastParticleEmitted] );
            iLastParticleEmitted = (iLastParticleEmitted+1) % MAX_PARTICLES;
        }
        fLastEmitTime = fTime;
    }

    D3DXVECTOR3 vel;
    float lifeSq = 0;
    for( UINT i=0; i<MAX_PARTICLES; i++ )
    {
        if( g_pCPUParticles[i].Life > -1 )
        {
            // squared velocity falloff
            lifeSq = g_pCPUParticles[i].Life*g_pCPUParticles[i].Life;

            // Slow down by 50% as we age
            vel = g_pCPUParticles[i].Vel * (1 - 0.5f*lifeSq);
            vel.y += 0.5f;	//(add some to the up direction, becuase of buoyancy)

            g_pCPUParticles[i].Pos += vel*fTimeDelta;
            g_pCPUParticles[i].Life += fTimeDelta/g_fParticleLifeSpan;
            g_pCPUParticles[i].Size = fParticleMinSize + (fParticleMaxSize-fParticleMinSize) * g_pCPUParticles[i].Life;

            if( g_pCPUParticles[i].Life > 0.99f )
                g_pCPUParticles[i].Life = -1;
        }
    }
}

//--------------------------------------------------------------------------------------
// Update the particle VB using UpdateSubresource
//--------------------------------------------------------------------------------------
void UpdateParticleBuffers( ID3D10Device* pd3dDevice )
{
    pd3dDevice->UpdateSubresource( g_pParticleVB, NULL, NULL, g_pCPUParticles, 0, 0 );
    pd3dDevice->UpdateSubresource( g_pParticleIB, NULL, NULL, g_pCPUParticleIndices, 0, 0 );
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?