9UTreeHeightsFromImageComponent::UTreeHeightsFromImageComponent()
11 PrimaryComponentTick.bCanEverTick =
false;
14void UTreeHeightsFromImageComponent::BeginPlay()
19void UTreeHeightsFromImageComponent::CacheTexture()
22 FString TexturePath = TEXT(
"/Game/Agrarsense/Maps/RovaniemiForest/CHM_RovaniemiForest_rescaled.CHM_RovaniemiForest_rescaled");
23 treeMapImage = Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(),
nullptr, *TexturePath));
26 FTexture2DMipMap& Mip = treeMapImage->GetPlatformData()->Mips[0];
27 void* Data = Mip.BulkData.Lock(LOCK_READ_ONLY);
28 int32 Size = Mip.BulkData.GetBulkDataSize();
30 Pixels.AddUninitialized(Size);
32 std::memcpy(Pixels.GetData(), Data, Size);
34 Mip.BulkData.Unlock();
36 UE_LOG(LogTemp, Warning, TEXT(
"Tree image cached.."));
37 UE_LOG(LogTemp, Warning, TEXT(
"Pixels data len %i"), Pixels.Num());
39 Width = treeMapImage->GetSizeX();
40 Height = treeMapImage->GetSizeY();
42 UE_LOG(LogTemp, Warning, TEXT(
"Source image resolution: %i x %i"), Width, Height);
47float UTreeHeightsFromImageComponent::EuclideanDistance(
const FColor& Color1,
const FColor& Color2)
55 return FMath::Sqrt(FMath::Square(R2 - R1) + FMath::Square(G2 - G1) + FMath::Square(B2 - B1));
58FColor UTreeHeightsFromImageComponent::FindClosestColor(
const FColor& TargetColor,
const TMap<int32, FColor>& ColorMap)
60 float MinDistance = FLT_MAX;
63 for (
const auto& Pair : ColorMap)
65 float Distance = EuclideanDistance(TargetColor, Pair.Value);
66 if (Distance < MinDistance)
68 MinDistance = Distance;
69 ClosestColor = Pair.Value;
76int32 UTreeHeightsFromImageComponent::GetColorFromPixel(FVector point)
84 UE_LOG(LogTemp, Warning, TEXT(
"Returning from Pixels are empty!"));
101 if (point.X <= 0 || point.Y <= 0)
103 UE_LOG(LogTemp, Warning, TEXT(
"Returning from point less than 0"));
129 if (point.X > Width || point.Y > Height)
132 UE_LOG(LogTemp, Warning, TEXT(
"Returning from point over the resolution"));
137 if (Width <= 0 || Height <= 0)
141 UE_LOG(LogTemp, Warning, TEXT(
"Returning from width <= 0"));
149 const int64 Base = ((int64)point.Y * (int64)Width + (int64)point.X) * 4;
151 if (Base >= 0 && Base + 3 < Pixels.Num())
154 const uint8 B = Pixels[(int32)Base + 0];
155 const uint8 G = Pixels[(int32)Base + 1];
156 const uint8 R = Pixels[(int32)Base + 2];
159 const FColor PixelColor(R, G, B);
161 const FColor Closest = FindClosestColor(PixelColor, colorHeightRovaniemi);
162 for (
const auto& Pair : colorHeightRovaniemi)
164 if (Pair.Value == Closest)
166 UE_LOG(LogTemp, Warning, TEXT(
"This tree is : %i m"), Pair.Key);
173 UE_LOG(LogTemp, Warning, TEXT(
"Index out of range"));
214void UTreeHeightsFromImageComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
216 Super::PostEditChangeProperty(PropertyChangedEvent);
219 if (PropertyChangedEvent.Property !=
nullptr && PropertyChangedEvent.Property->GetName() ==
"GenerateTrigger")
224 GenerateTrigger =
false;