Files
UnrealEngineUWP/Engine/Plugins/Experimental/MeshModelingToolset/Source/MeshModelingToolsEditorOnly/Private/SimplifyMeshTool.cpp
Ryan Schmidt 3019b90219 GeometryProcessing: Add option to do explicit geometric tolerance/deviation checking in TMeshSimplification. Checks edge midpoints and face centroids against a fixed tolerance.
MeshModelingToolset: expose new option in SimplifyMeshOp and SimplifyMeshTool
#rb david.hill
#rnx
#jira none
#preflight 6099fb752032ee00016bee43

[CL 16274273 by Ryan Schmidt in ue5-main branch]
2021-05-11 13:17:19 -04:00

304 lines
10 KiB
C++

// Copyright Epic Games, Inc. All Rights Reserved.
#include "SimplifyMeshTool.h"
#include "InteractiveToolManager.h"
#include "Properties/RemeshProperties.h"
#include "ToolBuilderUtil.h"
#include "ToolSetupUtil.h"
#include "Util/ColorConstants.h"
#include "DynamicMesh3.h"
#include "MeshDescriptionToDynamicMesh.h"
#include "DynamicMeshToMeshDescription.h"
#include "AssetUtils/MeshDescriptionUtil.h"
#include "AssetGenerationUtil.h"
#include "SceneManagement.h" // for FPrimitiveDrawInterface
#include "TargetInterfaces/MaterialProvider.h"
#include "TargetInterfaces/MeshDescriptionCommitter.h"
#include "TargetInterfaces/MeshDescriptionProvider.h"
#include "TargetInterfaces/PrimitiveComponentBackedTarget.h"
//#include "ProfilingDebugging/ScopedTimers.h" // enable this to use the timer.
#include "Modules/ModuleManager.h"
#include "IMeshReductionManagerModule.h"
#include "IMeshReductionInterfaces.h"
#if WITH_EDITOR
#include "Misc/ScopedSlowTask.h"
#endif
#include "ExplicitUseGeometryMathTypes.h" // using UE::Geometry::(math types)
using namespace UE::Geometry;
#define LOCTEXT_NAMESPACE "USimplifyMeshTool"
DEFINE_LOG_CATEGORY_STATIC(LogMeshSimplification, Log, All);
/*
* ToolBuilder
*/
USingleSelectionMeshEditingTool* USimplifyMeshToolBuilder::CreateNewTool(const FToolBuilderState& SceneState) const
{
return NewObject<USimplifyMeshTool>(SceneState.ToolManager);
}
/*
* Tool
*/
USimplifyMeshToolProperties::USimplifyMeshToolProperties()
{
SimplifierType = ESimplifyType::QEM;
TargetMode = ESimplifyTargetType::Percentage;
TargetPercentage = 50;
TargetCount = 1000;
TargetEdgeLength = 5.0;
bReproject = false;
bPreventNormalFlips = true;
bDiscardAttributes = false;
bGeometricConstraint = false;
bShowWireframe = true;
bShowGroupColors = false;
GroupBoundaryConstraint = EGroupBoundaryConstraint::Ignore;
MaterialBoundaryConstraint = EMaterialBoundaryConstraint::Ignore;
}
void USimplifyMeshTool::Setup()
{
UInteractiveTool::Setup();
// hide component and create + show preview
IPrimitiveComponentBackedTarget* TargetComponent = Cast<IPrimitiveComponentBackedTarget>(Target);
TargetComponent->SetOwnerVisibility(false);
Preview = NewObject<UMeshOpPreviewWithBackgroundCompute>(this, "Preview");
Preview->Setup(this->TargetWorld, this);
FComponentMaterialSet MaterialSet;
Cast<IMaterialProvider>(Target)->GetMaterialSet(MaterialSet);
Preview->ConfigureMaterials( MaterialSet.Materials,
ToolSetupUtil::GetDefaultWorkingMaterial(GetToolManager())
);
{
// if in editor, create progress indicator dialog because building mesh copies can be slow (for very large meshes)
// this is especially needed because of the copy we make of the meshdescription; for Reasons, copying meshdescription is pretty slow
#if WITH_EDITOR
static const FText SlowTaskText = LOCTEXT("SimplifyMeshInit", "Building mesh simplification data...");
FScopedSlowTask SlowTask(3.0f, SlowTaskText);
SlowTask.MakeDialog();
// Declare progress shortcut lambdas
auto EnterProgressFrame = [&SlowTask](int Progress)
{
SlowTask.EnterProgressFrame((float)Progress);
};
#else
auto EnterProgressFrame = [](int Progress) {};
#endif
IMeshDescriptionProvider* TargetMeshProvider = Cast<IMeshDescriptionProvider>(Target);
OriginalMeshDescription = MakeShared<FMeshDescription, ESPMode::ThreadSafe>(*TargetMeshProvider->GetMeshDescription());
// make sure the mesh description has tangents.
const bool bUseTangents = true;
if (bUseTangents)
{
// if the source was imported with auto-generate tangents, the mesh description tangents won't have been populated
FMeshBuildSettings BuildSettings;
BuildSettings.bRecomputeNormals = true;
BuildSettings.bRecomputeTangents = true;
// this will only generate tangents if the mesh description was missing them
UE::MeshDescription::InitializeAutoGeneratedAttributes(*OriginalMeshDescription, &BuildSettings);
}
EnterProgressFrame(1);
OriginalMesh = MakeShared<FDynamicMesh3, ESPMode::ThreadSafe>();
FMeshDescriptionToDynamicMesh Converter;
// convert with tangent overlay
Converter.Convert(TargetMeshProvider->GetMeshDescription(), *OriginalMesh, bUseTangents);
EnterProgressFrame(2);
OriginalMeshSpatial = MakeShared<FDynamicMeshAABBTree3, ESPMode::ThreadSafe>(OriginalMesh.Get(), true);
}
Preview->PreviewMesh->SetTransform(TargetComponent->GetWorldTransform());
Preview->PreviewMesh->SetTangentsMode(EDynamicMeshTangentCalcType::AutoCalculated);
Preview->PreviewMesh->UpdatePreview(OriginalMesh.Get());
// initialize our properties
SimplifyProperties = NewObject<USimplifyMeshToolProperties>(this);
SimplifyProperties->RestoreProperties(this);
AddToolPropertySource(SimplifyProperties);
SimplifyProperties->WatchProperty(SimplifyProperties->bShowGroupColors,
[this](bool bNewValue) { UpdateVisualization(); });
SimplifyProperties->WatchProperty(SimplifyProperties->bShowWireframe,
[this](bool bNewValue) { UpdateVisualization(); });
MeshStatisticsProperties = NewObject<UMeshStatisticsProperties>(this);
AddToolPropertySource(MeshStatisticsProperties);
Preview->OnMeshUpdated.AddLambda([this](UMeshOpPreviewWithBackgroundCompute* Compute)
{
MeshStatisticsProperties->Update(*Compute->PreviewMesh->GetPreviewDynamicMesh());
});
UpdateVisualization();
Preview->InvalidateResult();
SetToolDisplayName(LOCTEXT("ToolName", "Simplify"));
GetToolManager()->DisplayMessage(
LOCTEXT("OnStartTool", "Reduce the number of triangles in the selected Mesh using various strategies."),
EToolMessageLevel::UserNotification);
}
bool USimplifyMeshTool::CanAccept() const
{
return Super::CanAccept() && Preview->HaveValidResult();
}
void USimplifyMeshTool::Shutdown(EToolShutdownType ShutdownType)
{
SimplifyProperties->SaveProperties(this);
Cast<IPrimitiveComponentBackedTarget>(Target)->SetOwnerVisibility(true);
FDynamicMeshOpResult Result = Preview->Shutdown();
if (ShutdownType == EToolShutdownType::Accept)
{
GenerateAsset(Result);
}
}
void USimplifyMeshTool::OnTick(float DeltaTime)
{
Preview->Tick(DeltaTime);
}
TUniquePtr<FDynamicMeshOperator> USimplifyMeshTool::MakeNewOperator()
{
TUniquePtr<FSimplifyMeshOp> Op = MakeUnique<FSimplifyMeshOp>();
Op->bDiscardAttributes = SimplifyProperties->bDiscardAttributes;
Op->bPreventNormalFlips = SimplifyProperties->bPreventNormalFlips;
Op->bPreserveSharpEdges = SimplifyProperties->bPreserveSharpEdges;
Op->bAllowSeamCollapse = !SimplifyProperties->bPreserveSharpEdges;
Op->bReproject = SimplifyProperties->bReproject;
Op->SimplifierType = SimplifyProperties->SimplifierType;
Op->TargetCount = SimplifyProperties->TargetCount;
Op->TargetEdgeLength = SimplifyProperties->TargetEdgeLength;
Op->TargetMode = SimplifyProperties->TargetMode;
Op->TargetPercentage = SimplifyProperties->TargetPercentage;
Op->MeshBoundaryConstraint = (EEdgeRefineFlags)SimplifyProperties->MeshBoundaryConstraint;
Op->GroupBoundaryConstraint = (EEdgeRefineFlags)SimplifyProperties->GroupBoundaryConstraint;
Op->MaterialBoundaryConstraint = (EEdgeRefineFlags)SimplifyProperties->MaterialBoundaryConstraint;
Op->bGeometricDeviationConstraint = SimplifyProperties->bGeometricConstraint;
Op->GeometricTolerance = SimplifyProperties->GeometricTolerance;
FTransform LocalToWorld = Cast<IPrimitiveComponentBackedTarget>(Target)->GetWorldTransform();
Op->SetTransform(LocalToWorld);
Op->OriginalMeshDescription = OriginalMeshDescription;
Op->OriginalMesh = OriginalMesh;
Op->OriginalMeshSpatial = OriginalMeshSpatial;
IMeshReductionManagerModule& MeshReductionModule = FModuleManager::Get().LoadModuleChecked<IMeshReductionManagerModule>("MeshReductionInterface");
Op->MeshReduction = MeshReductionModule.GetStaticMeshReductionInterface();
return Op;
}
void USimplifyMeshTool::Render(IToolsContextRenderAPI* RenderAPI)
{
FPrimitiveDrawInterface* PDI = RenderAPI->GetPrimitiveDrawInterface();
FTransform Transform = Cast<IPrimitiveComponentBackedTarget>(Target)->GetWorldTransform(); //Actor->GetTransform();
if (SimplifyProperties->bShowUVSeams)
{
FColor UVSeamColor(15, 240, 15); // same color used in mesh inspector
const FDynamicMesh3* TargetMesh = Preview->PreviewMesh->GetPreviewDynamicMesh();
if (TargetMesh->HasAttributes())
{
float PDIScale = RenderAPI->GetCameraState().GetPDIScalingFactor();
const FDynamicMeshUVOverlay* UVOverlay = TargetMesh->Attributes()->PrimaryUV();
for (int eid : TargetMesh->EdgeIndicesItr())
{
if (UVOverlay->IsSeamEdge(eid))
{
FVector3d A, B;
TargetMesh->GetEdgeV(eid, A, B);
PDI->DrawLine(Transform.TransformPosition((FVector)A), Transform.TransformPosition((FVector)B),
UVSeamColor, 0, 2.0 * PDIScale, 1.0f, true);
}
}
}
}
}
void USimplifyMeshTool::OnPropertyModified(UObject* PropertySet, FProperty* Property)
{
if ( Property )
{
if ( Property->GetFName() == GET_MEMBER_NAME_CHECKED(USimplifyMeshToolProperties, bShowUVSeams) )
{
// nothing required. Render() handles this case
return;
}
if ( ( Property->GetFName() == GET_MEMBER_NAME_CHECKED(USimplifyMeshToolProperties, bShowWireframe) ) ||
( Property->GetFName() == GET_MEMBER_NAME_CHECKED(USimplifyMeshToolProperties, bShowGroupColors) ) )
{
UpdateVisualization();
}
else
{
Preview->InvalidateResult();
}
}
}
void USimplifyMeshTool::UpdateVisualization()
{
Preview->PreviewMesh->EnableWireframe(SimplifyProperties->bShowWireframe);
FComponentMaterialSet MaterialSet;
if (SimplifyProperties->bShowGroupColors)
{
MaterialSet.Materials = {ToolSetupUtil::GetSelectionMaterial(GetToolManager())};
Preview->PreviewMesh->SetTriangleColorFunction([this](const FDynamicMesh3* Mesh, int TriangleID)
{
return LinearColors::SelectFColor(Mesh->GetTriangleGroup(TriangleID));
},
UPreviewMesh::ERenderUpdateMode::FastUpdate);
}
else
{
Cast<IMaterialProvider>(Target)->GetMaterialSet(MaterialSet);
Preview->PreviewMesh->ClearTriangleColorFunction(UPreviewMesh::ERenderUpdateMode::FastUpdate);
}
Preview->ConfigureMaterials(MaterialSet.Materials,
ToolSetupUtil::GetDefaultWorkingMaterial(GetToolManager()));
}
void USimplifyMeshTool::GenerateAsset(const FDynamicMeshOpResult& Result)
{
GetToolManager()->BeginUndoTransaction(LOCTEXT("SimplifyMeshToolTransactionName", "Simplify Mesh"));
check(Result.Mesh.Get() != nullptr);
Cast<IMeshDescriptionCommitter>(Target)->CommitMeshDescription([&Result](const IMeshDescriptionCommitter::FCommitterParams& CommitParams)
{
FDynamicMeshToMeshDescription Converter;
Converter.Convert(Result.Mesh.Get(), *CommitParams.MeshDescriptionOut);
});
GetToolManager()->EndUndoTransaction();
}
#undef LOCTEXT_NAMESPACE