Hello,
I’m working on a C++ function who will generate a texture based on a serie of ones from a ContentBrowser folder during a specific asset import.
To generate my new texture I use a UTextureRenderTarget2D and a UMaterial. The idea is simple: put all the textures next to the previous one horizontaly.
I have a first version working but the quality is very bad.
The problem is not from the inputs because each texture source is 1024x1024 px, and the generated one is dynamicaly sized to put a 512x512 px space for each source texture.
In my Material the preview quality is very good. So it seems that the problem is from the rendering by the RenderTarget.
Do anyone have an idea of what I’m doing wrong ?
One of the input textures:
Result:
The current code:
// ARGS
FString SavePath;
TArray<UTexture2D*> TexturesArray;
// END ARGS
// Step 1: Setup
UTextureRenderTarget2D* RenderTarget = NewObject<UTextureRenderTarget2D>(GEngine->GetWorldContexts()[0].World());
RenderTarget->RenderTargetFormat = ETextureRenderTargetFormat::RTF_RGBA8_SRGB;
// Size calculation here. In this example the size is 8192 x 512 px
RenderTarget->InitAutoFormat(X, Y);
RenderTarget->UpdateResourceImmediate(true);
UMaterial* BakingMaterialSource = Cast<UMaterial>(ImporterUtils::LoadObjectByPath("/MyPlugin/M_BakeCombinedTexture.M_BakeCombinedTexture"));
UMaterialInstanceDynamic* BakeMaterial = UMaterialInstanceDynamic::Create(BakingMaterialSource, GEngine->GetWorldContexts()[0].World());
BakeMaterial->SetTextureParameterValue(FName("RTImage"), RenderTarget);
BakeMaterial->SetScalarParameterValue(FName("NumImages"), TexturesArray.Num());
// Step 2: Build Texture
for (int i = 0; i < TexturesArray.Num(); i++) {
BakeMaterial->SetTextureParameterValue(FName("SourceImage"), TexturesArray[i]);
BakeMaterial->SetScalarParameterValue(FName("CurrentIndex"), i);
UKismetRenderingLibrary::DrawMaterialToRenderTarget(GEngine->GetWorldContexts()[0].World(), RenderTarget, BakeMaterial);
}
// Step 3: Save to disk
UTexture2D* Asset = UKismetRenderingLibrary::RenderTargetCreateStaticTexture2DEditorOnly(RenderTarget, SavePath, TextureCompressionSettings::TC_Default, TextureMipGenSettings::TMGS_FromTextureGroup);
if (Asset == nullptr) return;
Asset->LODBias = 0;
Asset->CompressionNoAlpha = true;
Asset->SRGB = true;
Asset->NeverStream = true;
Asset->PostEditChange();