3 Commits

63 changed files with 784 additions and 1938 deletions
-9
View File
@@ -1,9 +1,6 @@
# Prerequisites
*.d
.idea/
.vs/
# Compiled Object files
*.slo
*.lo
@@ -34,15 +31,9 @@
*.out
*.app
*.umap
# UE file types
*.uasset filter=lfs diff=lfs merge=lfs -text
*.umap filter=lfs diff=lfs merge=lfs -text
SpeckleUnrealProject/Binaries/
SpeckleUnrealProject/Intermediate/
SpeckleUnrealProject/Plugins/SpeckleUnreal/Binaries/
SpeckleUnrealProject/Plugins/SpeckleUnreal/Intermediate/
SpeckleUnrealProject/Saved/
SpeckleUnrealProject/.vs/
SpeckleUnrealProject/SpeckleUnrealProject.sln.DotSettings.user
+3
View File
@@ -0,0 +1,3 @@
{
"CurrentProjectSetting": "No Configurations"
}
Binary file not shown.
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
{
"ExpandedNodes": [
"",
"\\SpeckleUnreal",
"\\SpeckleUnreal\\Source"
],
"PreviewInSolutionExplorer": false
}
BIN
View File
Binary file not shown.
+17 -197
View File
@@ -1,201 +1,21 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
MIT License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (c) 2020 mobiusnode
1. Definitions.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 AEC Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+31 -8
View File
@@ -1,18 +1,29 @@
# Speckle Unreal
# SpeckleUnreal
[![Twitter Follow](https://img.shields.io/twitter/follow/SpeckleSystems?style=social)](https://twitter.com/SpeckleSystems) [![Community forum users](https://img.shields.io/discourse/users?server=https%3A%2F%2Fspeckle.community&style=flat-square&logo=discourse&logoColor=white)](https://speckle.community) [![website](https://img.shields.io/badge/https://-speckle.systems-royalblue?style=flat-square)](https://speckle.systems) [![docs](https://img.shields.io/badge/docs-speckle.guide-orange?style=flat-square&logo=read-the-docs&logoColor=white)](https://speckle.guide/dev/)
[![Version](https://img.shields.io/badge/Version-v0.1.0-orange)](https://github.com/mobiusnode/SpeckleUnreal) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen)](http://makeapullrequest.com)
Plugin for Unreal Engine 4 to import objects from Speckle v2.
Our Team is developing a Speckle plugin and interoperability transport schema for UE4. Our goal is to enable Revit/Dynamo and Rhino/Grasshopper to send + receive geometry to UE4 for visualization. Our current priority is to establish and release a data sender (TO UE4). Were also working on receiver methods, however our initial focus is on Rhino/Grasshopper to UE4 translation and the attachment of UE4-specific metadata to the core JSON blobs in transport.
In this repository you will find the source code, assets and project settings of the SpeckleUnreal plugin for Unreal Engine app development (Unreal Engine 4.25.1 or newer recommended).
Screencast of an example: https://user-images.githubusercontent.com/2551138/114720093-61403e00-9d40-11eb-8045-6e8ca656554d.mp4
# Useful Links
Use the following links to access resources related to bug reporting, issues, feature requests, and general questions regarding SpeckleUnreal. Future releases may not contain these links & note.
## Speckle Unreal Server
https://speckle.mobiusnode.io
## Discourse Forums (Bugs, Issues, etc.)
https://discourse.mobiusnode.io
## SpeckleUnreal Slack Workspace
https://speckle-works-unreal.slack.com
## YouTub Demo & Tutorial - Getting Started
https://bit.ly/3ehHQE6
## NOTICE
* Tested on Windows, Unreal Engine v4.26 and Visual Studio Community 2019
* Tested on Windows and MacOS and Linux.
* Only displays meshes. Breps are converted using their display values.
* Does not use the Speckle Kit workflow as conversions all happen in C++.
@@ -26,8 +37,20 @@ Screencast of an example: https://user-images.githubusercontent.com/2551138/1147
We will eventually look to distributing the plugin officially on the Unreal Engine Marketplace but for now you'll need to install the plugin manually like this.
## Credits
Based off the original Unreal integration for Speckle v1 by Mark and Jak which can be found here: [https://github.com/mobiusnode/SpeckleUnreal](https://github.com/mobiusnode/SpeckleUnreal).
---
https://user-images.githubusercontent.com/2551138/114720051-571e3f80-9d40-11eb-9099-d3394747a1d3.mp4
## Roadmap
> Roadmap is subject to change. Last reviewed 10th of July 2020.
| Version | Defining Feature |
| ------- | -------------------------------------------------------------------------------- |
| ~0.1~ | ~First prototype release as Unreal Engine plugin~ |
| 0.2 | New component workflow and custom materials assigned via inspector~ |
| 0.3 | Spawn geometry in transform heirarchy based on layer data |
| 0.4 | User login API, get Stream API and no dependency on a local install of Speckle |
| 0.5 | Rendering Rule API |
| 0.6 | Support Lines, Points, Numbers and Text|
| 0.7 | Local caching of Speckle streams |
| 0.8 | Implement Sender API |
| 1.0 | Production ready (out of preview) |
@@ -1 +0,0 @@
@@ -14,6 +14,3 @@ AppliedDefaultGraphicsPerformance=Maximum
[/Script/IOSRuntimeSettings.IOSRuntimeSettings]
RemoteServerName=
[/Script/EngineSettings.GameMapsSettings]
GameDefaultMap=/Game/SpeckleScene.SpeckleScene
@@ -1,70 +1,3 @@
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=F126DB004A50E31B2A69D284041A10E1
[/Script/UnrealEd.ProjectPackagingSettings]
Build=IfProjectHasCode
BuildConfiguration=PPBC_Development
BuildTarget=
StagingDirectory=(Path="C:/Users/migkotzidis_local/Desktop/SpeckleBuild")
FullRebuild=False
ForDistribution=False
IncludeDebugFiles=False
BlueprintNativizationMethod=Disabled
bIncludeNativizedAssetsInProjectGeneration=False
bExcludeMonolithicEngineHeadersInNativizedCode=False
UsePakFile=True
bUseIoStore=False
bGenerateChunks=False
bGenerateNoChunks=False
bChunkHardReferencesOnly=False
bForceOneChunkPerFile=False
MaxChunkSize=0
bBuildHttpChunkInstallData=False
HttpChunkInstallDataDirectory=(Path="")
PakFileCompressionFormats=
PakFileAdditionalCompressionOptions=
HttpChunkInstallDataVersion=
IncludePrerequisites=True
IncludeAppLocalPrerequisites=False
bShareMaterialShaderCode=True
bDeterministicShaderCodeOrder=False
bSharedMaterialNativeLibraries=True
ApplocalPrerequisitesDirectory=(Path="")
IncludeCrashReporter=False
InternationalizationPreset=English
-CulturesToStage=en
+CulturesToStage=en
LocalizationTargetCatchAllChunkId=0
bCookAll=False
bCookMapsOnly=False
bCompressed=False
bSkipEditorContent=False
bSkipMovies=False
-IniKeyBlacklist=KeyStorePassword
-IniKeyBlacklist=KeyPassword
-IniKeyBlacklist=rsa.privateexp
-IniKeyBlacklist=rsa.modulus
-IniKeyBlacklist=rsa.publicexp
-IniKeyBlacklist=aes.key
-IniKeyBlacklist=SigningPublicExponent
-IniKeyBlacklist=SigningModulus
-IniKeyBlacklist=SigningPrivateExponent
-IniKeyBlacklist=EncryptionKey
-IniKeyBlacklist=IniKeyBlacklist
-IniKeyBlacklist=IniSectionBlacklist
+IniKeyBlacklist=KeyStorePassword
+IniKeyBlacklist=KeyPassword
+IniKeyBlacklist=rsa.privateexp
+IniKeyBlacklist=rsa.modulus
+IniKeyBlacklist=rsa.publicexp
+IniKeyBlacklist=aes.key
+IniKeyBlacklist=SigningPublicExponent
+IniKeyBlacklist=SigningModulus
+IniKeyBlacklist=SigningPrivateExponent
+IniKeyBlacklist=EncryptionKey
+IniKeyBlacklist=IniKeyBlacklist
+IniKeyBlacklist=IniSectionBlacklist
+MapsToCook=(FilePath="/Game/SpeckleScene")
Binary file not shown.

Before

Width:  |  Height:  |  Size: 852 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

@@ -1,6 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "ISpeckleReceiver.h"
// Add default functionality here for any IISpeckleReceiver functions that are not pure virtual.
@@ -1,116 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "SpeckleRESTHandlerComponent.h"
// Sets default values for this component's properties
USpeckleRESTHandlerComponent::USpeckleRESTHandlerComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
// ...
}
// Called when the game starts
void USpeckleRESTHandlerComponent::BeginPlay()
{
Super::BeginPlay();
// cache speckleManager for runtime purposes
SpeckleManager = Cast<ASpeckleUnrealManager>(GetOwner());
}
void USpeckleRESTHandlerComponent::ImportSpeckleObject(int CurrIndex)
{
#if WITH_EDITOR
SpeckleManager = Cast<ASpeckleUnrealManager>(GetOwner());
#endif
if(SpeckleManager)
{
auto Commits = SpeckleManager->ArrayOfCommits;
// check if within bounds and import
if(Commits.Num() > 0 && (CurrIndex <= Commits.Num() && CurrIndex >= 0))
{
const auto InputObjectRefID = Commits[CurrIndex].ReferenceObjectID;
SpeckleManager->ObjectID = InputObjectRefID;
SpeckleManager->ImportSpeckleObject();
return;
}
UE_LOG(LogTemp, Warning, TEXT("[SPECKLE LOG]: Speckle unreal commits array index out of bounds"));
}
}
void USpeckleRESTHandlerComponent::FetchListOfCommits(const FString& BranchName)
{
#if WITH_EDITOR
SpeckleManager = Cast<ASpeckleUnrealManager>(GetOwner());
#endif
if(SpeckleManager)
{
//FString PostPayload = "{\"query\": \"query{stream (id: \\\"" + SpeckleManager->StreamID + "\\\"){id name commits {totalCount cursor items {id referencedObject authorName message branchName} } }}\"}";
FString PostPayload = "{\"query\": \"query{stream (id: \\\"" + SpeckleManager->StreamID + "\\\"){branch(name: \\\"" + BranchName + "\\\"){commits{items {id referencedObject authorName message branchName} } }}}\"}";
TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> HandleResponse = [this](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{ SpeckleManager->OnCommitsItemsResponseReceived(Request, Response, bWasSuccessful); };
SpeckleManager->FetchStreamItems(PostPayload, HandleResponse);
}
}
void USpeckleRESTHandlerComponent::FetchListOfStreams()
{
#if WITH_EDITOR
SpeckleManager = Cast<ASpeckleUnrealManager>(GetOwner());
#endif
if(SpeckleManager)
{
FString PostPayload = "{\"query\": \"query{user {streams(limit:20) {totalCount items {id name description}}}}\"}";
TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> HandleResponse = [this](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{ SpeckleManager->OnStreamItemsResponseReceived(Request, Response, bWasSuccessful); };
SpeckleManager->FetchStreamItems(PostPayload, HandleResponse);
}
}
void USpeckleRESTHandlerComponent::FetchListOfBranches()
{
#if WITH_EDITOR
SpeckleManager = Cast<ASpeckleUnrealManager>(GetOwner());
#endif
if(SpeckleManager)
{
FString PostPayload = "{\"query\": \"query{\\n stream (id: \\\"" + SpeckleManager->StreamID + "\\\"){\\n id\\n name\\n branches{\\n totalCount\\n cursor\\n items{\\n id\\n name\\n description\\n}\\n }\\n }\\n}\"}";
TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> HandleResponse = [this](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{ SpeckleManager->OnBranchesItemsResponseReceived(Request, Response, bWasSuccessful); };
SpeckleManager->FetchStreamItems(PostPayload, HandleResponse);
}
}
void USpeckleRESTHandlerComponent::FetchGlobals()
{
#if WITH_EDITOR
SpeckleManager = Cast<ASpeckleUnrealManager>(GetOwner());
#endif
if(SpeckleManager)
{
FString PostPayload = "{\"query\": \"query{stream (id: \\\"" + SpeckleManager->StreamID + "\\\"){branch(name: \\\"" + "globals" + "\\\"){commits{totalCount items{referencedObject}}}}}\"}";
TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> HandleResponse = [this](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{ SpeckleManager->OnGlobalStreamItemsResponseReceived(Request, Response, bWasSuccessful); };
SpeckleManager->FetchStreamItems(PostPayload, HandleResponse);
}
}
@@ -1,5 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "SpeckleStructs.h"
@@ -2,15 +2,19 @@
#include "SpeckleUnreal.h"
IMPLEMENT_MODULE(FSpeckleUnrealModule, SpeckleUnreal)
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
void FSpeckleUnrealModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
}
void FSpeckleUnrealModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FSpeckleUnrealModule, SpeckleUnreal)
@@ -3,13 +3,16 @@
#include "SpeckleUnrealLayer.h"
USpeckleUnrealLayer::USpeckleUnrealLayer()
ASpeckleUnrealLayer::ASpeckleUnrealLayer()
{
Scene = CreateDefaultSubobject<USceneComponent>("Root");
RootComponent = Scene;
}
void USpeckleUnrealLayer::Init(FString NewLayerName, int32 NewStartIndex, int32 NewObjectCount)
void ASpeckleUnrealLayer::Init(FString NewLayerName, int32 NewStartIndex, int32 NewObjectCount)
{
SetActorLabel(NewLayerName);
LayerName = NewLayerName;
LayerColor = FLinearColor(FMath::FRandRange(0, 1), FMath::FRandRange(0, 1), FMath::FRandRange(0, 1), 1);
StartIndex = NewStartIndex;
@@ -1,22 +1,12 @@
#include "SpeckleUnrealManager.h"
#include "HttpManager.h"
#include "UObject/ConstructorHelpers.h"
#include "Dom/JsonObject.h"
// Sets default values
ASpeckleUnrealManager::ASpeckleUnrealManager()
{
static ConstructorHelpers::FObjectFinder<UMaterial> SpeckleMaterial(TEXT("Material'/SpeckleUnreal/SpeckleMaterial.SpeckleMaterial'"));
static ConstructorHelpers::FObjectFinder<UMaterial> SpeckleGlassMaterial(TEXT("Material'/SpeckleUnreal/SpeckleGlassMaterial.SpeckleGlassMaterial'"));
//When the object is constructed, Get the HTTP module
Http = &FHttpModule::Get();
// default conversion is millimeters to centimeters because streams tend to be in ml and unreal is in cm by defaults
ScaleFactor = 0.1;
World = AActor::GetWorld();
DefaultMeshOpaqueMaterial = SpeckleMaterial.Object;
DefaultMeshTransparentMaterial = SpeckleGlassMaterial.Object;
ScaleFactor = 0.1;
}
// Called when the game starts or when spawned
@@ -25,552 +15,242 @@ void ASpeckleUnrealManager::BeginPlay()
Super::BeginPlay();
World = GetWorld();
if (ImportAtRuntime)
ImportSpeckleObject();
GetStream();
}
/*Import the Speckle object*/
void ASpeckleUnrealManager::ImportSpeckleObject()
void ASpeckleUnrealManager::SetUpGetRequest(TSharedRef<IHttpRequest> Request)
{
FString url = ServerUrl + "/objects/" + StreamID + "/" + ObjectID;
FHttpRequestRef Request = Http->CreateRequest();
Request->SetVerb("GET");
Request->SetHeader("Accept", TEXT("text/plain"));
Request->SetHeader("Authorization", "Bearer " + AuthToken);
Request->OnProcessRequestComplete().BindUObject(this, &ASpeckleUnrealManager::OnStreamTextResponseReceived);
Request->SetURL(url);
Request->ProcessRequest();
}
void ASpeckleUnrealManager::OnStreamTextResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed: " + Response->GetContentAsString());
return;
}
auto responseCode = Response->GetResponseCode();
if (responseCode != 200)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, FString::Printf(TEXT("Error response. Response code %d"), responseCode));
return;
}
FString response = Response->GetContentAsString();
// ParseIntoArray is very inneficient for large strings.
// https://docs.unrealengine.com/en-US/API/Runtime/Core/Containers/FString/ParseIntoArrayLines/index.html
// https://answers.unrealengine.com/questions/81697/reading-text-file-line-by-line.html
// Can be fixed by setting the size of the array
int lineCount = 0;
for (const TCHAR* ptr = *response; *ptr; ptr++)
if (*ptr == '\n')
lineCount++;
TArray<FString> lines;
lines.Reserve(lineCount);
response.ParseIntoArray(lines, TEXT("\n"), true);
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, FString::Printf(TEXT("[Speckle] Parsing %d downloaded objects..."), lineCount));
for (auto& line : lines)
{
FString objectId, objectJson;
if (!line.Split("\t", &objectId, &objectJson))
continue;
TSharedPtr<FJsonObject> jsonObject;
TSharedRef<TJsonReader<>> jsonReader = TJsonReaderFactory<>::Create(objectJson);
if (!FJsonSerializer::Deserialize(jsonReader, jsonObject))
continue;
SpeckleObjects.Add(objectId, jsonObject);
}
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, FString::Printf(TEXT("[Speckle] Converting %d objects..."), lineCount));
ImportObjectFromCache(SpeckleObjects[ObjectID]);
for (auto& m : CreatedSpeckleMeshes)
{
if (InProgressSpeckleMeshes.Contains(m.Key) && InProgressSpeckleMeshes[m.Key] == m.Value)
continue;
if (m.Value->Scene) // actors removed by the user in the editor have the Scene set to nullptr
m.Value->Destroy();
}
CreatedSpeckleMeshes = InProgressSpeckleMeshes;
InProgressSpeckleMeshes.Empty();
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, FString::Printf(TEXT("[Speckle] Objects imported successfully. Created %d Actors"), CreatedSpeckleMeshes.Num()));
}
ASpeckleUnrealMesh* ASpeckleUnrealManager::GetExistingMesh(const FString &objectId)
{
if (InProgressSpeckleMeshes.Contains(objectId))
return InProgressSpeckleMeshes[objectId];
if(!CreatedSpeckleMeshes.Contains(objectId))
return nullptr;
ASpeckleUnrealMesh* meshActor = CreatedSpeckleMeshes[objectId];
// Check if actor has been deleted by the user
if (!meshActor || !meshActor->Scene)
return nullptr;
return meshActor;
}
void ASpeckleUnrealManager::ImportObjectFromCache(const TSharedPtr<FJsonObject> speckleObj)
{
if (!speckleObj->HasField("speckle_type"))
return;
if (speckleObj->GetStringField("speckle_type") == "reference" && speckleObj->HasField("referencedId")) {
TSharedPtr<FJsonObject> referencedObj;
if (SpeckleObjects.Contains(speckleObj->GetStringField("referencedId")))
ImportObjectFromCache(SpeckleObjects[speckleObj->GetStringField("referencedId")]);
return;
}
if (!speckleObj->HasField("id"))
return;
FString objectId = speckleObj->GetStringField("id");
FString speckleType = speckleObj->GetStringField("speckle_type");
// UE_LOG(LogTemp, Warning, TEXT("Importing object %s (type %s)"), *objectId, *speckleType);
if (speckleObj->GetStringField("speckle_type") == "Objects.Geometry.Mesh") {
ASpeckleUnrealMesh* mesh = GetExistingMesh(objectId);
if (!mesh)
mesh = CreateMesh(speckleObj);
InProgressSpeckleMeshes.Add(objectId, mesh);
return;
}
if (speckleObj->HasField("@displayMesh"))
{
UMaterialInterface* explicitMaterial = nullptr;
if (speckleObj->HasField("renderMaterial"))
explicitMaterial = CreateMaterial(speckleObj->GetObjectField("renderMaterial"));
// Check if the @displayMesh is an object or an array
const TSharedPtr<FJsonObject> *meshObjPtr;
const TArray<TSharedPtr<FJsonValue>> *meshArrayPtr;
if (speckleObj->TryGetObjectField("@displayMesh", meshObjPtr))
{
TSharedPtr<FJsonObject> meshObj = SpeckleObjects[(*meshObjPtr)->GetStringField("referencedId")];
ASpeckleUnrealMesh* mesh = GetExistingMesh(objectId);
if (!mesh)
mesh = CreateMesh(meshObj, explicitMaterial);
InProgressSpeckleMeshes.Add(objectId, mesh);
}
else if (speckleObj->TryGetArrayField("@displayMesh", meshArrayPtr))
{
for (auto& meshObjValue : *meshArrayPtr)
{
FString meshId = meshObjValue->AsObject()->GetStringField("referencedId");
FString unrealMeshKey = objectId + meshId;
ASpeckleUnrealMesh* mesh = GetExistingMesh(unrealMeshKey);
if (!mesh)
mesh = CreateMesh(SpeckleObjects[meshId], explicitMaterial);
InProgressSpeckleMeshes.Add(unrealMeshKey, mesh);
}
}
}
// Go recursively into all object fields (except @displayMesh)
for (auto& kv : speckleObj->Values)
{
if (kv.Key == "@displayMesh")
continue;
const TSharedPtr< FJsonObject > *subObjectPtr;
if (kv.Value->TryGetObject(subObjectPtr))
{
ImportObjectFromCache(*subObjectPtr);
continue;
}
const TArray<TSharedPtr<FJsonValue>> *subArrayPtr;
if (kv.Value->TryGetArray(subArrayPtr))
{
for (auto& arrayElement : *subArrayPtr)
{
const TSharedPtr<FJsonObject> *arraySubObjPtr;
if (!arrayElement->TryGetObject(arraySubObjPtr))
continue;
ImportObjectFromCache(*arraySubObjPtr);
}
}
}
}
UMaterialInterface* ASpeckleUnrealManager::CreateMaterial(TSharedPtr<FJsonObject> obj)
{
if (obj->GetStringField("speckle_type") == "reference")
obj = SpeckleObjects[obj->GetStringField("referencedId")];
int opacity;
if (obj->TryGetNumberField("opacity", opacity)) {
if (opacity < 1) {
return DefaultMeshTransparentMaterial;
}
}
return DefaultMeshOpaqueMaterial;
}
ASpeckleUnrealMesh* ASpeckleUnrealManager::CreateMesh(TSharedPtr<FJsonObject> obj, UMaterialInterface* explicitMaterial)
{
UE_LOG(LogTemp, Warning, TEXT("Creating mesh for object %s"), *obj->GetStringField("id"));
FString Units = obj->GetStringField("units");
// unreal engine units are in cm by default but the conversion is editable by users so
// this needs to be accounted for later.
ScaleFactor = 1;
if (Units == "meters" || Units == "metres" || Units == "m")
ScaleFactor = 100;
if (Units == "centimeters" || Units == "centimetres" || Units == "cm")
ScaleFactor = 1;
if (Units == "millimeters" || Units == "millimetres" || Units == "mm")
ScaleFactor = 0.1;
if (Units == "yards" || Units == "yd")
ScaleFactor = 91.4402757;
if (Units == "feet" || Units == "ft")
ScaleFactor = 30.4799990;
if (Units == "inches" || Units == "in")
ScaleFactor = 2.5399986;
// The following line can be used to debug large objects
// ScaleFactor = ScaleFactor * 0.1;
FString verticesId = obj->GetArrayField("vertices")[0]->AsObject()->GetStringField("referencedId");
FString facesId = obj->GetArrayField("faces")[0]->AsObject()->GetStringField("referencedId");
TArray<TSharedPtr<FJsonValue>> ObjectVertices = SpeckleObjects[verticesId]->GetArrayField("data");
TArray<TSharedPtr<FJsonValue>> ObjectFaces = SpeckleObjects[facesId]->GetArrayField("data");
#if WITH_EDITOR
World = GetWorld();
#endif
if(World == nullptr)
{
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, FString::Printf(TEXT("Null World")));
return nullptr;
}
AActor* ActorInstance = World->SpawnActor(MeshActor);
ASpeckleUnrealMesh* MeshInstance = (ASpeckleUnrealMesh*)ActorInstance;
// attaches each speckleMesh under this actor (SpeckleManager)
if(MeshInstance != nullptr)
{
MeshInstance->AttachToActor(this, FAttachmentTransformRules::KeepRelativeTransform);
MeshInstance->SetOwner(this);
}
TArray<FVector> ParsedVerticies;
for (size_t j = 0; j < ObjectVertices.Num(); j += 3)
{
ParsedVerticies.Add(FVector
(
(float)(ObjectVertices[j].Get()->AsNumber()) * -1,
(float)(ObjectVertices[j + 1].Get()->AsNumber()),
(float)(ObjectVertices[j + 2].Get()->AsNumber())
) * ScaleFactor);
}
//convert mesh faces into triangle array regardless of whether or not they are quads
TArray<int32> ParsedTriangles;
int32 j = 0;
while (j < ObjectFaces.Num())
{
if (ObjectFaces[j].Get()->AsNumber() == 0)
{
//Triangles
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 2].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
j += 4;
}
else
{
//Quads to triangles
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 2].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 4].Get()->AsNumber());
j += 5;
}
}
// Material priority (low to high): DefaultMeshOpaqueMaterial, renderMaterial set on parent, renderMaterial set on mesh
if (!explicitMaterial)
explicitMaterial = DefaultMeshOpaqueMaterial;
if (obj->HasField("renderMaterial"))
explicitMaterial = CreateMaterial(obj->GetObjectField("renderMaterial"));
MeshInstance->SetMesh(ParsedVerticies, ParsedTriangles, explicitMaterial, FLinearColor::White);
// UE_LOG(LogTemp, Warning, TEXT("Added %d vertices and %d triangles"), ParsedVerticies.Num(), ParsedTriangles.Num());
return MeshInstance;
}
void ASpeckleUnrealManager::OnCommitsItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed: " + Response->GetContentAsString());
return;
}
auto responseCode = Response-> GetResponseCode();
if (responseCode != 200)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red,
FString::Printf(TEXT("Error response. Response code %d"), responseCode));
return;
}
FString response = Response->GetContentAsString();
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response);
ArrayOfCommits.Empty();
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
for(const auto& pair:JsonObject->Values)
{
auto CommitsArr = JsonObject->GetObjectField(TEXT("data"))
->GetObjectField(TEXT("stream"))
->GetObjectField(TEXT("branch"))
->GetObjectField(TEXT("commits"))
->GetArrayField(TEXT("items"));
for (auto commit : CommitsArr)
{
auto ObjID = commit->AsObject()->GetStringField("referencedObject");
auto Message = commit->AsObject()->GetStringField("message");
auto AuthorName = commit->AsObject()->GetStringField("authorName");
auto BranchName = commit->AsObject()->GetStringField("branchName");
auto Commit = FSpeckleCommit(ObjID, AuthorName, Message, BranchName);
ArrayOfCommits.Add(Commit);
}
}
}
OnCommitsProcessed.Broadcast(ArrayOfCommits);
}
void ASpeckleUnrealManager::OnBranchesItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed: " + Response->GetContentAsString());
return;
}
auto responseCode = Response-> GetResponseCode();
if (responseCode != 200)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red,
FString::Printf(TEXT("Error response. Response code %d"), responseCode));
return;
}
FString response = Response->GetContentAsString();
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response);
ArrayOfBranches.Empty();
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
for(const auto& pair:JsonObject->Values)
{
auto BranchesArr = JsonObject->GetObjectField(TEXT("data"))
->GetObjectField(TEXT("stream"))
->GetObjectField(TEXT("branches"))
->GetArrayField(TEXT("items"));
for (auto b : BranchesArr)
{
auto ID = b->AsObject()->GetStringField("id");
auto Name = b->AsObject()->GetStringField("name");
auto Description = b->AsObject()->GetStringField("description");
auto Branch = FSpeckleBranch(ID, Name, Description);
ArrayOfBranches.Add(Branch);
}
}
}
OnBranchesProcessed.Broadcast(ArrayOfBranches);
}
void ASpeckleUnrealManager::OnStreamItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response,
bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed: " + Response->GetContentAsString());
return;
}
auto responseCode = Response-> GetResponseCode();
if (responseCode != 200)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red,
FString::Printf(TEXT("Error response. Response code %d"), responseCode));
return;
}
FString response = Response->GetContentAsString();
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response);
ArrayOfStreams.Empty();
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
for(const auto& pair:JsonObject->Values)
{
auto StreamsArr = JsonObject->GetObjectField(TEXT("data"))
->GetObjectField(TEXT("user"))
->GetObjectField(TEXT("streams"))
->GetArrayField(TEXT("items"));
for (auto s : StreamsArr)
{
auto ID = s->AsObject()->GetStringField("id");
auto Name = s->AsObject()->GetStringField("name");
auto Description = s->AsObject()->GetStringField("description");
auto Stream = FSpeckleStream(ID, Name, Description);
ArrayOfStreams.Add(Stream);
}
}
}
OnStreamsProcessed.Broadcast(ArrayOfStreams);
}
void ASpeckleUnrealManager::OnGlobalStreamItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response,
bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed: " + Response->GetContentAsString());
return;
}
auto responseCode = Response-> GetResponseCode();
if (responseCode != 200)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red,
FString::Printf(TEXT("Error response. Response code %d"), responseCode));
return;
}
FString response = Response->GetContentAsString();
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response);
auto RefObjectID = FString();
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
for(const auto& pair:JsonObject->Values)
{
RefObjectID = JsonObject->GetObjectField(TEXT("data"))
->GetObjectField(TEXT("stream"))
->GetObjectField(TEXT("branch"))
->GetObjectField("commits")
->GetArrayField("items")[0]->AsObject()->GetStringField("referencedObject");
}
TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> TempResponseHandler = [=](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
FString response = Response->GetContentAsString();
TSharedPtr<FJsonObject> JsonObject;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response);
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
for(const auto& pair:JsonObject->Values)
{
auto GlobalObject = JsonObject->GetObjectField(TEXT("data"))
->GetObjectField(TEXT("stream"))
->GetObjectField(TEXT("object"))
->GetObjectField(TEXT("data"));
auto Region = GlobalObject->GetStringField("Region");
auto Lat = GlobalObject->GetNumberField("Latitude");
auto Long = GlobalObject->GetNumberField("Longitude");
FSpeckleGlobals Global = FSpeckleGlobals(RefObjectID, Region, static_cast<float>(Lat), static_cast<float>(Long));
OnGlobalsProcessed.Broadcast(Global);
}
}
};
FString PostPayload = "{\"query\": \"query{stream (id:\\\"" + StreamID + "\\\"){id name description object(id:\\\"" + RefObjectID + "\\\"){id data}}}\"}";
FetchStreamItems(PostPayload, TempResponseHandler);
}
}
void ASpeckleUnrealManager::FetchStreamItems(FString PostPayload, TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> HandleResponse)
{
FString url = ServerUrl + "/graphql";
FHttpRequestRef Request = Http->CreateRequest();
Request->SetVerb(TEXT("POST"));
Request->SetHeader("Accept-Encoding", TEXT("gzip"));
Request->SetHeader("Content-Type", TEXT("application/json"));
Request->SetHeader("Accept", TEXT("application/json"));
Request->SetHeader("DNT", TEXT("1"));
Request->SetHeader("Origin", TEXT("https://speckle.xyz"));
Request->SetHeader("Authorization", "Bearer " + AuthToken);
Request->SetHeader("Authorization", AuthToken);
}
Request->SetContentAsString(PostPayload);
Request->OnProcessRequestComplete().BindLambda([=](
FHttpRequestPtr request,
FHttpResponsePtr response,
bool success)
{ HandleResponse(request, response, success); });
/*Http call*/
void ASpeckleUnrealManager::GetStream()
{
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, "Downloading: " + StreamID);
TSharedRef<IHttpRequest> Request = Http->CreateRequest();
SetUpGetRequest(Request);
Request->OnProcessRequestComplete().BindUObject(this, &ASpeckleUnrealManager::OnStreamResponseReceived);
//This is the url on which to process the request
Request->SetURL(ServerUrl + "streams/" + StreamID);
Request->SetURL(url);
Request->ProcessRequest();
}
void ASpeckleUnrealManager::DeleteObjects()
/*Assigned function on successfull http call*/
void ASpeckleUnrealManager::OnStreamResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
for (auto& m : CreatedSpeckleMeshes)
if (!bWasSuccessful)
{
if (m.Value->Scene)
m.Value->Destroy();
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed");
return;
}
CreatedSpeckleMeshes.Empty();
InProgressSpeckleMeshes.Empty();
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> ResponseJsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, ResponseJsonObject))
{
//Get the value of the json object by field name
FString ResponseMessage = ResponseJsonObject->GetStringField("message");
TSharedPtr<FJsonObject> Stream = ResponseJsonObject->GetObjectField("resource");
FString StreamName = Stream->GetStringField("name");
FString StreamDescription = Stream->GetStringField("description");
FString Units = ResponseJsonObject->GetObjectField("baseProperties")->GetStringField("units").ToLower();
// unreal engine units are in cm by default but the conversion is editable by users so
// this needs to be accounted for later.
if (Units == "meters" || Units == "metres")
ScaleFactor = 100;
if (Units == "centimeters" || Units == "centimetres")
ScaleFactor = 1;
if (Units == "millimeters" || Units == "millimetres")
ScaleFactor = 0.1;
if (Units == "yards")
ScaleFactor = 91.4402757;
if (Units == "feet")
ScaleFactor = 30.4799990;
if (Units == "inches")
ScaleFactor = 2.5399986;
TArray<TSharedPtr<FJsonValue>> LayersInStream = Stream->GetArrayField("layers");
SpeckleUnrealLayers = TArray<ASpeckleUnrealLayer*>();
for (size_t i = 0; i < LayersInStream.Num(); i++)
{
TSharedPtr<FJsonObject> LayerObject = LayersInStream[i]->AsObject();
FString LayerName = LayerObject->GetStringField("name");
int32 StartIndex = LayerObject->GetIntegerField("startIndex");
int32 ObjectCount = LayerObject->GetIntegerField("objectCount");
//USpeckleUnrealLayer NewLayer = USpeckleUnrealLayer(LayerName, StartIndex, ObjectCount);
ASpeckleUnrealLayer* NewLayer = (ASpeckleUnrealLayer*)World->SpawnActor(ASpeckleUnrealLayer::StaticClass());
NewLayer->Init(LayerName, StartIndex, ObjectCount);
SpeckleUnrealLayers.Add(NewLayer);
}
//Output it to the engine
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, "Units: " + FString::SanitizeFloat(ScaleFactor));
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Green, "Status: " + ResponseMessage);
GEngine->AddOnScreenDebugMessage(2, 5.0f, FColor::Green, "Name: " + StreamName);
GEngine->AddOnScreenDebugMessage(3, 5.0f, FColor::Green, "Description: " + StreamDescription);
TArray<TSharedPtr<FJsonValue>> ObjectPlaceholderArray = Stream->GetArrayField("objects");
GetStreamObjects(ObjectPlaceholderArray.Num());
}
else
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Couldn't deserialize Json from stream response");
GEngine->AddOnScreenDebugMessage(2, 10.0f, FColor::Red, Response->GetContentAsString());
}
}
void ASpeckleUnrealManager::GetStreamObjects(int32 objectCount)
{
int32 RequestLimit = 1;
CurrentObjectIndex = 0;
LayerIndex = 0;
for (size_t i = 0; i < objectCount; i += RequestLimit)
{
TSharedRef<IHttpRequest> Request = Http->CreateRequest();
SetUpGetRequest(Request);
Request->OnProcessRequestComplete().BindUObject(this, &ASpeckleUnrealManager::OnStreamObjectResponseReceived);
//This is the url on which to process the request
Request->SetURL(ServerUrl + "streams/" + StreamID + "/objects?limit=" + FString::FromInt(RequestLimit) + "&offset=" + FString::FromInt(i));
Request->ProcessRequest();
}
}
void ASpeckleUnrealManager::OnStreamObjectResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Object Request failed");
return;
}
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> ResponseJsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, ResponseJsonObject))
{
int32 Offset = FCString::Atoi (*Request->GetURLParameter("offset"));
//Get the value of the json object by field name
TArray<TSharedPtr<FJsonValue>> StreamObjects = ResponseJsonObject->GetArrayField("resources");
for (size_t i = 0; i < SpeckleUnrealLayers.Num(); i++)
{
if (Offset >= SpeckleUnrealLayers[i]->StartIndex)
{
if (Offset < (SpeckleUnrealLayers[i]->StartIndex + SpeckleUnrealLayers[i]->ObjectCount))
LayerIndex = i;
}
}
for (size_t i = 0; i < StreamObjects.Num(); i++)
{
TSharedPtr<FJsonObject> StreamObject = StreamObjects[i].Get()->AsObject();
TSharedPtr<FJsonObject> ObjectToConvert = StreamObject;
FString objectType = ObjectToConvert->GetStringField("type");
if (objectType.ToLower().Contains("brep"))
{
ObjectToConvert = StreamObject->GetObjectField("displayValue");
objectType = ObjectToConvert->GetStringField("type");
}
if (objectType.ToLower().Contains("mesh"))
{
AActor* ActorInstance = World->SpawnActor(MeshActor);
ASpeckleUnrealMesh* MeshInstance = (ASpeckleUnrealMesh*)ActorInstance;
TArray<TSharedPtr<FJsonValue>> ObjectVertices = ObjectToConvert->GetArrayField("vertices");
TArray<TSharedPtr<FJsonValue>> ObjectFaces = ObjectToConvert->GetArrayField("faces");
TArray<FVector> ParsedVerticies;
for (size_t j = 0; j < ObjectVertices.Num(); j += 3)
{
ParsedVerticies.Add(FVector
(
(float)(ObjectVertices[j].Get()->AsNumber()) * -1,
(float)(ObjectVertices[j + 1].Get()->AsNumber()),
(float)(ObjectVertices[j + 2].Get()->AsNumber())
) * ScaleFactor);
}
//convert mesh faces into triangle array regardless of whether or not they are quads
TArray<int32> ParsedTriangles;
int32 j = 0;
while (j < ObjectFaces.Num())
{
if (ObjectFaces[j].Get()->AsNumber() == 0)
{
//Triangles
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 2].Get()->AsNumber());
j += 4;
}
else
{
//Quads to triangles
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 2].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 4].Get()->AsNumber());
j += 5;
}
}
if (RandomColorsPerLayer)
MeshInstance->SetMesh(ParsedVerticies, ParsedTriangles, DefaultMeshMaterial, SpeckleUnrealLayers[LayerIndex]->LayerColor);
else
MeshInstance->SetMesh(ParsedVerticies, ParsedTriangles, DefaultMeshMaterial, FLinearColor::White);
UE_LOG(LogTemp, Warning, TEXT("%d"), Offset);
UE_LOG(LogTemp, Warning, TEXT("%s"), *SpeckleUnrealLayers[LayerIndex]->LayerName);
}
}
}
else
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Couldn't deserialize Json from object response");
GEngine->AddOnScreenDebugMessage(2, 10.0f, FColor::Red, Response->GetContentAsString());
}
}
@@ -2,7 +2,6 @@
#include "SpeckleUnrealMesh.h"
#include "Materials/MaterialInstanceDynamic.h"
// Sets default values
ASpeckleUnrealMesh::ASpeckleUnrealMesh()
@@ -12,10 +11,9 @@ ASpeckleUnrealMesh::ASpeckleUnrealMesh()
ProceduralMesh = CreateDefaultSubobject<UProceduralMeshComponent>("Mesh");
ProceduralMesh->SetupAttachment(RootComponent);
}
void ASpeckleUnrealMesh::SetMesh(const TArray<FVector> &Vertices, const TArray<int32> &Triangles, UMaterialInterface* Material, FLinearColor Color)
void ASpeckleUnrealMesh::SetMesh(TArray<FVector> Vertices, TArray<int32> Triangles, UMaterialInterface* Material, FLinearColor Color)
{
ProceduralMesh->ClearAllMeshSections();
@@ -47,7 +45,7 @@ void ASpeckleUnrealMesh::SetMesh(const TArray<FVector> &Vertices, const TArray<i
UMaterialInstanceDynamic* DynMaterial = UMaterialInstanceDynamic::Create(Material, this);
DynMaterial->SetVectorParameterValue("BaseColor", FLinearColor::White);
DynMaterial->SetVectorParameterValue("BaseColor", Color);
ProceduralMesh->SetMaterial(0, DynMaterial);
}
@@ -0,0 +1,304 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "SpeckleUnrealReceiver.h"
// Sets default values
USpeckleUnrealReceiver::USpeckleUnrealReceiver()
{
//When the object is constructed, Get the HTTP module
Http = &FHttpModule::Get();
// default conversion is millimeters to centimeters because streams tend to be in ml and unreal is in cm by defaults
ScaleFactor = 0.1;
}
void USpeckleUnrealReceiver::SetUpGetRequest(TSharedRef<IHttpRequest> Request)
{
Request->SetVerb("GET");
Request->SetHeader("Content-Type", TEXT("application/json"));
Request->SetHeader("Authorization", AuthToken);
}
/*Http call*/
void USpeckleUnrealReceiver::ReceiveStream()
{
World = GetWorld();
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, "Downloading: " + StreamID);
TSharedRef<IHttpRequest> Request = Http->CreateRequest();
SetUpGetRequest(Request);
Request->OnProcessRequestComplete().BindUObject(this, &USpeckleUnrealReceiver::OnStreamResponseReceived);
//This is the url on which to process the request
Request->SetURL(ServerUrl + "streams/" + StreamID);
Request->ProcessRequest();
}
/*Assigned function on successfull http call*/
void USpeckleUnrealReceiver::OnStreamResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Stream Request failed");
return;
}
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> ResponseJsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, ResponseJsonObject))
{
//Get the value of the json object by field name
FString ResponseMessage = ResponseJsonObject->GetStringField("message");
TSharedPtr<FJsonObject> Stream = ResponseJsonObject->GetObjectField("resource");
FString StreamName = Stream->GetStringField("name");
FString StreamDescription = Stream->GetStringField("description");
FString Units = ResponseJsonObject->GetObjectField("baseProperties")->GetStringField("units").ToLower();
// unreal engine units are in cm by default but the conversion is editable by users so
// this needs to be accounted for later.
if (Units == "meters" || Units == "metres")
ScaleFactor = 100;
if (Units == "centimeters" || Units == "centimetres")
ScaleFactor = 1;
if (Units == "millimeters" || Units == "millimetres")
ScaleFactor = 0.1;
if (Units == "yards")
ScaleFactor = 91.4402757;
if (Units == "feet")
ScaleFactor = 30.4799990;
if (Units == "inches")
ScaleFactor = 2.5399986;
TArray<TSharedPtr<FJsonValue>> LayersInStream = Stream->GetArrayField("layers");
SpeckleUnrealLayers = TArray<ASpeckleUnrealLayer*>();
for (size_t i = 0; i < LayersInStream.Num(); i++)
{
TSharedPtr<FJsonObject> LayerObject = LayersInStream[i]->AsObject();
ASpeckleUnrealLayer* NewLayer = (ASpeckleUnrealLayer*)World->SpawnActor(ASpeckleUnrealLayer::StaticClass());
FString LayerName = LayerObject->GetStringField("name");
if (LayerName.Contains("::"))
{
TArray<FString> Parsed = TArray<FString> ();
int32 heirarchySize = LayerName.ParseIntoArray(Parsed, TEXT("::"), true);
LayerName = Parsed[heirarchySize - 1];
FString ParentLayerName = Parsed[heirarchySize - 2];
for (size_t j = 0; j < SpeckleUnrealLayers.Num(); j++)
{
if (SpeckleUnrealLayers[j]->LayerName == ParentLayerName)
{
EAttachmentRule rule = EAttachmentRule();
FAttachmentTransformRules rules = FAttachmentTransformRules(rule, false);
NewLayer->AttachToActor(SpeckleUnrealLayers[j], rules);
break;
}
}
}
int32 StartIndex = LayerObject->GetIntegerField("startIndex");
int32 ObjectCount = LayerObject->GetIntegerField("objectCount");
NewLayer->Init(LayerName, StartIndex, ObjectCount);
SpeckleUnrealLayers.Add(NewLayer);
}
//Output it to the engine
GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, "Units: " + FString::SanitizeFloat(ScaleFactor));
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Green, "Status: " + ResponseMessage);
GEngine->AddOnScreenDebugMessage(2, 5.0f, FColor::Green, "Name: " + StreamName);
GEngine->AddOnScreenDebugMessage(3, 5.0f, FColor::Green, "Description: " + StreamDescription);
TArray<TSharedPtr<FJsonValue>> ObjectPlaceholderArray = Stream->GetArrayField("objects");
GetStreamObjects(ObjectPlaceholderArray.Num());
}
else
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Couldn't deserialize Json from stream response");
GEngine->AddOnScreenDebugMessage(2, 10.0f, FColor::Red, Response->GetContentAsString());
}
}
void USpeckleUnrealReceiver::GetStreamObjects(int32 objectCount)
{
ObjectsReceived = TArray<bool>();
int32 RequestLimit = 1;
CurrentObjectIndex = 0;
LayerIndex = 0;
for (size_t i = 0; i < objectCount; i += RequestLimit)
{
TSharedRef<IHttpRequest> Request = Http->CreateRequest();
SetUpGetRequest(Request);
Request->OnProcessRequestComplete().BindUObject(this, &USpeckleUnrealReceiver::OnStreamObjectResponseReceived);
//This is the url on which to process the request
Request->SetURL(ServerUrl + "streams/" + StreamID + "/objects?limit=" + FString::FromInt(RequestLimit) + "&offset=" + FString::FromInt(i));
ObjectsReceived.Add(false);
Request->ProcessRequest();
}
}
void USpeckleUnrealReceiver::OnStreamObjectResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
int32 Offset = FCString::Atoi(*Request->GetURLParameter("offset"));
if (!bWasSuccessful)
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Object Request failed");
return;
}
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> ResponseJsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, ResponseJsonObject))
{
//Get the value of the json object by field name
TArray<TSharedPtr<FJsonValue>> StreamObjects = ResponseJsonObject->GetArrayField("resources");
for (size_t i = 0; i < SpeckleUnrealLayers.Num(); i++)
{
if (Offset >= SpeckleUnrealLayers[i]->StartIndex)
{
if (Offset < (SpeckleUnrealLayers[i]->StartIndex + SpeckleUnrealLayers[i]->ObjectCount))
LayerIndex = i;
}
}
for (size_t i = 0; i < StreamObjects.Num(); i++)
{
TSharedPtr<FJsonObject> StreamObject = StreamObjects[i].Get()->AsObject();
TSharedPtr<FJsonObject> ObjectToConvert = StreamObject;
FString objectType = ObjectToConvert->GetStringField("type");
if (objectType.ToLower().Contains("brep"))
{
ObjectToConvert = StreamObject->GetObjectField("displayValue");
objectType = ObjectToConvert->GetStringField("type");
}
if (objectType.ToLower().Contains("mesh"))
{
EAttachmentRule rule = EAttachmentRule();
FAttachmentTransformRules rules = FAttachmentTransformRules(rule, false);
ASpeckleUnrealMesh* MeshInstance = World->SpawnActor<ASpeckleUnrealMesh>(ASpeckleUnrealMesh::StaticClass());
TArray<TSharedPtr<FJsonValue>> ObjectVertices = ObjectToConvert->GetArrayField("vertices");
TArray<TSharedPtr<FJsonValue>> ObjectFaces = ObjectToConvert->GetArrayField("faces");
TArray<FVector> ParsedVerticies;
for (size_t j = 0; j < ObjectVertices.Num(); j += 3)
{
ParsedVerticies.Add(FVector
(
(float)(ObjectVertices[j].Get()->AsNumber()) * -1,
(float)(ObjectVertices[j + 1].Get()->AsNumber()),
(float)(ObjectVertices[j + 2].Get()->AsNumber())
) * ScaleFactor);
}
//convert mesh faces into triangle array regardless of whether or not they are quads
TArray<int32> ParsedTriangles;
int32 j = 0;
while (j < ObjectFaces.Num())
{
if (ObjectFaces[j].Get()->AsNumber() == 0)
{
//Triangles
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 2].Get()->AsNumber());
j += 4;
}
else
{
//Quads to triangles
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 2].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 3].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 1].Get()->AsNumber());
ParsedTriangles.Add(ObjectFaces[j + 4].Get()->AsNumber());
j += 5;
}
}
if (RandomColorsPerLayer)
MeshInstance->SetMesh(ParsedVerticies, ParsedTriangles, DefaultMeshMaterial, SpeckleUnrealLayers[LayerIndex]->LayerColor);
else
MeshInstance->SetMesh(ParsedVerticies, ParsedTriangles, DefaultMeshMaterial, FLinearColor::White);
MeshInstance->AttachToActor(SpeckleUnrealLayers[LayerIndex], rules);
UE_LOG(LogTemp, Warning, TEXT("%d"), Offset);
UE_LOG(LogTemp, Warning, TEXT("%s"), *SpeckleUnrealLayers[LayerIndex]->LayerName);
}
}
}
else
{
GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, "Couldn't deserialize Json from object response");
GEngine->AddOnScreenDebugMessage(2, 10.0f, FColor::Red, Response->GetContentAsString());
}
ObjectsReceived[Offset] = true;
}
float USpeckleUnrealReceiver::GetStreamProgress()
{
if (ObjectsReceived.Num() == 0)
return 0;
float ProgressMade = 0;
for (size_t i = 0; i < ObjectsReceived.Num(); i++)
{
if (ObjectsReceived[i])
ProgressMade++;
}
return ProgressMade / ObjectsReceived.Num();
}
@@ -1,8 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "SpeckleWidgetBase.h"
#include "ISpeckleReceiver.h"
@@ -1,32 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "SpeckleUnrealManager.h"
#include "UObject/Interface.h"
#include "ISpeckleReceiver.generated.h"
// This class does not need to be modified.
UINTERFACE(MinimalAPI)
class UISpeckleReceiver : public UInterface
{
GENERATED_BODY()
};
/**
*
*/
class SPECKLEUNREAL_API IISpeckleReceiver
{
GENERATED_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
virtual void ImportSpeckleObject(int CurrIndex) = 0;
virtual void FetchListOfCommits(const FString& BranchName) = 0;
virtual void FetchListOfStreams() = 0;
virtual void FetchListOfBranches() = 0;
virtual void FetchGlobals() = 0;
};
@@ -1,44 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "ISpeckleReceiver.h"
#include "Components/ActorComponent.h"
#include "SpeckleRESTHandlerComponent.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class SPECKLEUNREAL_API USpeckleRESTHandlerComponent : public UActorComponent, public IISpeckleReceiver
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
USpeckleRESTHandlerComponent();
protected:
// Called when the game starts
virtual void BeginPlay() override;
public:
UFUNCTION(BlueprintCallable, Category="Speckle REST")
virtual void ImportSpeckleObject(int CurrIndex) override;
UFUNCTION(BlueprintCallable, Category="Speckle REST")
virtual void FetchListOfCommits(const FString& BranchName) override;
UFUNCTION(BlueprintCallable, Category="Speckle REST")
virtual void FetchListOfStreams() override;
UFUNCTION(BlueprintCallable, Category="Speckle REST")
virtual void FetchListOfBranches() override;
UFUNCTION(BlueprintCallable, Category="Speckle REST")
virtual void FetchGlobals() override;
UPROPERTY()
ASpeckleUnrealManager* SpeckleManager;
};
@@ -1,136 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "SpeckleStructs.generated.h"
/*
* Struct that holds all the properties required
* from a speckle commit
* received from GraphQL.
*/
USTRUCT(BlueprintType)
struct FSpeckleCommit
{
GENERATED_USTRUCT_BODY()
UPROPERTY(BlueprintReadWrite)
FString ReferenceObjectID;
UPROPERTY(BlueprintReadWrite)
FString AuthorName;
UPROPERTY(BlueprintReadWrite)
FString Message;
UPROPERTY(BlueprintReadWrite)
FString BranchName;
FSpeckleCommit(){};
FSpeckleCommit(const FString& ReferenceObjectID, const FString& AuthorName, const FString& Message, const FString& BranchName)
: ReferenceObjectID(ReferenceObjectID),
AuthorName(AuthorName),
Message(Message),
BranchName(BranchName)
{
}
//Operators overloading
FORCEINLINE bool operator==(const FSpeckleCommit &Other) const
{
return ReferenceObjectID == Other.ReferenceObjectID;
}
};
/*
* Struct that holds all the properties required
* from a speckle Branch
* received from GraphQL.
*/
USTRUCT(BlueprintType)
struct FSpeckleBranch
{
GENERATED_USTRUCT_BODY()
UPROPERTY(BlueprintReadWrite)
FString ID;
UPROPERTY(BlueprintReadWrite)
FString Name;
UPROPERTY(BlueprintReadWrite)
FString Description;
FSpeckleBranch(){};
FSpeckleBranch(const FString& ID, const FString& Name, const FString& Description):
ID(ID), Name(Name), Description(Description){}
};
/*
* Struct that holds all the properties required
* from a speckle Branch
* received from GraphQL.
*/
USTRUCT(BlueprintType)
struct FSpeckleGlobals
{
GENERATED_USTRUCT_BODY()
UPROPERTY(BlueprintReadWrite)
FString ID;
UPROPERTY(BlueprintReadWrite)
FString Region;
UPROPERTY(BlueprintReadWrite)
float Latitude;
UPROPERTY(BlueprintReadWrite)
float Longitude;
FSpeckleGlobals(): Latitude(0), Longitude(0)
{
};
FSpeckleGlobals(const FString& ID, const FString& Region, float Latitude, float Longitude)
: ID(ID),
Region(Region),
Latitude(Latitude),
Longitude(Longitude)
{
}
};
/*
* Struct that holds all the properties required
* from a speckle Branch
* received from GraphQL.
*/
USTRUCT(BlueprintType)
struct FSpeckleStream
{
GENERATED_USTRUCT_BODY()
UPROPERTY(BlueprintReadWrite)
FString ID;
UPROPERTY(BlueprintReadWrite)
FString Name;
UPROPERTY(BlueprintReadWrite)
FString Description;
FSpeckleStream(){};
FSpeckleStream(const FString& ID, const FString& Name, const FString& Description):
ID(ID), Name(Name), Description(Description){}
};
UENUM()
enum ESpeckleItemType {Stream, Commit, Branch};
@@ -3,12 +3,13 @@
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
class FSpeckleUnrealModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
@@ -3,18 +3,21 @@
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "GameFramework/Actor.h"
#include "SpeckleUnrealLayer.generated.h"
/**
*
*/
UCLASS(BlueprintType)
class SPECKLEUNREAL_API USpeckleUnrealLayer : public UObject
class SPECKLEUNREAL_API ASpeckleUnrealLayer : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere)
USceneComponent* Scene;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle")
FString LayerName;
@@ -27,7 +30,7 @@ public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle")
int32 ObjectCount;
USpeckleUnrealLayer();
ASpeckleUnrealLayer();
void Init(FString NewLayerName, int32 NewStartIndex, int32 NewObjectCount);
};
@@ -5,9 +5,9 @@
// json manipulation
#include "Dom/JsonObject.h"
// #include "Dom/JsonValue.h"
// #include "Serialization/JsonReader.h"
// #include "Serialization/JsonSerializer.h"
#include "Dom/JsonValue.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"
// web requests
#include "Runtime/Online/HTTP/Public/Http.h"
@@ -15,78 +15,48 @@
#include "SpeckleUnrealMesh.h"
#include "SpeckleUnrealLayer.h"
#include "GameFramework/Actor.h"
#include "SpeckleStructs.h"
#include "SpeckleUnrealManager.generated.h"
UCLASS(BlueprintType, Blueprintable)
UCLASS(BlueprintType)
class SPECKLEUNREAL_API ASpeckleUnrealManager : public AActor
{
GENERATED_BODY()
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FBranchesRequestProcessed, const TArray<FSpeckleBranch>&, BranchesList);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FCommitsRequestProcessed, const TArray<FSpeckleCommit>&, CommitsList);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FStreamsRequestProcessed, const TArray<FSpeckleStream>&, StreamsList);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGlobalsRequestProcessed, const FSpeckleGlobals&, GlobalsObject);
public:
FHttpModule* Http;
/* The actual HTTP call */
UFUNCTION(CallInEditor, Category = "Speckle")
void ImportSpeckleObject();
UFUNCTION(CallInEditor, BlueprintCallable, Category = "Speckle")
void DeleteObjects();
UFUNCTION()
void GetStream();
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString ServerUrl
{
"https://speckle.xyz"
FString ServerUrl {
"https://hestia.speckle.works/api/"
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString StreamID
{
FString StreamID {
""
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString ObjectID
{
""
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString AuthToken
{
FString AuthToken {
""
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
TSubclassOf<ASpeckleUnrealMesh> MeshActor
{
ASpeckleUnrealMesh::StaticClass()
};
TSubclassOf<ASpeckleUnrealMesh> MeshActor;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
UMaterialInterface* DefaultMeshOpaqueMaterial;
UMaterialInterface* DefaultMeshMaterial;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
UMaterialInterface* DefaultMeshTransparentMaterial;
bool RandomColorsPerLayer;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
bool ImportAtRuntime;
TArray<ASpeckleUnrealLayer*> SpeckleUnrealLayers;
TArray<USpeckleUnrealLayer*> SpeckleUnrealLayers;
void OnStreamTextResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnCommitsItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnBranchesItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnStreamItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnGlobalStreamItemsResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
/*Assign this function to call when the GET request processes sucessfully*/
void OnStreamResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
// Sets default values for this actor's properties
ASpeckleUnrealManager();
@@ -94,55 +64,18 @@ public:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY()
TArray<FSpeckleCommit> ArrayOfCommits;
UPROPERTY()
TArray<FSpeckleBranch> ArrayOfBranches;
UPROPERTY()
TArray<FSpeckleStream> ArrayOfStreams;
void FetchStreamItems(FString PostPayload, TFunction<void(FHttpRequestPtr, FHttpResponsePtr , bool)> HandleResponse);
UPROPERTY(BlueprintAssignable, Category = "SpeckleEvents");
FBranchesRequestProcessed OnBranchesProcessed;
UPROPERTY(BlueprintAssignable, Category = "SpeckleEvents");
FCommitsRequestProcessed OnCommitsProcessed;
UPROPERTY(BlueprintAssignable, Category = "SpeckleEvents");
FStreamsRequestProcessed OnStreamsProcessed;
UPROPERTY(BlueprintAssignable, Category = "SpeckleEvents");
FGlobalsRequestProcessed OnGlobalsProcessed;
protected:
UWorld* World;
float ScaleFactor;
TMap<FString, TSharedPtr<FJsonObject>> SpeckleObjects;
TMap<FString, TSharedPtr<FJsonObject>> SpeckleCommits;
TMap<FString, ASpeckleUnrealMesh*> CreatedSpeckleMeshes;
TMap<FString, ASpeckleUnrealMesh*> InProgressSpeckleMeshes;
int32 LayerIndex;
int32 CurrentObjectIndex;
ASpeckleUnrealMesh* GetExistingMesh(const FString &objectId);
void SetUpGetRequest(TSharedRef<IHttpRequest> Request);
void ImportObjectFromCache(const TSharedPtr<FJsonObject> speckleObject);
void GetStreamObjects(int32 objectCount);
UMaterialInterface* CreateMaterial(TSharedPtr<FJsonObject>);
ASpeckleUnrealMesh* CreateMesh(TSharedPtr<FJsonObject>, UMaterialInterface *explicitMaterial = nullptr);
TArray<uint8> FStringToUint8(const FString& InString)
{
TArray<uint8> OutBytes;
// Handle empty strings
if (InString.Len() > 0)
{
FTCHARToUTF8 Converted(*InString); // Convert to UTF8
OutBytes.Append(reinterpret_cast<const uint8*>(Converted.Get()), Converted.Length());
}
return OutBytes;
}
void OnStreamObjectResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
};
@@ -22,7 +22,7 @@ public:
// Sets default values for this actor's properties
ASpeckleUnrealMesh();
virtual void SetMesh(const TArray<FVector> &Vertices, const TArray<int32> &Triangles, UMaterialInterface* Material, FLinearColor Color);
virtual void SetMesh(TArray<FVector> Vertices, TArray<int32> Triangles, UMaterialInterface* Material, FLinearColor Color);
protected:
// Called when the game starts or when spawned
@@ -0,0 +1,91 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
// logs
#include "Engine/Engine.h"
// json manipulation
#include "Dom/JsonObject.h"
#include "Dom/JsonValue.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"
// web requests
#include "Runtime/Online/HTTP/Public/Http.h"
#include "SpeckleUnrealMesh.h"
#include "SpeckleUnrealLayer.h"
#include "GameFramework/Actor.h"
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "SpeckleUnrealReceiver.generated.h"
/**
*
*/
UCLASS(BlueprintType)
class SPECKLEUNREAL_API USpeckleUnrealReceiver : public UObject
{
GENERATED_BODY()
public:
FHttpModule* Http;
/* The actual HTTP call */
UFUNCTION(BlueprintCallable, Category = "Speckle")
void ReceiveStream();
UFUNCTION(BlueprintCallable, Category = "Speckle")
float GetStreamProgress();
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString ServerUrl {
"https://hestia.speckle.works/api/"
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString StreamID {
""
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
FString AuthToken {
""
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
TSubclassOf<ASpeckleUnrealMesh> MeshActor;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
UMaterialInterface* DefaultMeshMaterial;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle")
bool RandomColorsPerLayer;
TArray<ASpeckleUnrealLayer*> SpeckleUnrealLayers;
/*Assign this function to call when the GET request processes sucessfully*/
void OnStreamResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
// Sets default values for this actor's properties
USpeckleUnrealReceiver();
protected:
UWorld* World;
float ScaleFactor;
TArray<bool> ObjectsReceived;
int32 LayerIndex;
int32 CurrentObjectIndex;
void SetUpGetRequest(TSharedRef<IHttpRequest> Request);
void GetStreamObjects(int32 objectCount);
void OnStreamObjectResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
};
@@ -1,20 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "SpeckleUnrealManager.h"
#include "Blueprint/UserWidget.h"
#include "SpeckleWidgetBase.generated.h"
/**
*
*/
UCLASS(BlueprintType)
class SPECKLEUNREAL_API USpeckleWidgetBase : public UUserWidget
{
GENERATED_BODY()
public:
};
@@ -29,13 +29,12 @@ public class SpeckleUnreal : ModuleRules
"Http",
"Json",
"JsonUtilities",
"ProceduralMeshComponent",
"InputCore",
"Slate",
"SlateCore",
"ProceduralMeshComponent"
// ... add other public dependencies that you statically link with here ...
}
);
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
@@ -43,7 +42,6 @@ public class SpeckleUnreal : ModuleRules
"Engine",
"Slate",
"SlateCore",
"UMG"
// ... add private dependencies that you statically link with here ...
}
);
@@ -1,20 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "FSpeckleEditorCommands.h"
#include "Framework/Commands/Commands.h"
void FSpeckleEditorCommands::RegisterCommands()
{
//we meed to define a localized namespace even if its not used
#define LOCTEXT_NAMESPACE ""
UI_COMMAND(
SpeckleToolBarBtn,
"SpeckleBtn",
"Speckle Editor Button",
EUserInterfaceActionType::Button,
FInputGesture());
#undef LOCTEXT_NAMESPACE
}
@@ -1,107 +0,0 @@

#include "FSpeckleUnrealEditorModule.h"
#include "EditorUtilityWidget.h"
#include "SpeckleUnrealManager.h"
#include "FSpeckleEditorCommands.h"
IMPLEMENT_MODULE(FSpeckleUnrealEditorModule, SpeckleUnrealEditor);
#define LOCTEXT_NAMESPACE "FSpeckleUnrealEditorModule"
void FSpeckleUnrealEditorModule::StartupModule()
{
FSpeckleEditorCommands::Register();
TSharedPtr<FUICommandList> CommandList = MakeShareable(new FUICommandList());
FSpeckleStyle::Initialize();
//map object to function
CommandList->MapAction
(
FSpeckleEditorCommands::Get().SpeckleToolBarBtn,
FExecuteAction::CreateRaw(this, &FSpeckleUnrealEditorModule::SpeckleButtonListener),
FCanExecuteAction()
);
//add to UE4 toolbar
ToolbarExtender = MakeShareable(new FExtender());
Extension = ToolbarExtender->AddToolBarExtension
(
"Misc",
EExtensionHook::After,
CommandList,
FToolBarExtensionDelegate::CreateRaw(this,
&FSpeckleUnrealEditorModule::AddToolbarExtension)
);
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditorModule.GetToolBarExtensibilityManager()->AddExtender(ToolbarExtender);
}
void FSpeckleUnrealEditorModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
ToolbarExtender->RemoveExtension(Extension.ToSharedRef());
Extension.Reset();
ToolbarExtender.Reset();
FSpeckleStyle::Shutdown();
}
void FSpeckleUnrealEditorModule::SpeckleButtonListener()
{
if(SpeckleEditorWindow == nullptr)
{
//Start the editor Utility widget
auto EditorUIClass = LoadClass<UEditorUtilityWidget>(nullptr,
TEXT("EditorUtilityWidgetBlueprint'/SpeckleUnreal/EWBP_SpeckleEditorWindow.EWBP_SpeckleEditorWindow_C'"));
IMainFrameModule& MainFrameModule = FModuleManager::LoadModuleChecked<IMainFrameModule>(TEXT("MainFrame"));
UWorld* World = GEditor->GetEditorWorldContext().World();
check(World);
auto CreatedUMGWidget = Cast<UEditorUtilityWidget>(CreateWidget(World, EditorUIClass));
// create new slate window
SpeckleEditorWindow = SNew(SWindow)
.AutoCenter(EAutoCenter::None)
.IsInitiallyMaximized(false)
.ClientSize(FVector2D(300,500))
.SizingRule(ESizingRule::UserSized)
.SupportsMaximize(false)
.SupportsMinimize(true)
.CreateTitleBar(true)
.HasCloseButton(true)
.MaxHeight(600)
.MaxWidth(400);
// Use UMG in slate
if(CreatedUMGWidget != nullptr)
{
SpeckleEditorWindow->SetContent(CreatedUMGWidget->TakeWidget());
}
// Add Windows to slate app
FSlateApplication & SlateApp = FSlateApplication::Get();
if (MainFrameModule.GetParentWindow().IsValid())
{
SlateApp.AddWindow(SpeckleEditorWindow.ToSharedRef(), true);
}
//Bind delegate when window is closed
OnSpeckleWindowClosed.BindRaw(this, &FSpeckleUnrealEditorModule::OnEditorWindowClosed);
SpeckleEditorWindow->SetOnWindowClosed(OnSpeckleWindowClosed);
}
else // if editor window already exists
{
SpeckleEditorWindow->BringToFront();
}
}
void FSpeckleUnrealEditorModule::OnEditorWindowClosed(const TSharedRef<SWindow>&)
{
UE_LOG(LogTemp, Warning, TEXT("[SPECKLE LOG] :Speckle editor window closed"));
SpeckleEditorWindow = nullptr;
}
#undef LOCTEXT_NAMESPACE
@@ -1,134 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "SpeckleEditorWidget.h"
#include "Blueprint/WidgetTree.h"
#include "Components/ComboBoxString.h"
#include "Components/TextBlock.h"
#include "ObjectEditorUtils.h"
#include "Async/Async.h"
#include "SpeckleUnreal/Public/SpeckleUnrealManager.h"
void USpeckleEditorWidget::NativeConstruct()
{
//bind widgets. To make it work in the editor we search based on the WidgetTree.
StreamName = Cast<UTextBlock>(WidgetTree->FindWidget(TEXT("Stream")));
CommitsCBox = Cast<UComboBoxString>(WidgetTree->FindWidget(TEXT("CommitsBox")));
BranchesCBox = Cast<UComboBoxString>(WidgetTree->FindWidget(TEXT("BranchesBox")));
SelectedCommitText = Cast<UTextBlock>(WidgetTree->FindWidget(TEXT("SelectedCommit")));
SpeckleManagersCBox = Cast<UComboBoxString>(WidgetTree->FindWidget(TEXT("SpeckleManagersBox")));
SpeckleManagersCBox->OnSelectionChanged.AddDynamic(this, &USpeckleEditorWidget::SpeckleManagerSelectionListener);
BranchesCBox->OnSelectionChanged.AddDynamic(this,&USpeckleEditorWidget::BranchesBoxSelectionListener);
//Grab all speckleManagers in the scene
FindAllActors(GetWorld(), SpeckleManagers);
if(SpeckleManagers.Num() > 0)
{
CurrentSpeckleManager = SpeckleManagers[0];
//display speckle managers to combo box
for(auto s : SpeckleManagers)
{
SpeckleManagersCBox->AddOption(s->GetName());
}
SpeckleManagersCBox->SetSelectedOption(CurrentSpeckleManager->GetName());
}
else
{
if(GEngine)
{
GEngine->AddOnScreenDebugMessage(1, 10.0f, FColor::Red,
"[SPECKLE LOG]: No available speckle managers in the scene. Place and reopen the window");
}
}
//Bind event handlers to fill in the received items.
if(CurrentSpeckleManager != nullptr)
{
CurrentSpeckleManager->OnBranchesProcessed.AddDynamic(this, &USpeckleEditorWidget::SpeckleBranchesReceived);
CurrentSpeckleManager->OnCommitsProcessed.AddDynamic(this, &USpeckleEditorWidget::SpeckleCommitsReceived);
}
InitUI();
}
void USpeckleEditorWidget::InitUI()
{
if(CurrentSpeckleManager)
{
StreamName->SetText(FText::FromString("Stream ID: " + CurrentSpeckleManager->StreamID));
}
}
void USpeckleEditorWidget::ImportSpeckleObject(UActorComponent* SpeckleActorComponent)
{
if(SpeckleActorComponent != nullptr)
{
const auto SpeckleReceiver = Cast<IISpeckleReceiver>(SpeckleActorComponent);
if(SpeckleReceiver)
{
const auto CurrentIdx = CommitsCBox->FindOptionIndex(CommitsCBox->GetSelectedOption());
SpeckleReceiver->ImportSpeckleObject(CurrentIdx);
}
}
}
void USpeckleEditorWidget::FetchSpeckleCommits(UActorComponent* SpeckleActorComponent)
{
if(SpeckleActorComponent != nullptr)
{
const auto SpeckleReceiver = Cast<IISpeckleReceiver>(SpeckleActorComponent);
if(SpeckleReceiver)
{
SpeckleReceiver->FetchListOfCommits(SelectedBranch);
}
}
}
void USpeckleEditorWidget::SpeckleCommitsReceived(const TArray<FSpeckleCommit>& CommitsList)
{
CommitsCBox->ClearOptions();
for (auto C : CommitsList)
{
CommitsCBox->AddOption(C.Message + " [" + C.AuthorName + "]");
}
}
void USpeckleEditorWidget::FetchSpeckleBranches(UActorComponent* SpeckleActorComponent)
{
if(SpeckleActorComponent != nullptr)
{
const auto SpeckleReceiver = Cast<IISpeckleReceiver>(SpeckleActorComponent);
if(SpeckleReceiver)
{
SpeckleReceiver->FetchListOfBranches();
}
}
}
void USpeckleEditorWidget::SpeckleBranchesReceived(const TArray<FSpeckleBranch>& BranchesList)
{
BranchesCBox->ClearOptions();
for(auto b : BranchesList)
{
BranchesCBox->AddOption(b.Name);
}
if(BranchesCBox->GetOptionCount() > 0)
{
BranchesCBox->SetSelectedOption("main");
SelectedBranch = TEXT("main");
}
}
void USpeckleEditorWidget::SpeckleManagerSelectionListener(FString SelectedItem, ESelectInfo::Type SelectionType)
{
const int32 Idx = SpeckleManagersCBox->FindOptionIndex(SelectedItem);
CurrentSpeckleManager = SpeckleManagers[Idx];
InitUI();
}
@@ -1,64 +0,0 @@
#include "SpeckleStyle.h"
#include "Slate/SlateGameResources.h"
#include "FSpeckleUnrealEditorModule.h"
#include "Styling/SlateStyleRegistry.h"
#include "Interfaces/IPluginManager.h"
#define IMAGE_BRUSH(RelativePath,...) FSlateImageBrush(FSpeckleStyle::InContent(RelativePath,".png"), __VA_ARGS__)
FString FSpeckleStyle::InContent(const FString& RelativePath, const ANSICHAR* Extension)
{
static FString ContentDir = IPluginManager::Get().FindPlugin(TEXT("SpeckleUnreal"))->GetContentDir();
return (ContentDir / RelativePath) + Extension;
}
TSharedPtr<FSlateStyleSet>FSpeckleStyle::SpeckleStyleSet = nullptr;
TSharedPtr<ISlateStyle> FSpeckleStyle::Get()
{
return SpeckleStyleSet;
}
void FSpeckleStyle::Initialize()
{
// Only register once
if (SpeckleStyleSet.IsValid())
{
return;
}
SpeckleStyleSet = MakeShareable<FSlateStyleSet>(new FSlateStyleSet(GetStyleSetName()));
// Const icon sizes
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon24x24(24.0f, 24.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
const FVector2D Icon48x48(48.0f, 48.0f);
//set menu/toolbar icon
SpeckleStyleSet->Set("Speckle.MenuIcon", new IMAGE_BRUSH(TEXT("speckle_icon_64_64"), Icon40x40));
FSlateStyleRegistry::RegisterSlateStyle(*SpeckleStyleSet.Get());
}
void FSpeckleStyle::Shutdown()
{
if (SpeckleStyleSet.IsValid())
{
FSlateStyleRegistry::UnRegisterSlateStyle(*SpeckleStyleSet.Get());
ensure(SpeckleStyleSet.IsUnique());
SpeckleStyleSet.Reset();
}
}
FName FSpeckleStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("SpeckleStyle"));
return StyleSetName;
}
#undef IMAGE_BRUSH
@@ -1,26 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Framework/Commands/Commands.h"
#include "EditorStyleSet.h"
/**
*
*/
class FSpeckleEditorCommands : public TCommands<FSpeckleEditorCommands>
{
public:
FSpeckleEditorCommands() : TCommands<FSpeckleEditorCommands>
(
FName(TEXT("Speckle Commands")),
FText::FromString("Speckle Editor Commands"),
NAME_None,
FEditorStyle::GetStyleSetName()
){};
virtual void RegisterCommands() override;
TSharedPtr<FUICommandInfo> SpeckleToolBarBtn;
};
@@ -1,51 +0,0 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleInterface.h"
#include "LevelEditor.h"
#include "SlateBasics.h"
#include "Interfaces/IMainFrameModule.h"
#include "FSpeckleEditorCommands.h"
#include "SpeckleStyle.h"
class FSpeckleUnrealEditorModule : public IModuleInterface
{
virtual void StartupModule() override;
virtual void ShutdownModule() override;
// static inline FSpeckleUnrealEditorModule& Get() {
// return FModuleManager::LoadModuleChecked<FSpeckleUnrealEditorModule>("SpeckleUnrealEditor");
// }
//
// static inline bool IsAvailable() {
// return FModuleManager::Get().IsModuleLoaded("SpeckleUnrealEditor");
// }
TSharedPtr<FExtender> ToolbarExtender;
TSharedPtr<const FExtensionBase> Extension;
TSharedPtr<SWindow> SpeckleEditorWindow;
FOnWindowClosed OnSpeckleWindowClosed;
void SpeckleButtonListener();
UFUNCTION()
void OnEditorWindowClosed(const TSharedRef<SWindow>&);
void AddToolbarExtension(FToolBarBuilder &builder)
{
//FSlateIcon IconBrush = FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.ViewOptions", "LevelEditor.ViewOptions.Small");
FSlateIcon IconBrush = FSlateIcon(FSpeckleStyle::GetStyleSetName(), "Speckle.MenuIcon");
builder.AddToolBarButton
(
FSpeckleEditorCommands::Get().SpeckleToolBarBtn,
NAME_None,
FText::FromString("Speckle"),
FText::FromString("Click to open Speckle Window"),
IconBrush,
NAME_None
);
};
};
@@ -1,95 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "EditorUtilityWidget.h"
#include "EngineUtils.h"
#include "SpeckleUnreal/Public/ISpeckleReceiver.h"
#include "SpeckleEditorWidget.generated.h"
class ASpeckleUnrealManager;
UCLASS()
class USpeckleEditorWidget : public UEditorUtilityWidget
{
GENERATED_BODY()
protected:
virtual void NativeConstruct() override;
public:
// BUTTONS
UPROPERTY()
class UButton* ImportObjectButton;
UPROPERTY()
UButton* FetchButton;
//TEXT BLOCKS
UPROPERTY()
class UTextBlock* StreamName;
UPROPERTY()
class UTextBlock* SelectedCommitText;
//COMBO BOXES
UPROPERTY()
class UComboBoxString* BranchesCBox;
UPROPERTY()
class UComboBoxString* CommitsCBox;
UPROPERTY()
class UComboBoxString* SpeckleManagersCBox;
//FUNCTIONS
void InitUI();
UFUNCTION(BlueprintCallable)
void ImportSpeckleObject(UActorComponent* SpeckleReceiver);
UFUNCTION(BlueprintCallable)
void FetchSpeckleCommits(UActorComponent* SpeckleReceiver);
UFUNCTION(BlueprintCallable)
void SpeckleCommitsReceived(const TArray<FSpeckleCommit>& CommitsList);
UFUNCTION(BlueprintCallable)
void FetchSpeckleBranches(UActorComponent* SpeckleReceiver);
UFUNCTION(BlueprintCallable)
void SpeckleBranchesReceived(const TArray<FSpeckleBranch>& BranchesList);
UFUNCTION(BlueprintCallable)
void SpeckleManagerSelectionListener(FString SelectedItem, ESelectInfo::Type SelectionType);
FString SelectedBranch;
UFUNCTION(BlueprintCallable)
void BranchesBoxSelectionListener(FString SelectedItem, ESelectInfo::Type SelectionType)
{
SelectedBranch = SelectedItem;
}
template<typename T>
UFUNCTION(BlueprintCallable)
void FindAllActors(UWorld* World, TArray<T*>& Out)
{
for (TActorIterator<T> It(World); It; ++It)
{
Out.Add(*It);
}
}
UPROPERTY(EditAnywhere)
TSubclassOf<ASpeckleUnrealManager> SpeckleManagerClass;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
ASpeckleUnrealManager* CurrentSpeckleManager;
UPROPERTY()
TArray<ASpeckleUnrealManager*> SpeckleManagers;
};
@@ -1,17 +0,0 @@
#pragma once
#include "SlateBasics.h"
#include "SlateExtras.h"
class FSpeckleStyle
{
public:
static void Initialize();
static void Shutdown();
static TSharedPtr< class ISlateStyle > Get();
static FName GetStyleSetName();
private:
static FString InContent(const FString& RelativePath, const ANSICHAR* Extension);
private:
static TSharedPtr<class FSlateStyleSet> SpeckleStyleSet;
};
@@ -1,75 +0,0 @@
using UnrealBuildTool;
public class SpeckleUnrealEditor : ModuleRules
{
public SpeckleUnrealEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"Http",
"Json",
"JsonUtilities",
"ProceduralMeshComponent",
"InputCore",
"Slate",
"SlateCore",
"MainFrame",
"EditorStyle"
}
);
if (Target.bBuildEditor)
{
PublicDependencyModuleNames.AddRange(new string[]
{
"UnrealEd",
});
}
if (Target.Type == TargetType.Editor) // Is UBT building for Editor ?
{
PrivateDependencyModuleNames.Add("SpeckleUnreal");
}
PrivateDependencyModuleNames.AddRange(
new string[]
{
"CoreUObject",
"Engine",
"Slate",
"SlateCore",
"Blutility",
"Projects",
"UMG",
"UMGEditor"
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
@@ -5,9 +5,9 @@
"FriendlyName": "SpeckleUnreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the MIT license, is customizable, and available in the cloud or via a self-hosted server. It allows users to exchange data between various AEC modelling and content creation platforms.",
"Category": "AEC",
"CreatedBy": "Speckle",
"CreatedByURL": "https://speckle.systems/",
"DocsURL": "https://github.com/specklesystems/speckle-unreal",
"CreatedBy": "Mobius Node",
"CreatedByURL": "https://www.mobiusnode.io/",
"DocsURL": "https://github.com/mobiusnode/SpeckleUnreal",
"MarketplaceURL": "",
"SupportURL": "",
"CanContainContent": true,
@@ -19,11 +19,6 @@
"Name": "SpeckleUnreal",
"Type": "Runtime",
"LoadingPhase": "Default"
},
{
"Name": "SpeckleUnrealEditor",
"Type": "Editor",
"LoadingPhase": "PostEngineInit"
}
],
"Plugins": [
+51 -33
View File
@@ -7,63 +7,81 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Engine", "Engine", "{94A6C6
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Games", "Games", "{8E2F6A87-1826-34F4-940C-CC23A48F9FE4}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UE4", "Intermediate\ProjectFiles\UE4.vcxproj", "{CE2AC9DC-3204-4D56-954E-856D5121C6CE}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UE4", "Intermediate\ProjectFiles\UE4.vcxproj", "{DE17FD13-E94F-4875-9509-F6023C8B5747}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SpeckleUnrealProject", "Intermediate\ProjectFiles\SpeckleUnrealProject.vcxproj", "{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SpeckleUnrealProject", "Intermediate\ProjectFiles\SpeckleUnrealProject.vcxproj", "{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Visualizers", "Visualizers", "{1CCEC849-CC72-4C59-8C36-2F7C38706D4C}"
ProjectSection(SolutionItems) = preProject
..\..\..\Program Files\Epic Games\UE_4.26\Engine\Extras\VisualStudioDebugging\UE4.natvis = ..\..\..\Program Files\Epic Games\UE_4.26\Engine\Extras\VisualStudioDebugging\UE4.natvis
..\..\..\Epic Games\UE_4.25\Engine\Extras\VisualStudioDebugging\UE4.natvis = ..\..\..\Epic Games\UE_4.25\Engine\Extras\VisualStudioDebugging\UE4.natvis
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
DebugGame Editor|Android = DebugGame Editor|Android
DebugGame Editor|Win32 = DebugGame Editor|Win32
DebugGame Editor|Win64 = DebugGame Editor|Win64
DebugGame|Android = DebugGame|Android
DebugGame|Win32 = DebugGame|Win32
DebugGame|Win64 = DebugGame|Win64
Development Editor|Android = Development Editor|Android
Development Editor|Win32 = Development Editor|Win32
Development Editor|Win64 = Development Editor|Win64
Development|Android = Development|Android
Development|Win32 = Development|Win32
Development|Win64 = Development|Win64
Shipping|Android = Shipping|Android
Shipping|Win32 = Shipping|Win32
Shipping|Win64 = Shipping|Win64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.DebugGame Editor|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.DebugGame Editor|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.DebugGame|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.DebugGame|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.Development Editor|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.Development Editor|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.Development|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.Development|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.Shipping|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{CE2AC9DC-3204-4D56-954E-856D5121C6CE}.Shipping|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame Editor|Win32.ActiveCfg = Invalid|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame Editor|Win64.ActiveCfg = DebugGame_Editor|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame Editor|Win64.Build.0 = DebugGame_Editor|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame|Win32.ActiveCfg = DebugGame|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame|Win32.Build.0 = DebugGame|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame|Win64.ActiveCfg = DebugGame|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.DebugGame|Win64.Build.0 = DebugGame|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development Editor|Win32.ActiveCfg = Invalid|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development Editor|Win64.ActiveCfg = Development_Editor|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development Editor|Win64.Build.0 = Development_Editor|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development|Win32.ActiveCfg = Development|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development|Win32.Build.0 = Development|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development|Win64.ActiveCfg = Development|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Development|Win64.Build.0 = Development|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Shipping|Win32.ActiveCfg = Shipping|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Shipping|Win32.Build.0 = Shipping|Win32
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Shipping|Win64.ActiveCfg = Shipping|x64
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6}.Shipping|Win64.Build.0 = Shipping|x64
{DE17FD13-E94F-4875-9509-F6023C8B5747}.DebugGame Editor|Android.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.DebugGame Editor|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.DebugGame Editor|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.DebugGame|Android.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.DebugGame|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.DebugGame|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Development Editor|Android.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Development Editor|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Development Editor|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Development|Android.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Development|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Development|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Shipping|Android.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Shipping|Win32.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{DE17FD13-E94F-4875-9509-F6023C8B5747}.Shipping|Win64.ActiveCfg = BuiltWithUnrealBuildTool|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame Editor|Android.ActiveCfg = Invalid|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame Editor|Win32.ActiveCfg = Invalid|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame Editor|Win64.ActiveCfg = DebugGame_Editor|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame Editor|Win64.Build.0 = DebugGame_Editor|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame|Android.ActiveCfg = Android_DebugGame|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame|Android.Build.0 = Android_DebugGame|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame|Win32.ActiveCfg = DebugGame|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame|Win32.Build.0 = DebugGame|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame|Win64.ActiveCfg = DebugGame|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.DebugGame|Win64.Build.0 = DebugGame|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development Editor|Android.ActiveCfg = Invalid|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development Editor|Win32.ActiveCfg = Invalid|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development Editor|Win64.ActiveCfg = Development_Editor|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development Editor|Win64.Build.0 = Development_Editor|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development|Android.ActiveCfg = Android_Development|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development|Android.Build.0 = Android_Development|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development|Win32.ActiveCfg = Development|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development|Win32.Build.0 = Development|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development|Win64.ActiveCfg = Development|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Development|Win64.Build.0 = Development|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Shipping|Android.ActiveCfg = Android_Shipping|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Shipping|Android.Build.0 = Android_Shipping|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Shipping|Win32.ActiveCfg = Shipping|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Shipping|Win32.Build.0 = Shipping|Win32
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Shipping|Win64.ActiveCfg = Shipping|x64
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9}.Shipping|Win64.Build.0 = Shipping|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{CE2AC9DC-3204-4D56-954E-856D5121C6CE} = {94A6C6F3-99B3-346E-9557-ABF9D4064DBD}
{9DBAC0A8-8945-4AB3-AFB6-639C4EC5B2E6} = {8E2F6A87-1826-34F4-940C-CC23A48F9FE4}
{DE17FD13-E94F-4875-9509-F6023C8B5747} = {94A6C6F3-99B3-346E-9557-ABF9D4064DBD}
{A1185D9A-4D4D-4C9C-A9CD-D130F0A23FB9} = {8E2F6A87-1826-34F4-940C-CC23A48F9FE4}
EndGlobalSection
EndGlobal
@@ -1,6 +1,6 @@
{
"FileVersion": 3,
"EngineAssociation": "4.26",
"EngineAssociation": "4.25",
"Category": "",
"Description": "",
"Modules": [