I am trying to take a snapshot of a USceneCaptureComponent2D and save to an image, I implemented my approach both in the scene and in code, in the case of connecting the components in the scene, I did the following:
- connected the USceneCaptureComponent2D to a render target in its properties
- applied the render target to a material
- then applied the material to a plane
This is working as supposed.
In the case of implementing a similar approach in the code, I made a node that takes the USceneCaptureComponent2D and the RenderTarget, sets the RenderTarget as a TextureTarget for the CaptureConponent, Captures the scene as follwos:
TArray<FColor> ALedCommBase::GetCameraViewAvgColor(USceneCaptureComponent2D *nativeSceneCapture, UTextureRenderTarget2D *nativeRenderTarget2D){
nativeSceneCapture->TextureTarget = nativeRenderTarget2D;
nativeSceneCapture->CaptureScene();
nativeRenderTarget2D->UpdateResourceImmediate();
UTexture2D* Aux2DTex = UTexture2D::CreateTransient(nativeRenderTarget2D->SizeX, nativeRenderTarget2D->SizeY, PF_A16B16G16R16);//PF_B8G8R8A8);
#if WITH_EDITORONLY_DATA
Aux2DTex->MipGenSettings = TextureMipGenSettings::TMGS_NoMipmaps;
#endif
//Turn off Gamma-correction
Aux2DTex->SRGB = nativeRenderTarget2D->SRGB;;
// Saving data to image
TArray<FColor> SurfData;
FRenderTarget* TargetResource = nativeRenderTarget2D->GameThread_GetRenderTargetResource();
FString FileLocation = FString("Snapshot");
TargetResource->ReadPixels(SurfData);
SavePixelBufferToFile(SurfData,FileLocation, nativeRenderTarget2D->SizeX, nativeRenderTarget2D->SizeY);
Aux2DTex->PlatformData->Mips[0].BulkData.Unlock();
Aux2DTex->UpdateResource();
return SurfData;
}
the other function I use to do the part of saving the color array to an image is as follows:
void ALedCommBase::SavePixelBufferToFile(TArray<FColor> RawPixels, FString& FileLocation, int32 pWidth, int32 pHeight)
{
// Save Texture to jpg
FString GameDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir());
FString PicsDir = FPaths::Combine(*GameDir, TEXT("ScreenShots"));
FString Filename = FileLocation+TEXT("-DC-") + FGuid::NewGuid().ToString();
FileLocation = FPaths::Combine(*PicsDir, *Filename);
TSharedPtr<IImageWrapper> ImageWrapper = NULL;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);
FileLocation += ".png";
if (ImageWrapper.IsValid())
{
if (ImageWrapper->SetRaw(RawPixels.GetData() , RawPixels.Num() * sizeof(FColor), pWidth, pHeight, ERGBFormat::RGBA, 8))
{
FFileHelper::SaveArrayToFile(ImageWrapper->GetCompressed(), *FileLocation);
}
}
}
But I get a black image always.
Does anybody know if I am skipping something?
Here is a screenshot of the node.