void AWorldCreator::BeginPlay()
{
Super::BeginPlay();
UTexture2D* texture = CreateTexture();
ALandscape* targetLandscape = Cast<ALandscape>(UGameplayStatics::GetActorOfClass(GetWorld(), ALandscape::StaticClass()));
if (targetLandscape && RenderTarget && HeightBrushMI && texture) {
// Tracing으로 위치 찾기
FHitResult outHit;
FVector traceStart = GetActorLocation();
FVector traceEnd = traceStart + (FVector::UpVector * -9999.f);
FCollisionQueryParams collisionParam;
collisionParam.AddIgnoredActor(GetOwner());
GetWorld()->LineTraceSingleByChannel(outHit, traceStart, traceEnd, ECollisionChannel::ECC_Visibility, collisionParam);
// HeightBrushMI 준비
UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(HeightBrushMI, GetWorld());
DynamicMaterial->SetTextureParameterValue(FName("TextureParam"), texture);
targetLandscape->UpdateAllComponentMaterialInstances();
MaterialConverter->SetMaterial(0, DynamicMaterial);
// RenderTarget 위에 HeightBrushMI 마스킹
if (outHit.GetActor()) {
UCanvas* canvas;
FVector origin;
FVector boxExtent;
targetLandscape->GetActorBounds(false, origin, boxExtent);
FVector2D HitScreenPosition = FVector2D(
abs(targetLandscape->GetActorLocation().X - outHit.Location.X) / (boxExtent.X * 2),
abs(targetLandscape->GetActorLocation().Y - outHit.Location.Y) / (boxExtent.Y * 2)
);
FVector2D screenSize = FVector2D(RenderTarget->SizeX, RenderTarget->SizeY);
FDrawToRenderTargetContext targetContext;
UKismetRenderingLibrary::BeginDrawCanvasToRenderTarget(GetWorld(), RenderTarget, canvas, screenSize, targetContext);
UKismetRenderingLibrary::ClearRenderTarget2D(GetWorld(), RenderTarget);
FCanvasMaterialTransform CanvasMaterialTransform = GetCanvasMaterialTransform(HitScreenPosition, screenSize, 1.0f);
canvas->K2_DrawMaterial(MaterialConverter->GetMaterial(0), CanvasMaterialTransform.Position, CanvasMaterialTransform.Size, FVector2D(0, 0));
UKismetRenderingLibrary::EndDrawCanvasToRenderTarget(GetWorld(), targetContext);
}
}
else {
if (targetLandscape == nullptr) UE_LOG(LogTemp, Warning, TEXT("Null targetLandscape"));
if (RenderTarget == nullptr) UE_LOG(LogTemp, Warning, TEXT("Null RenderTarget"));
if (texture == nullptr) UE_LOG(LogTemp, Warning, TEXT("Null texture"));
}
}
UTexture2D* AWorldCreator::CreateTexture() {
uint8* pixels = (uint8*)malloc(Height * Width * 4); // x4 because it's RGBA. 4 integers, one for Red, one for Green, one for Blue, one for Alpha
...
UPackage* package = CreatePackage(nullptr, *pathPackage);
...
UTexture2D* texture = NewObject<UTexture2D>(package, textureName, RF_Public | RF_Standalone);
...
free(pixels);
pixels = NULL;
return texture;
}