UE4 RenderTexture转UTexture2D

运行时RenderTexture转UTexture2D

#include "Engine/TextureRenderTarget2D.h"

UTexture2D* ATester::GetCurGameraRT(UTextureRenderTarget2D* RT)
{
    
    
    if (RT != nullptr)
    {
    
    
        UTexture2D* Result = NULL;

        // Check render target size is valid and power of two.
        const bool bIsValidSize = (RT->SizeX != 0 && !(RT->SizeX & (RT->SizeX - 1)) &&
        RT->SizeY != 0 && !(RT->SizeY & (RT->SizeY - 1)));
        // The r2t resource will be needed to read its surface contents
        FRenderTarget* RenderTarget = RT->GameThread_GetRenderTargetResource();

        const EPixelFormat PixelFormat = RT->GetFormat();
        ETextureSourceFormat TextureFormat = TSF_Invalid;
        switch (PixelFormat)
            {
    
    
                case PF_B8G8R8A8:
                    TextureFormat = TSF_BGRA8;
                    break;
                case PF_FloatRGBA:
                    TextureFormat = TSF_RGBA16F;
                    break;
                case PF_G8:
                    TextureFormat = TSF_G8;
                    break;
                default:
                    {
    
    
                        return nullptr;
                    }
            }

        // exit if source is not compatible.
        if (bIsValidSize == false || RenderTarget == NULL || TextureFormat == TSF_Invalid)
        {
    
    
            return Result;
        }

        // create the 2d texture
        Result = UTexture2D::CreateTransient(RT->SizeX, RT->SizeY, PF_B8G8R8A8);

        // Lock the texture so it can be modified
        auto& BulkD = Result->PlatformData->Mips[0].BulkData;
        uint8* MipData = static_cast<uint8*>(BulkD.Lock(LOCK_READ_WRITE));

        TextureCompressionSettings CompressionSettingsForTexture = TC_HDR;

        TArray<FColor> SurfData;
        RenderTarget->ReadPixels(SurfData);

        // read the 2d surface
        if (TextureFormat == TSF_BGRA8)
        {
    
    
            check(BulkD.GetBulkDataSize() == SurfData.Num() * sizeof(FColor));
            FMemory::Memcpy(MipData, SurfData.GetData(), BulkD.GetBulkDataSize());
        }
        Result->LODGroup = TextureGroup::TEXTUREGROUP_UI;
        Result->SRGB = false;
        Result->CompressionSettings = CompressionSettingsForTexture;
        Result->Filter = TextureFilter::TF_Trilinear;
        BulkD.Unlock();
        Result->UpdateResource();
        return Result;
    }
    return nullptr;
}

猜你喜欢

转载自blog.csdn.net/t1370620378/article/details/128192436