UE5.2、CesiumForUnreal实现加载GeoJson绘制单面

news2024/10/6 4:04:48

文章目录

  • 前言
  • 一、实现目标
  • 二、实现过程
    • 1.实现原理
    • 2.数据读取
    • 3.三角剖分
    • 3.具体代码
  • 4.蓝图测试


前言

UE5、CesiumForUnreal实现加载GeoJson绘制单面(Polygon)功能(StaticMesh方式)


一、实现目标

通过读取本地的Geojson数据,在UE中以staticMeshComponent的形式绘制出面数据,支持Editor和Runtime环境,如下图

singlePolygon

二、实现过程

1.实现原理

首先读取Geojson数据,然后进行三角剖分,最后根据顶点和索引创建StaticMesh。

2.数据读取

本文使用的是polygon转linestring格式的Geojson线状数据文件,特别需要注意,转完的数据需要去掉coordinates字段里的一组中括号。在UE中直接读取文本对其进行解析,生成坐标数组。本文数据只考虑一个feature情况,数据坐标格式为wgs84经纬度坐标。

例:{
“type”: “FeatureCollection”,
“name”: “singlePolygon”,
“crs”: { “type”: “name”, “properties”: { “name”: “urn:ogc:def:crs:OGC:1.3:CRS84” } },
“features”: [
{ “type”: “Feature”, “properties”: { “id”: 1 }, “geometry”: { “type”: “MultiLineString”, “coordinates”: [ [ 107.5955545517036, 34.322768426465544 ], [ 108.086216375377106, 34.660927250889173 ], [ 109.133845674571887, 34.448749164976306 ], [ 109.518418455288952, 33.261877996901205 ], [ 109.067540022724117, 32.552407522130054 ], [ 107.734796420583919, 32.738063347303815 ], [ 106.726950512497794, 32.930349737662347 ], [ 106.786625599160786, 33.792323211683374 ], [ 107.025325945812767, 33.938195645748472 ], [ 107.608815682073157, 34.322768426465544 ], [ 107.608815682073157, 34.322768426465544 ],[ 107.5955545517036, 34.322768426465544 ] ] } }
]
}

3.三角剖分

ue不支持直接绘制面,因此需要将面进行三角剖分。为快速的对地理控件点位进行三角剖分,直接使用Mapbox的earcut.hpp耳切算法三角剖分库。
地址:传送门
在这里插入图片描述
将其放到工程中的Source下的某个目录中,本文是放到了Developer文件夹中
在这里插入图片描述

Build.cs配置


using UnrealBuildTool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public class cesiumGeoJson : ModuleRules
{
	public cesiumGeoJson(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

		//PublicIncludePaths.AddRange(new string[] { Path.Combine(ModuleDirectory, "./Source/Engine/Developer") });
	
		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" ,"CesiumRuntime","Json"});

		PrivateDependencyModuleNames.AddRange(new string[] {  });

		// Uncomment if you are using Slate UI
		// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
		
		// Uncomment if you are using online features
		// PrivateDependencyModuleNames.Add("OnlineSubsystem");

		// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
	}
}

3.具体代码

  1. AsinglePolygon_Geojson.h
// Copyright 2020-2021 CesiumGS, Inc. and Contributors

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CesiumGeoreference.h"
#include "singlePolygon_Geojson.generated.h"

UCLASS()
class CESIUMGEOJSON_API AsinglePolygon_Geojson : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	AsinglePolygon_Geojson();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;


	// Current world CesiumGeoreference.
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Entity | Polygon")
		ACesiumGeoreference* Georeference;

	// The selected feature index, current is only for '0', just for demo.
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Entity | Polygon");
	int SelectedFeatureIndex = 0;

	// The data path, that is the relative path of ue game content.
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Entity | Polygon");
	FString GeoJsonPath;

	/**
	 * @breif Test generate polygon.
	 */
	UFUNCTION(CallInEditor, Category = "Entity | Polygon")
		void TestGeneratePolygon();

	/**
	 * @brief Get feature vertices from linestring geojson.
	 */
	void GetCoordinatesFromLineStringGeoJson(const FString& FilePath, int FeatureIndex, TArray<FVector>& Positions);

	/**
	 * @brief Build static polygon mesh component from current data.
	 */
	void BuildPolygonStaticMesh();

private:
	// Verices that crs is unreal world.
	TArray<FVector> GeometryUE;

	// Vertices that crs is geographic wgs 84, epsg 4326.
	TArray<FVector> GeometryGeo;

	// Indices of vertices.
	TArray<uint32> Indices;

};

  1. AsinglePolygon_Geojson.cpp
// Copyright 2020-2021 CesiumGS, Inc. and Contributors


#include "singlePolygon_Geojson.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Engine/Developer/earcut.hpp"
#include "array"

// Sets default values
AsinglePolygon_Geojson::AsinglePolygon_Geojson()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

}

// Called when the game starts or when spawned
void AsinglePolygon_Geojson::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void AsinglePolygon_Geojson::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

void AsinglePolygon_Geojson::TestGeneratePolygon()
{
	// Check file path and georeference is exist.
	if (!Georeference || GeoJsonPath.IsEmpty())
	{
		UE_LOG(LogTemp, Warning, TEXT("CesiumGeoreference or GeoJsonPath is valid, please check!"));
		return;
	}

	// Get the full path of file;
	FString FilePath = UKismetSystemLibrary::GetProjectDirectory() + GeoJsonPath;

	GetCoordinatesFromLineStringGeoJson(FilePath, 0, GeometryGeo);

	// First and last is the same point.
	GeometryGeo.Pop();

	// Triangulation
	std::vector<std::vector<std::array<double, 2>>> Polygon;
	std::vector<std::array<double, 2>> Points;
	for (FVector& Item : GeometryGeo)
	{
		std::array<double, 2> CurPoint = { Item.X, Item.Y };
		Points.push_back(CurPoint);

		// Convert coord from geo to ue.
		
		FVector PointUE = Georeference->TransformLongitudeLatitudeHeightPositionToUnreal(Item);
		GeometryUE.Push(PointUE);
	}

	// Current is just for simply polygon.
	Polygon.push_back(Points);
	std::vector<uint32_t> CalculateIndices = mapbox::earcut(Polygon);

	for (uint32_t Item : CalculateIndices)
	{
		Indices.Push(Item);
	}

	// Build static mesh.
	BuildPolygonStaticMesh();
}

void AsinglePolygon_Geojson::GetCoordinatesFromLineStringGeoJson(
	const FString& FilePath, int FeatureIndex, TArray<FVector>& Positions)
{
	// Check file exist.
	if (!FPaths::FileExists(FilePath)) {
		UE_LOG(LogTemp, Warning, TEXT("GeoJson file don't exist!"));
		return;
	}

	// Clear
	GeometryUE.Empty();
	GeometryGeo.Empty();
	Indices.Empty();

	FString FileString;
	FFileHelper::LoadFileToString(FileString, *FilePath);

	TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(FileString);
	TSharedPtr<FJsonObject> Root;

	// Check deserialize
	if (!FJsonSerializer::Deserialize(JsonReader, Root)) {
		return;
	}

	if (Root->HasField(TEXT("features"))) {
		TArray<TSharedPtr<FJsonValue>> Features = Root->GetArrayField(TEXT("features"));

		// Check feature exist
		if (Features.Num() < 1 || Features.Num() < (FeatureIndex + 1)) {
			return;
		}

		TSharedPtr<FJsonObject> Feature = Features[FeatureIndex]->AsObject();

		if (Feature->HasField(TEXT("geometry"))) {
			TSharedPtr<FJsonObject> Geometry = Feature->GetObjectField(TEXT("geometry"));

			if (Geometry->HasField(TEXT("coordinates"))) {
				TArray<TSharedPtr<FJsonValue>> Coordinates = Geometry->GetArrayField(TEXT("coordinates"));


				for (auto Item : Coordinates) {
					auto Coordinate = Item->AsArray();
					FVector Position;

					// Check coord array is 2 or 3.
					if (Coordinate.Num() == 2) {
						// If don't have z value, add target value for z.
						Position = FVector(Coordinate[0]->AsNumber(), Coordinate[1]->AsNumber(), 5000);
					}
					else if (Coordinate.Num() == 3)
					{
						Position = FVector(Coordinate[0]->AsNumber(), Coordinate[1]->AsNumber(), Coordinate[2]->AsNumber());
					}

					Positions.Emplace(Position);
				}
			}
		}
	}
}

void AsinglePolygon_Geojson::BuildPolygonStaticMesh()
{
	UStaticMeshComponent* pStaticMeshComponent = NewObject<UStaticMeshComponent>(this);
	pStaticMeshComponent->SetFlags(RF_Transient);
	pStaticMeshComponent->SetWorldLocationAndRotation(FVector(0, 0, 0), FRotator(0, 0, 0));
	UStaticMesh* pStaticMesh = NewObject<UStaticMesh>(pStaticMeshComponent);
	pStaticMesh->NeverStream = true;
	pStaticMeshComponent->SetStaticMesh(pStaticMesh);

	FStaticMeshRenderData* pRenderData = new FStaticMeshRenderData();
	pRenderData->AllocateLODResources(1);
	FStaticMeshLODResources& LODResourece = pRenderData->LODResources[0];
	TArray<FStaticMeshBuildVertex> StaticMeshBuildVertices;
	StaticMeshBuildVertices.SetNum(GeometryUE.Num());

	// Calculate bounds
	glm::dvec3 MinPosition{ std::numeric_limits<double>::max() };
	glm::dvec3 MaxPosition{ std::numeric_limits<double>::lowest() };

	// Vertices
	for (int i = 0; i < GeometryUE.Num(); i++)
	{
		FStaticMeshBuildVertex& Vertex = StaticMeshBuildVertices[i];
		Vertex.Position = FVector3f(GeometryUE[i]);
		Vertex.UVs[0] = FVector2f(0, 0);
		Vertex.TangentX = FVector3f(0, 1, 0);
		Vertex.TangentY = FVector3f(1, 0, 0);
		Vertex.TangentZ = FVector3f(0, 0, 1);

		// Calculate max and min position;
		MinPosition.x = glm::min<double>(MinPosition.x, GeometryUE[i].X);
		MinPosition.y = glm::min<double>(MinPosition.y, GeometryUE[i].Y);
		MinPosition.z = glm::min<double>(MinPosition.z, GeometryUE[i].Z);
		MaxPosition.x = glm::max<double>(MaxPosition.x, GeometryUE[i].X);
		MaxPosition.y = glm::max<double>(MaxPosition.y, GeometryUE[i].Y);
		MaxPosition.z = glm::max<double>(MaxPosition.z, GeometryUE[i].Z);
	}

	// Bounding box
	FBox BoundingBox(FVector3d(MinPosition.x, MinPosition.y, MinPosition.z), FVector3d(MaxPosition.x, MaxPosition.y, MaxPosition.z));
	BoundingBox.GetCenterAndExtents(pRenderData->Bounds.Origin, pRenderData->Bounds.BoxExtent);

	LODResourece.bHasColorVertexData = false;
	LODResourece.VertexBuffers.PositionVertexBuffer.Init(StaticMeshBuildVertices);
	LODResourece.VertexBuffers.StaticMeshVertexBuffer.Init(StaticMeshBuildVertices, 1);
	LODResourece.IndexBuffer.SetIndices(Indices, EIndexBufferStride::AutoDetect);

	LODResourece.bHasDepthOnlyIndices = false;
	LODResourece.bHasReversedIndices = false;
	LODResourece.bHasReversedDepthOnlyIndices = false;

	FStaticMeshSectionArray& Sections = LODResourece.Sections;
	FStaticMeshSection& Section = Sections.AddDefaulted_GetRef();
	Section.bEnableCollision = true;
	Section.bCastShadow = true;
	Section.NumTriangles = Indices.Num() / 3;
	Section.FirstIndex = 0;
	Section.MinVertexIndex = 0;
	Section.MaxVertexIndex = Indices.Num() - 1;

	// Add material
	UMaterialInterface* CurMaterial = LoadObject<UMaterialInterface>(nullptr, TEXT("Material'/Game/Martials/M_Polygon.M_Polygon'"));  //此处的材质需要手动在编辑器中创建,而后在c++代码中引用
	UMaterialInstanceDynamic* CurMaterialIns = UMaterialInstanceDynamic::Create(CurMaterial, nullptr);
	CurMaterialIns->AddToRoot();
	CurMaterialIns->TwoSided = true;
	FName CurMaterialSlotName = pStaticMesh->AddMaterial(CurMaterialIns);
	int32 CurMaterialIndex = pStaticMesh->GetMaterialIndex(CurMaterialSlotName);
	Section.MaterialIndex = CurMaterialIndex;

	// Todo:Build Collision

	pStaticMesh->SetRenderData(TUniquePtr<FStaticMeshRenderData>(pRenderData));
	pStaticMesh->InitResources();
	pStaticMesh->CalculateExtendedBounds();
	pRenderData->ScreenSize[0].Default = 1.0f;
	pStaticMesh->CreateBodySetup();
	pStaticMeshComponent->SetMobility(EComponentMobility::Movable);
	pStaticMeshComponent->SetupAttachment(this->RootComponent);
	pStaticMeshComponent->RegisterComponent();
}

代码中提到的材质,查看路径操作如下:
在这里插入图片描述

4.蓝图测试

  1. 基于c++类生成蓝图类,并放到世界场景中测试。
    在这里插入图片描述
  2. 在该细节面板中配置相关设置,主要是需要CesiumGeoference,用于WGS84和UE世界坐标的转换。已经Geojson数据的存放相对路径(相对于Game工程目录),不支持Geojson多feature。如下:
    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1406453.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Go学习】Ginkgo测试框架学习实践 + 问题记录 + 怎么解决(0)

1、ginkgo测试框架介绍&#xff1a;https://onsi.github.io/ginkgo/ 2、重点是学习实践 问题记录 怎么解决 3、送福利&#xff1a;国内好用的ChatGpt有很多&#xff0c;比如&#xff1a;天工、文心一言、讯飞星火、通义万相等 1. 安装 xxxmacdeMacBook-Pro-3  /Volumes/mac…

关于网络模型的笔记

1. OSI 七层参考模型&#xff1a; 简介&#xff1a; 七层模型&#xff0c;亦称 OSI&#xff08;Open System Interconnection&#xff09;参考模型&#xff0c;即开放式系统互联。参考模型 是国际标准化组织&#xff08;ISO&#xff09;制定的一个用于计算机或通信系统间互联…

mc我的世界服务器多少钱一个月?

我的世界服务器多少钱一个月&#xff1f;低至7元一个月&#xff0c;阿里云和腾讯云均可以选择mc服务器&#xff0c;阿里云2核2G3M轻量服务器87元一年、腾讯云轻量2核2G3M服务器88元一年&#xff0c;阿里云ECS云服务器2核2G3M带宽99元一年&#xff0c;腾讯云2核4G5M带宽轻量应用…

IPoE技术汇总

在国内并没有遇到这么多的IPoE&#xff08;IP over Ethernet&#xff09;技术&#xff0c;可能也是因为我来日本多年了&#xff0c;没有接触国内的IPv4 over IPv6的技术&#xff0c;感觉国内IPv4地址紧张&#xff0c;用的传统NAT和PPPoE非常多&#xff0c;大多数设备还是建立在…

docker - compose 部署 Tomcat

目录 下面用 docker-compose 方法部署 Tomcat 1、准备工作 2、部署容器 启动容器 查看新启动的容器 3、总结 下面用 docker-compose 方法部署 Tomcat 1、准备工作 先在主机创建工作文件夹&#xff0c;为了放置 Tomcat 的配置文件等。创建文件夹的方法&#xff0c;自己搞…

【linux】远程桌面连接到Debian

远程桌面连接到Debian系统&#xff0c;可以使用以下几种工具&#xff1a; 1. VNC (Virtual Network Computing) VNC&#xff08;Virtual Network Computing&#xff09;是一种流行的远程桌面解决方案&#xff0c;它使用RFB&#xff08;Remote Framebuffer Protocol&#xff0…

上位机图像处理和嵌入式模块部署(流程)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 前面我们说过&#xff0c;传统图像处理的方法&#xff0c;一般就是pccamera的处理方式。camera本身只是提供基本的raw data数据&#xff0c;所有的…

sublime text 开启vim模式

sublime text 开启vim模式 打开配置文件 mac下点击菜单栏 Sublime Text -> Settings... -> Settings 修改配置文件并保存 添加配置 // 开启vim模式 "ignored_packages": [// "Vintage", ], // 以命令模式打开文件 "vintage_start_in_comman…

【博客搭建记录贴】问题记录:hexo : 无法加载文件 C:\Program Files\nodejs\hexo.ps1,因为在此系统上禁止运行脚本。

1&#xff0c;背景 hexo&#xff08;博客框架&#xff09;安装完毕之后&#xff0c;正准备看看其版本&#xff0c;发现出现下面脚本禁止运行的错误。 PS C:\Users\PC> hexo -v hexo : 无法加载文件 C:\Program Files\nodejs\hexo.ps1&#xff0c;因为在此系统上禁止运行脚…

【Android】在WSA安卓子系统中进行新实验性功能试用与抓包(2311.4.5.0)

前言 在根据几篇22和23的WSA抓包文章进行尝试时遇到了问题&#xff0c;同时发现新版Wsa的一些实验性功能能优化抓包配置时的一些步骤&#xff0c;因而写下此篇以作记录。 Wsa版本&#xff1a;2311.40000.5.0 本文出现的项目&#xff1a; MagiskOnWSALocal MagiskTrustUserCer…

自然语言处理--概率最大中文分词

自然语言处理附加作业--概率最大中文分词 一、理论描述 中文分词是指将中文句子或文本按照语义和语法规则进行切分成词语的过程。在中文语言中&#xff0c;词语之间没有明显的空格或标点符号来分隔&#xff0c;因此需要通过分词工具或算法来实现对中文文本的分词处理。分词的…

RPC教程 3.服务注册

0. 前言 这一节要熟悉Go中的反射reflet&#xff0c;不然可能比较难理解。在使用到反射的一些函数时候&#xff0c;我也会讲解关于反射reflect的用法。 1.引出反射reflect 这个例子是表示客户端想使用Foo服务的Sum方法。即是想调用Foo结构体的Sum方法。 client.Call("F…

uniapp 在static/index.html中添加全局样式

前言 略 在static/index.html中添加全局样式 <style>div {background-color: #ccc;} </style>static/index.html源码&#xff1a; <!DOCTYPE html> <html lang"zh-CN"><head><meta charset"utf-8"><meta http-…

Java线程池,看这一篇足够

目录一览 Java线程池1. Executors提供6个线程池快捷创建方式2. ThreadPoolExecutor的7大参数3. 自定义线程池 Java线程池 上一篇《Async注解的注意事项》说到Async注解要配合自定义线程池一起使用&#xff0c;这一节说下Java的线程池。 1. Executors提供6个线程池快捷创建方式…

基于springboot+vue的小徐影城管理系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 项目介绍…

一个处理Range List的面试题解法

大纲 题目解法Rangeaddremove ToolsRangeListaddremove 代码 最近看到一个比较有意思的面试题。题目不算难&#xff0c;但是想把效率优化做好&#xff0c;也没那么容易。 我们先看下题目 题目 // Task: Implement a class named RangeList // A pair of integers define a ra…

K8S搭建(centos)三、安装Docker

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…

完美调试android-goldfish(linux kernel) aarch64的方法

环境要求 Mac m1Mac m1 中 虚拟机安装aarch64 ubuntu22.02Mac m1安装OrbStack&#xff0c;并在其中安装 ubuntu20.04&#xff08;x86_64&#xff09; 构建文件系统 在虚拟机 aarch64 ubuntu22.02中构建 安装必要的库 sudo apt-get install libncurses5-dev build-essenti…

工业空调协议转BACnet网关BA108

随着通讯技术和控制技术的发展&#xff0c;为了实现楼宇的高效、智能化管理&#xff0c;集中监控管理已成为楼宇智能管理发展的必然趋势。在此背景下&#xff0c;高性能的楼宇暖通数据传输解决方案——协议转换网关应运而生&#xff0c;广泛应用于楼宇自控和暖通空调系统应用中…

RK3399平台开发系列讲解(USB篇)USB协议层数据格式

🚀返回专栏总目录 文章目录 一、USB 资料二、协议层2.1、字节/位传输顺序2.2、SOP起始包2.3、SYNC同步域2.4、EOP 结束包(End of Packet)2.5、Packet内容2.5.1、PID:2.5.2、地址:2.5.3、帧号:2.5.4、数据域: