diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..3b5e4bb --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,111 @@ +version: 2.1 + +orbs: + aws-s3: circleci/aws-s3@2.0.0 + +parameters: + marketplace-deploy: + type: boolean + default: false + +commands: + zip-source: + parameters: + target: + type: string + outputdir: + type: string + steps: + - run: + name: "Create Archive" + command: | + \cp -r ".pluginconfig/<>/." "./" + mkdir -p "<>/" + stashName=`git stash create`; + git archive -o "<>/speckle-unreal-UE<>.zip" --worktree-attributes --prefix="speckle-unreal/" $stashName + + add-source-copyright: + parameters: + copyright-string: + type: string + steps: + - run: #Remove BOM header, then add copyright comment + name: "Add copyright notice to source files" + command: | + shopt -s globstar + for file in Source/**/*.{cpp,hpp,c,h,cs}; + do if [ -f $file ]; then + sed -i '1s/^\xEF\xBB\xBF//' $file; + sed -i '1s/^/\/\/ <>\n/' $file; + echo "added copyright notice to $file"; + fi; + done; + +jobs: + generate-source-zip: + docker: + - image: cimg/base:stable + parameters: + target: + type: string + steps: + - checkout + - add-source-copyright: + copyright-string: "Copyright AEC SYSTEMS 2023" + - zip-source: + target: <> + outputdir: "output/unreal/<>" + - store_artifacts: + path: "output/unreal/<>" + destination: "unreal-marketplace/<>" + - persist_to_workspace: + root: ./ + paths: + - "output/unreal/<>" + + marketplace-deploy: + docker: + - image: cimg/base:stable + steps: + - attach_workspace: + at: ./ + - aws-s3/copy: + arguments: "--recursive --endpoint=https://$SPACES_REGION.digitaloceanspaces.com --acl public-read" + aws-access-key-id: SPACES_KEY + aws-region: SPACES_REGION + aws-secret-access-key: SPACES_SECRET + from: '"output"' + to: s3://speckle-releases/installers/ + +workflows: + marketplace-publish: + when: <> + jobs: + - generate-source-zip: + name: "Generate Source Archive UE4.27" + target: "4.27" + - generate-source-zip: + name: "Generate Source Archive UE5.0" + target: "5.0" + - generate-source-zip: + name: "Generate Source Archive UE5.1" + target: "5.1" + - generate-source-zip: + name: "Generate Source Archive UE5.2" + target: "5.2" + - generate-source-zip: + name: "Generate Source Archive UE5.3" + target: "5.3" + - generate-source-zip: + name: "Generate Source Archive UE5.4" + target: "5.4" + - marketplace-deploy: + name: "Deploy to marketplace" + context: do-spaces-speckle-releases + requires: + - "Generate Source Archive UE4.27" + - "Generate Source Archive UE5.0" + - "Generate Source Archive UE5.1" + - "Generate Source Archive UE5.2" + - "Generate Source Archive UE5.3" + - "Generate Source Archive UE5.4" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..98681ce --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +.pluginconfig/* export-ignore \ No newline at end of file diff --git a/.github/workflows/close-issue.yml b/.github/workflows/close-issue.yml index 094d6df..30e1ebc 100644 --- a/.github/workflows/close-issue.yml +++ b/.github/workflows/close-issue.yml @@ -6,73 +6,7 @@ on: jobs: update_issue: - runs-on: ubuntu-latest - steps: - - name: Get project data - env: - GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}} - ORGANIZATION: specklesystems - PROJECT_NUMBER: 9 - run: | - gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query=' - query($org: String!, $number: Int!) { - organization(login: $org){ - projectNext(number: $number) { - id - fields(first:20) { - nodes { - id - name - settings - } - } - } - } - }' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json - - echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV - echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV - - echo "$PROJECT_ID" - echo "$STATUS_FIELD_ID" - - echo 'DONE_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .settings | fromjson | .options[] | select(.name== "Done") | .id' project_data.json) >> $GITHUB_ENV - echo "$DONE_ID" - - - name: Add Issue to project #it's already in the project, but we do this to get its node id! - env: - GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}} - ISSUE_ID: ${{ github.event.issue.node_id }} - run: | - item_id="$( gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query=' - mutation($project:ID!, $id:ID!) { - addProjectNextItem(input: {projectId: $project, contentId: $id}) { - projectNextItem { - id - } - } - }' -f project=$PROJECT_ID -f id=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')" - - echo 'ITEM_ID='$item_id >> $GITHUB_ENV - - - name: Update Status - env: - GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}} - ISSUE_ID: ${{ github.event.issue.node_id }} - run: | - gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query=' - mutation($project:ID!, $status:ID!, $id:ID!, $value:String!) { - set_status: updateProjectNextItemField( - input: { - projectId: $project - itemId: $id - fieldId: $status - value: $value - } - ) { - projectNextItem { - id - } - } - }' -f project=$PROJECT_ID -f status=$STATUS_FIELD_ID -f id=$ITEM_ID -f value=${{ env.DONE_ID }} - + uses: specklesystems/github-actions/.github/workflows/project-add-issue.yml@main + secrets: inherit + with: + issue-id: ${{ github.event.issue.node_id }} \ No newline at end of file diff --git a/.github/workflows/open-issue.yml b/.github/workflows/open-issue.yml index 831d2b0..27fe2b8 100644 --- a/.github/workflows/open-issue.yml +++ b/.github/workflows/open-issue.yml @@ -6,45 +6,7 @@ on: jobs: track_issue: - runs-on: ubuntu-latest - steps: - - name: Get project data - env: - GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}} - ORGANIZATION: specklesystems - PROJECT_NUMBER: 9 - run: | - gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query=' - query($org: String!, $number: Int!) { - organization(login: $org){ - projectNext(number: $number) { - id - fields(first:20) { - nodes { - id - name - settings - } - } - } - } - }' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json - - echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV - echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV - - - name: Add Issue to project - env: - GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}} - ISSUE_ID: ${{ github.event.issue.node_id }} - run: | - item_id="$( gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query=' - mutation($project:ID!, $id:ID!) { - addProjectNextItem(input: {projectId: $project, contentId: $id}) { - projectNextItem { - id - } - } - }' -f project=$PROJECT_ID -f id=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')" - - echo 'ITEM_ID='$item_id >> $GITHUB_ENV + uses: specklesystems/github-actions/.github/workflows/project-add-issue.yml@main + secrets: inherit + with: + issue-id: ${{ github.event.issue.node_id }} \ No newline at end of file diff --git a/.pluginconfig/4.27/.gitattributes b/.pluginconfig/4.27/.gitattributes new file mode 100644 index 0000000..6f82cb6 --- /dev/null +++ b/.pluginconfig/4.27/.gitattributes @@ -0,0 +1,6 @@ +.gitattributes export-ignore +.github/* export-ignore +.circleci/* export-ignore +.circleci/ export-ignore +.pluginconfig/* export-ignore +LICENSE export-ignore \ No newline at end of file diff --git a/.pluginconfig/4.27/SpeckleUnreal.uplugin b/.pluginconfig/4.27/SpeckleUnreal.uplugin new file mode 100644 index 0000000..19e1915 --- /dev/null +++ b/.pluginconfig/4.27/SpeckleUnreal.uplugin @@ -0,0 +1,42 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", + "CanContainContent": true, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "EngineVersion": "4.27", + "Modules": [ + { + "Name": "SpeckleUnreal", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + } + ], + "Plugins": [ + { + "Name": "ProceduralMeshComponent", + "Enabled": true + }, + { + "Name": "LidarPointCloud", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/.pluginconfig/5.0/.gitattributes b/.pluginconfig/5.0/.gitattributes new file mode 100644 index 0000000..6f82cb6 --- /dev/null +++ b/.pluginconfig/5.0/.gitattributes @@ -0,0 +1,6 @@ +.gitattributes export-ignore +.github/* export-ignore +.circleci/* export-ignore +.circleci/ export-ignore +.pluginconfig/* export-ignore +LICENSE export-ignore \ No newline at end of file diff --git a/.pluginconfig/5.0/SpeckleUnreal.uplugin b/.pluginconfig/5.0/SpeckleUnreal.uplugin new file mode 100644 index 0000000..77f1d29 --- /dev/null +++ b/.pluginconfig/5.0/SpeckleUnreal.uplugin @@ -0,0 +1,42 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", + "CanContainContent": true, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "EngineVersion": "5.0", + "Modules": [ + { + "Name": "SpeckleUnreal", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + } + ], + "Plugins": [ + { + "Name": "ProceduralMeshComponent", + "Enabled": true + }, + { + "Name": "LidarPointCloud", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/.pluginconfig/5.1/.gitattributes b/.pluginconfig/5.1/.gitattributes new file mode 100644 index 0000000..6f82cb6 --- /dev/null +++ b/.pluginconfig/5.1/.gitattributes @@ -0,0 +1,6 @@ +.gitattributes export-ignore +.github/* export-ignore +.circleci/* export-ignore +.circleci/ export-ignore +.pluginconfig/* export-ignore +LICENSE export-ignore \ No newline at end of file diff --git a/.pluginconfig/5.1/SpeckleUnreal.uplugin b/.pluginconfig/5.1/SpeckleUnreal.uplugin new file mode 100644 index 0000000..742772f --- /dev/null +++ b/.pluginconfig/5.1/SpeckleUnreal.uplugin @@ -0,0 +1,42 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", + "CanContainContent": true, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "EngineVersion": "5.1", + "Modules": [ + { + "Name": "SpeckleUnreal", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + } + ], + "Plugins": [ + { + "Name": "ProceduralMeshComponent", + "Enabled": true + }, + { + "Name": "LidarPointCloud", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/.pluginconfig/5.2/.gitattributes b/.pluginconfig/5.2/.gitattributes new file mode 100644 index 0000000..6f82cb6 --- /dev/null +++ b/.pluginconfig/5.2/.gitattributes @@ -0,0 +1,6 @@ +.gitattributes export-ignore +.github/* export-ignore +.circleci/* export-ignore +.circleci/ export-ignore +.pluginconfig/* export-ignore +LICENSE export-ignore \ No newline at end of file diff --git a/.pluginconfig/5.2/SpeckleUnreal.uplugin b/.pluginconfig/5.2/SpeckleUnreal.uplugin new file mode 100644 index 0000000..51943ca --- /dev/null +++ b/.pluginconfig/5.2/SpeckleUnreal.uplugin @@ -0,0 +1,42 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", + "CanContainContent": true, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "EngineVersion": "5.2", + "Modules": [ + { + "Name": "SpeckleUnreal", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + } + ], + "Plugins": [ + { + "Name": "ProceduralMeshComponent", + "Enabled": true + }, + { + "Name": "LidarPointCloud", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/.pluginconfig/5.3/.gitattributes b/.pluginconfig/5.3/.gitattributes new file mode 100644 index 0000000..6f82cb6 --- /dev/null +++ b/.pluginconfig/5.3/.gitattributes @@ -0,0 +1,6 @@ +.gitattributes export-ignore +.github/* export-ignore +.circleci/* export-ignore +.circleci/ export-ignore +.pluginconfig/* export-ignore +LICENSE export-ignore \ No newline at end of file diff --git a/.pluginconfig/5.3/SpeckleUnreal.uplugin b/.pluginconfig/5.3/SpeckleUnreal.uplugin new file mode 100644 index 0000000..b00b3b4 --- /dev/null +++ b/.pluginconfig/5.3/SpeckleUnreal.uplugin @@ -0,0 +1,42 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", + "CanContainContent": true, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "EngineVersion": "5.3", + "Modules": [ + { + "Name": "SpeckleUnreal", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + } + ], + "Plugins": [ + { + "Name": "ProceduralMeshComponent", + "Enabled": true + }, + { + "Name": "LidarPointCloud", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/.pluginconfig/5.4/.gitattributes b/.pluginconfig/5.4/.gitattributes new file mode 100644 index 0000000..6f82cb6 --- /dev/null +++ b/.pluginconfig/5.4/.gitattributes @@ -0,0 +1,6 @@ +.gitattributes export-ignore +.github/* export-ignore +.circleci/* export-ignore +.circleci/ export-ignore +.pluginconfig/* export-ignore +LICENSE export-ignore \ No newline at end of file diff --git a/.pluginconfig/5.4/SpeckleUnreal.uplugin b/.pluginconfig/5.4/SpeckleUnreal.uplugin new file mode 100644 index 0000000..b47e8fc --- /dev/null +++ b/.pluginconfig/5.4/SpeckleUnreal.uplugin @@ -0,0 +1,42 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", + "CanContainContent": true, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "EngineVersion": "5.4", + "Modules": [ + { + "Name": "SpeckleUnreal", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + } + ], + "Plugins": [ + { + "Name": "ProceduralMeshComponent", + "Enabled": true + }, + { + "Name": "LidarPointCloud", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/Config/DefaultSpeckleUnreal.ini b/Config/DefaultSpeckleUnreal.ini new file mode 100644 index 0000000..fed4408 --- /dev/null +++ b/Config/DefaultSpeckleUnreal.ini @@ -0,0 +1,2 @@ +[CoreRedirects] ++FunctionRedirects=(OldName="/Script/SpeckleUnreal.ObjectModelRegistry.FindClosestType",NewName="/Script/SpeckleUnreal.ObjectModelRegistry.GetAtomicType") \ No newline at end of file diff --git a/Config/FilterPlugin.ini b/Config/FilterPlugin.ini index ccebca2..11d8e6e 100644 --- a/Config/FilterPlugin.ini +++ b/Config/FilterPlugin.ini @@ -1,8 +1,2 @@ [FilterPlugin] -; This section lists additional files which will be packaged along with your plugin. Paths should be listed relative to the root plugin directory, and -; may include "...", "*", and "?" wildcards to match directories, files, and individual characters respectively. -; -; Examples: -; /README.txt -; /Extras/... -; /Binaries/ThirdParty/*.dll +/README.md \ No newline at end of file diff --git a/Content/API/BP_APIOperations.uasset b/Content/API/BP_APIOperations.uasset new file mode 100644 index 0000000..fda8c44 Binary files /dev/null and b/Content/API/BP_APIOperations.uasset differ diff --git a/Content/Converters/BP_CameraConverter.uasset b/Content/Converters/BP_CameraConverter.uasset new file mode 100644 index 0000000..c7ed6ca Binary files /dev/null and b/Content/Converters/BP_CameraConverter.uasset differ diff --git a/Content/Converters/DefaultBlockConverter.uasset b/Content/Converters/DefaultBlockConverter.uasset new file mode 100644 index 0000000..ca4be1b Binary files /dev/null and b/Content/Converters/DefaultBlockConverter.uasset differ diff --git a/Content/Converters/DefaultCameraConverter.uasset b/Content/Converters/DefaultCameraConverter.uasset new file mode 100644 index 0000000..65c6781 Binary files /dev/null and b/Content/Converters/DefaultCameraConverter.uasset differ diff --git a/Content/Converters/DefaultCollectionConverter.uasset b/Content/Converters/DefaultCollectionConverter.uasset new file mode 100644 index 0000000..45784f9 Binary files /dev/null and b/Content/Converters/DefaultCollectionConverter.uasset differ diff --git a/Content/Converters/DefaultMaterialConverter.uasset b/Content/Converters/DefaultMaterialConverter.uasset new file mode 100644 index 0000000..c331311 Binary files /dev/null and b/Content/Converters/DefaultMaterialConverter.uasset differ diff --git a/Content/Converters/DefaultPointCloudConverter.uasset b/Content/Converters/DefaultPointCloudConverter.uasset new file mode 100644 index 0000000..927ba31 Binary files /dev/null and b/Content/Converters/DefaultPointCloudConverter.uasset differ diff --git a/Content/Converters/DefaultProceduralMeshConverter.uasset b/Content/Converters/DefaultProceduralMeshConverter.uasset new file mode 100644 index 0000000..b607d7e Binary files /dev/null and b/Content/Converters/DefaultProceduralMeshConverter.uasset differ diff --git a/Content/Converters/DefaultStaticMeshConverter.uasset b/Content/Converters/DefaultStaticMeshConverter.uasset new file mode 100644 index 0000000..8273997 Binary files /dev/null and b/Content/Converters/DefaultStaticMeshConverter.uasset differ diff --git a/Content/Examples/BlueprintReceiving.uasset b/Content/Examples/BlueprintReceiving.uasset new file mode 100644 index 0000000..08c9963 Binary files /dev/null and b/Content/Examples/BlueprintReceiving.uasset differ diff --git a/Content/Tests/API/BP_BranchFetchTest.uasset b/Content/Tests/API/BP_BranchFetchTest.uasset new file mode 100644 index 0000000..664a537 Binary files /dev/null and b/Content/Tests/API/BP_BranchFetchTest.uasset differ diff --git a/Content/Tests/API/BP_CommitFetchTest.uasset b/Content/Tests/API/BP_CommitFetchTest.uasset new file mode 100644 index 0000000..f5eac14 Binary files /dev/null and b/Content/Tests/API/BP_CommitFetchTest.uasset differ diff --git a/Content/Tests/API/BP_FetchBranchTest.uasset b/Content/Tests/API/BP_FetchBranchTest.uasset new file mode 100644 index 0000000..ce486df Binary files /dev/null and b/Content/Tests/API/BP_FetchBranchTest.uasset differ diff --git a/Content/Tests/API/BP_ListCommitsTest.uasset b/Content/Tests/API/BP_ListCommitsTest.uasset new file mode 100644 index 0000000..44dbb9b Binary files /dev/null and b/Content/Tests/API/BP_ListCommitsTest.uasset differ diff --git a/Content/Tests/API/BP_ListSTreamsTest.uasset b/Content/Tests/API/BP_ListSTreamsTest.uasset new file mode 100644 index 0000000..855d042 Binary files /dev/null and b/Content/Tests/API/BP_ListSTreamsTest.uasset differ diff --git a/Content/Tests/API/BP_StreamFetchTest.uasset b/Content/Tests/API/BP_StreamFetchTest.uasset new file mode 100644 index 0000000..1df37fb Binary files /dev/null and b/Content/Tests/API/BP_StreamFetchTest.uasset differ diff --git a/Content/Tests/API/BP_StreamsFetchTest.uasset b/Content/Tests/API/BP_StreamsFetchTest.uasset new file mode 100644 index 0000000..bfa01a2 Binary files /dev/null and b/Content/Tests/API/BP_StreamsFetchTest.uasset differ diff --git a/Content/Tests/API/BP_UserFetch.uasset b/Content/Tests/API/BP_UserFetch.uasset new file mode 100644 index 0000000..32916a2 Binary files /dev/null and b/Content/Tests/API/BP_UserFetch.uasset differ diff --git a/Content/Tests/API/StreamFetchTest.uasset b/Content/Tests/API/StreamFetchTest.uasset new file mode 100644 index 0000000..b8e4a38 Binary files /dev/null and b/Content/Tests/API/StreamFetchTest.uasset differ diff --git a/README.md b/README.md index 0160f8c..2b38420 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,64 @@ -# Speckle Unreal +# Speckle for Unreal Engine -[![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/) +[![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/user/unreal.html) -Plugin for Unreal Engine 4 to import objects from Speckle v2. +Speckle makes integrating Unreal Engine with your 3D workflows even easier.
+This plugin connects Unreal Engine to Speckle, allowing you to receive your versioned 3D data from Speckle inside Unreal Engine, +enabling interoperable collaboration between Unreal and other Speckle connectors (Revit, Rhino, Blender, Sketchup, Unity, AutoCAD, [and more!](https://speckle.systems/features/connectors/)) -Screencast of an example: https://user-images.githubusercontent.com/2551138/114720093-61403e00-9d40-11eb-8045-6e8ca656554d.mp4 +https://user-images.githubusercontent.com/45512892/187969471-3f548b17-3388-48ee-a07c-bd3a0ecf5149.mp4 +Checkout our dedicated [Tutorials and Docs](https://v1.speckle.systems/tag/unreal/). +If you are enjoying using Speckle, don't forget to ⭐ our [GitHub repositories](https://github.com/specklesystems), +and [join our community forum](https://speckle.community/) where you can post any questions, suggestions, and discuss exciting projects! -## NOTICE +## Notice -* Tested on Windows, Unreal Engine v4.26 and Visual Studio Community 2019 -* Only displays meshes. Breps are converted using their display values. -* Does not use the Speckle Kit workflow as conversions all happen in C++. +We officially support Unreal Engine 4.27, 5.0-5.4 -## How To Install +**Features**: +- [Receiving Speckle geometry as Actors in editor and standalone runtime](https://speckle.systems/tutorials/getting-started-with-speckle-for-unreal/). +- [Material override/substitiution](https://speckle.guide/user/unreal.html#material-converter). +- [Blueprint nodes for receiving and converting objects](https://speckle.guide/user/unreal.html#usage-blueprint). +- [Blueprint nodes for fetching stream/branch/commit/user details](https://speckle.systems/tutorials/unreal-engine-blueprint-nodes-fetch-stream-branch-commit-info-and-more/). +- [Ability to write/extend custom conversion functions in C++/BP](https://speckle.systems/tutorials/unreal-developing-custom-conversion-logic/). +**Supported Conversions**: -1. Clone the repository or download it as a zip file. -2. Navigate to `SpeckleUnrealProject` > `Plugins` and copy the `SpeckleUnreal` folder -3. Paste the folder into your Unreal project under `YourUnrealProjectFolder` > `Plugins` (Create a `Plugins` folder if you don't already have one). -4. Reopen your project. + Speckle Type | | Native Type | +| ---: | :---: | :--- | +| [`Objects.Geometry.Mesh`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Mesh.cs) | → | [Static Mesh Component](https://docs.unrealengine.com/4.27/en-US/API/Runtime/Engine/Components/UStaticMeshComponent/) /
[Procedural Mesh Component](https://docs.unrealengine.com/4.27/en-US/API/Plugins/ProceduralMeshComponent/UProceduralMeshComponent/) | +| [`Objects.Geometry.PointCloud`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Pointcloud.cs) | → | [LiDAR Point Cloud](https://docs.unrealengine.com/4.27/en-US/WorkingWithContent/LidarPointCloudPlugin/LidarPointCloudPluginReference/) | +| [`Objects.Other.Instance`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Other/Instance.cs) | → | Actor with Transform | +| [`Objects.BuiltElements.View`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/BuiltElements/View.cs) | → | [Camera](https://docs.unrealengine.com/4.27/en-US/InteractiveExperiences/Framework/Camera/) | +| [`Speckle.Core.Models.Collection`](https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Models/Collection.cs) | → | Empty Actor | -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. +**Supported platforms**: Windows, Linux, MacOS +*Other platforms may work, but currently untested*. -## 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 +**Limitations**: +- Currently no support for sending Unreal geometry to Speckle. +- Does not use the .NET or Python SDK, or the Speckle Kit based workflow, all code is in native C++/BP. +- Does not use our shared [Desktop UI 2](https://speckle.guide/user/ui2.html), only a simple editor UI is currently provided. +- Does not fetch [accounts from Speckle Manager](https://speckle.guide/user/manager.html#logging-in-adding-accounts), you must generate a [personal access token (auth token)](https://speckle.guide/dev/tokens.html#personal-access-tokens) to receive non-public streams. +## How to install + +**Speckle for Unreal Engine** can be installed through the [Unreal Engine Marketplace](https://www.unrealengine.com/marketplace/en-US/product/speckle-for-unreal-engine). + +--- + +Alternatively, developers may prefer to install manually. +1. Git clone [this repo](https://github.com/specklesystems/speckle-unreal) (or download and extract the [archive zip](https://github.com/specklesystems/speckle-unreal/archive/refs/heads/main.zip)) into your project's `Plugins` directory (created as needed) +2. Open/Restart your Unreal project. This will build the plugin for your environment. + +See our [docs](https://speckle.guide/user/unreal.html) for usage instructions. + +If you encounter build issues, try building your project from VS/Rider directly. Look at the `Saved\Logs\` files for error messages, +and don't hesitate to reach out on our [community forums](https://speckle.community) for help! + +For contributing to any of our code repositories, please make sure you read the [contribution guidelines](https://github.com/specklesystems/speckle-sharp/blob/main/.github/CONTRIBUTING.md) for an overview of the best practices we try to follow. diff --git a/Source/SpeckleUnreal/Private/API/ClientAPI.cpp b/Source/SpeckleUnreal/Private/API/ClientAPI.cpp new file mode 100644 index 0000000..ded67e4 --- /dev/null +++ b/Source/SpeckleUnreal/Private/API/ClientAPI.cpp @@ -0,0 +1,194 @@ + +#include "API/ClientAPI.h" + +#include "HttpModule.h" +#include "JsonObjectConverter.h" +#include "Interfaces/IHttpResponse.h" +#include "LogSpeckle.h" +#include "Mixpanel.h" + +void FClientAPI::MakeGraphQLRequest(const FString& ServerUrl, const FString& AuthToken, + const FString& ResponsePropertyName, + const FString& PostPayload, const FString& RequestLogName, + const FAPIResponceDelegate OnCompleteAction, const FErrorDelegate OnErrorAction) +{ + + auto OnError = [=](const FString& Message) mutable + { + UE_LOG(LogSpeckle, Warning, TEXT("%s: failed - %s"), *RequestLogName , *Message); + ensureAlwaysMsgf(OnErrorAction.ExecuteIfBound(Message), TEXT("%s: Unhandled error - %s"), *RequestLogName , *Message); + }; + + auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable + { + if(CheckRequestFailed(bWasSuccessful, Response, RequestLogName, OnError)) return; + + TSharedPtr Obj; + if(!GetResponseAsJSON(Response, RequestLogName, Obj, OnError)) return; + + const TSharedPtr* DataObjectPtr; + if(!Obj->TryGetObjectField(TEXT("data"), DataObjectPtr)) + { + OnError(TEXT("%s responce was invalid, expected to find a \"data\" property in response")); + return; + } + const TSharedPtr DataObject = *DataObjectPtr; + + const TSharedPtr* RequestedJson; + if(!DataObject->TryGetObjectField(ResponsePropertyName, RequestedJson)) + { + //Requested property has a null or non-object value + if(DataObject->HasField(ResponsePropertyName)) + { + FString Message = FString::Printf(TEXT("%s: Response data contained the requested property \"%s\", but the value was null was or not an object."), + *RequestLogName, *ResponsePropertyName); + OnError(Message); + return; + } + + //Requested property was missing + TArray Options; + Options.Reserve(DataObject->Values.Num()); + for(const auto& Properties : DataObject->Values) + { + Options.Add(FString::Printf(TEXT("\"%s\" "), *Properties.Key)); + } + + FString Message = FString::Printf(TEXT("%s: Could not find the requested property name \"%s\" in responce data.\n Got { %s} instead."), + *RequestLogName, *ResponsePropertyName, *FString::Join(Options, TEXT(", "))); + OnError(Message); + return; + } + + FString OutputString; + const TSharedRef> Writer = TJsonWriterFactory<>::Create(&OutputString); + ensureAlways(FJsonSerializer::Serialize(RequestedJson->ToSharedRef(), Writer)); + + // Commented out, deserialisation done by caller + //void* DeserializedData; + //FSpeckleUser DeserializedData = FSpeckleUser( UserJSONObject ); + // if(!FJsonObjectConverter::JsonObjectToUStruct(*RequestedJson, OutStructType::StaticStruct(), &DeserializedData, 0, 0)) + // { + // OnError("Failed to deserialize user object"); + // return; + // } + + UE_LOG(LogSpeckle, Log, TEXT("Operation %s completed successfully"), *RequestLogName); + ensureAlwaysMsgf(OnCompleteAction.ExecuteIfBound(OutputString), TEXT("%s: Complete handler was not bound properly"), *RequestLogName); + }; + + const FHttpRequestRef Request = CreatePostRequest(ServerUrl, AuthToken, PostPayload); + Request->OnProcessRequestComplete().BindLambda(ResponseHandler); + + if(Request->ProcessRequest()) + { + UE_LOG(LogSpeckle, Log, TEXT("POST Request %s to %s was sent, awaiting response"), *RequestLogName, *Request->GetURL() ); + } + else + { + UE_LOG(LogSpeckle, Warning, TEXT("POST Request %s to %s failed to send"), *RequestLogName, *Request->GetURL() ); + } + + FAnalytics::TrackEvent(Request->GetURL(), TEXT("NodeRun"), TMap { {TEXT("name"), __FUNCTION__}}); +} + + +bool FClientAPI::GetResponseAsJSON(const FHttpResponsePtr Response, const FString& RequestLogName, TSharedPtr& OutObject, const TFunctionRef OnErrorAction) +{ + + const FString JsonResponse = Response->GetContentAsString(); + + TSharedRef> Reader = TJsonReaderFactory<>::Create(JsonResponse); + + if(!FJsonSerializer::Deserialize(Reader, OutObject)) + { + const FString Message = FString::Printf( + TEXT("Recieved a response from \"%s\" for \"%s\" request, but the response failed to deserialize: %s"), + *Response->GetURL(), *RequestLogName, *JsonResponse); + OnErrorAction(Message); + return false; + } + + + FString Error; + if(CheckForOperationErrors(OutObject, Error)) + { + OnErrorAction(Error); + return false; + } + + return true; +} + +FHttpRequestRef FClientAPI::CreatePostRequest(const FString& ServerUrl, const FString AuthToken, const FString& PostPayload, const FString& Encoding) +{ + FHttpRequestRef Request = FHttpModule::Get().CreateRequest(); + + Request->SetURL(ServerUrl + TEXT("/graphql")); + Request->SetVerb(TEXT("POST")); + Request->SetHeader(TEXT("Accept-Encoding"), Encoding); + Request->SetHeader(TEXT("Content-Type"), TEXT("application/json")); + if(!AuthToken.IsEmpty()) + Request->SetHeader(TEXT("Authorization"), FString::Printf(TEXT("Bearer %s"), *AuthToken)); + Request->SetHeader(TEXT("apollographql-client-name"), TEXT("Unreal Engine")); + Request->SetHeader(TEXT("apollographql-client-version"), SPECKLE_CONNECTOR_VERSION); + Request->SetContentAsString(PostPayload); + + return Request; +} + + + +bool FClientAPI::CheckRequestFailed(bool bWasSuccessful, FHttpResponsePtr Response, const FString& RequestLogName, const TFunctionRef OnErrorAction) +{ + //Check the request was sent + if(!bWasSuccessful) + { + FString Message = FString::Printf(TEXT("Request \"%s\" to \"%s\" was unsuccessful: %s"), + *RequestLogName, *Response->GetURL(), *Response->GetContentAsString()); + OnErrorAction(Message); + return true; + } + + //Check Response code + const int32 ResponseCode = Response->GetResponseCode(); + if (ResponseCode != 200) + { + FString Message = FString::Printf(TEXT("Request \"%s\" to \"%s\" failed with HTTP response %d - %s"), + *RequestLogName, *Response->GetURL(), ResponseCode, *Response->GetContentAsString()); + OnErrorAction(Message); + return true; + } + + UE_LOG(LogSpeckle, Log, TEXT("Operation %s recieved a response from %s"), *RequestLogName, *Response->GetURL()); + + return false; +} + +bool FClientAPI::CheckForOperationErrors(const TSharedPtr GraphQLResponse, FString& OutErrorMessage) +{ + check(GraphQLResponse != nullptr); + + bool WasError = false; + const TArray>* Errors; + if(GraphQLResponse->TryGetArrayField(TEXT("errors"), Errors)) + { + for(const TSharedPtr& e : *Errors) + { + FString Message; + const TSharedPtr* ErrorObject; + bool HadMessage = e->TryGetObject(ErrorObject) + && (*ErrorObject)->TryGetStringField(TEXT("message"), Message); + if(!HadMessage) + { + Message = TEXT("An operation error occured but had no message!\n"); + UE_LOG(LogSpeckle, Warning, TEXT("%s"), *Message); + } + + OutErrorMessage.Append(Message + "\n"); + WasError = true; + } + } + return WasError; +} + diff --git a/Source/SpeckleUnreal/Private/API/Operations/ReceiveOperation.cpp b/Source/SpeckleUnreal/Private/API/Operations/ReceiveOperation.cpp new file mode 100644 index 0000000..3cb93ac --- /dev/null +++ b/Source/SpeckleUnreal/Private/API/Operations/ReceiveOperation.cpp @@ -0,0 +1,91 @@ + +#include "API/Operations/ReceiveOperation.h" + +#include "Dom/JsonObject.h" +#include "Transports/Transport.h" +#include "API/SpeckleSerializer.h" +#include "Objects/Base.h" +#include "Mixpanel.h" + + +UReceiveOperation* UReceiveOperation::ReceiveOperation(UObject* WorldContextObject, + const FString& ObjectId, + TScriptInterface RemoteTransport, + TScriptInterface LocalTransport) +{ + UReceiveOperation* Node = NewObject(); + Node->ObjectId = ObjectId; + Node->RemoteTransport = RemoteTransport; + Node->LocalTransport = LocalTransport; + + Node->RegisterWithGameInstance(WorldContextObject); + return Node; +} + +void UReceiveOperation::Activate() +{ + FAnalytics::TrackEvent("unknown", "NodeRun", TMap { {"name", StaticClass()->GetName()} }); + + Receive(); +} + +void UReceiveOperation::Receive() +{ + check(LocalTransport != nullptr); + + // 1. Try and get object from local transport + auto Obj = LocalTransport->GetSpeckleObject(ObjectId); + + if (Obj != nullptr ) + { + HandleReceive(Obj); + return; + } + + // 2. Try and get object from remote transport + if(RemoteTransport == nullptr) + { + FString ErrorMessage = TEXT( + "Could not find specified object using the local transport, and you didn't provide a fallback remote from which to pull it."); + + HandleError(ErrorMessage); + return; + } + + FTransportCopyObjectCompleteDelegate CompleteDelegate; + CompleteDelegate.BindUObject(this, &UReceiveOperation::HandleReceive); + + FTransportErrorDelegate ErrorDelegate; + ErrorDelegate.BindUObject(this, &UReceiveOperation::HandleError); + + RemoteTransport->CopyObjectAndChildren(ObjectId, LocalTransport, CompleteDelegate, ErrorDelegate); +} + +void UReceiveOperation::HandleReceive(TSharedPtr Object) +{ + check(IsInGameThread()) + + FEditorScriptExecutionGuard ScriptGuard; + if(Object == nullptr) + { + OnError.Broadcast(nullptr, FString::Printf(TEXT("Failed to get object %s from transport"), *ObjectId)); + } + else + { + UBase* Res = USpeckleSerializer::DeserializeBase(Object, LocalTransport); + if(IsValid(Res)) + OnReceiveSuccessfully.Broadcast(Res, ""); + else + OnError.Broadcast(nullptr, FString::Printf(TEXT("Root Speckle Object %s failed to deserialize"), *ObjectId)); + } + + + SetReadyToDestroy(); +} + +void UReceiveOperation::HandleError(FString& Message) +{ + FEditorScriptExecutionGuard ScriptGuard; + OnError.Broadcast(nullptr, Message); + SetReadyToDestroy(); +} \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/API/Operations/SpeckleStreamAPIOperation.cpp b/Source/SpeckleUnreal/Private/API/Operations/SpeckleStreamAPIOperation.cpp new file mode 100644 index 0000000..0b30e34 --- /dev/null +++ b/Source/SpeckleUnreal/Private/API/Operations/SpeckleStreamAPIOperation.cpp @@ -0,0 +1,68 @@ + +#include "API/Operations/SpeckleStreamAPIOperation.h" + +#include "JsonObjectConverter.h" +#include "Mixpanel.h" +#include "LogSpeckle.h" +#include "API/ClientAPI.h" + + +USpeckleStreamAPIOperation* USpeckleStreamAPIOperation::SpeckleStreamAPIOperation( + const FString& ServerUrl, + const FString& AuthToken, + const FString& GraphQlQuery, + const FString& ResponsePropertyName, + const FString& RequestLogName) +{ + USpeckleStreamAPIOperation* Node = NewObject(); + Node->ServerUrl = ServerUrl.TrimEnd(); + Node->AuthToken = AuthToken.TrimEnd(); + Node->Query = GraphQlQuery; + Node->ResponsePropertyName = ResponsePropertyName; + Node->RequestLogName = RequestLogName; + + return Node; +} + +void USpeckleStreamAPIOperation::Activate() +{ + FAnalytics::TrackEvent(ServerUrl, "NodeRun", TMap { {"name", RequestLogName} }); + + Request(); +} + +void USpeckleStreamAPIOperation::Request() +{ + FString Payload = FString::Printf(TEXT("{\"query\": \"%s\"}"), *Query.ReplaceCharWithEscapedChar()); + FAPIResponceDelegate CompleteDelegate; + CompleteDelegate.BindUObject(this, &USpeckleStreamAPIOperation::HandleReceive); + + FErrorDelegate ErrorDelegate; + ErrorDelegate.BindUObject(this, &USpeckleStreamAPIOperation::HandleError); + FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, ResponsePropertyName, Payload,RequestLogName , CompleteDelegate, ErrorDelegate); +} + +void USpeckleStreamAPIOperation::HandleReceive(const FString& ResponseJson) +{ + check(IsInGameThread()); + + UE_LOG(LogSpeckle, Log, TEXT("%s to %s Succeeded"), *StaticClass()->GetName(), *ServerUrl); + + FEditorScriptExecutionGuard ScriptGuard; + OnReceiveSuccessfully.Broadcast(ResponseJson, ""); + + SetReadyToDestroy(); +} + +void USpeckleStreamAPIOperation::HandleError(const FString& Message) +{ + check(IsInGameThread()); + + UE_LOG(LogSpeckle, Warning, TEXT("%s failed - %s"), *StaticClass()->GetName(), *Message); + + FEditorScriptExecutionGuard ScriptGuard; + OnError.Broadcast("", Message); + + SetReadyToDestroy(); +} + diff --git a/Source/SpeckleUnreal/Private/API/SpeckleAPIFunctions.cpp b/Source/SpeckleUnreal/Private/API/SpeckleAPIFunctions.cpp new file mode 100644 index 0000000..33b183e --- /dev/null +++ b/Source/SpeckleUnreal/Private/API/SpeckleAPIFunctions.cpp @@ -0,0 +1,57 @@ + +#include "API/SpeckleAPIFunctions.h" + +#include "JsonObjectConverter.h" + +bool USpeckleAPIFunctions::DeserializeResponse(const FString& JsonString, int32& OutStruct) +{ + // We should never hit this! stubs to avoid NoExport on the class. + check(0); + return false; +} + + +bool USpeckleAPIFunctions::GenericDeserializeResponse(const FString& JsonString, const UScriptStruct* StructType, + void* OutStruct) +{ + //see FJsonObjectConverter::JsonObjectStringToUStruct + TSharedPtr JsonObject; + TSharedRef > JsonReader = TJsonReaderFactory<>::Create(JsonString); + if (!FJsonSerializer::Deserialize(JsonReader, JsonObject) || !JsonObject.IsValid()) + { + UE_LOG(LogJson, Warning, TEXT("JsonObjectStringToUStruct - Unable to parse json=[%s]"), *JsonString); + return false; + } + if (!FJsonObjectConverter::JsonObjectToUStruct(JsonObject.ToSharedRef(), StructType, OutStruct, 0, 0)) + { + UE_LOG(LogJson, Warning, TEXT("JsonObjectStringToUStruct - Unable to deserialize. json=[%s]"), *JsonString); + return false; + } + return true; +} + +void USpeckleAPIFunctions::CommitReceived(FSpeckleCommit& Commit) +{ + //TODO send read read receipt + //FString Query = FString::Printf(TEXT("mutation{ commitReceive(input:%s) }"), ); +} + +DEFINE_FUNCTION(USpeckleAPIFunctions::execDeserializeResponse) +{ + // Get JsonString + P_GET_PROPERTY(FStrProperty, JsonString); + + // Get OutStruct + Stack.MostRecentPropertyAddress = nullptr; + Stack.StepCompiledIn(nullptr); + void* OutBlueprintDataPtr = Stack.MostRecentPropertyAddress; + FStructProperty* StructProp = CastField(Stack.MostRecentProperty); + UScriptStruct* StructType = StructProp->Struct; + + P_FINISH; + + P_NATIVE_BEGIN; + + *static_cast(RESULT_PARAM) = GenericDeserializeResponse(JsonString, StructType, OutBlueprintDataPtr); + P_NATIVE_END; +} \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/API/SpeckleSerializer.cpp b/Source/SpeckleUnreal/Private/API/SpeckleSerializer.cpp new file mode 100644 index 0000000..db12023 --- /dev/null +++ b/Source/SpeckleUnreal/Private/API/SpeckleSerializer.cpp @@ -0,0 +1,80 @@ + +#include "API/SpeckleSerializer.h" + +#include "Objects/Base.h" +#include "LogSpeckle.h" +#include "Objects/DisplayValueElement.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Objects/ObjectModelRegistry.h" +#include "Templates/SubclassOf.h" +#include "Transports/Transport.h" +#include "UObject/Package.h" + + +UBase* USpeckleSerializer::DeserializeBase(const TSharedPtr Obj, + const TScriptInterface ReadTransport) +{ + if(Obj == nullptr) return nullptr; + + // Handle Detached Objects + TSharedPtr DetachedObject; + if(USpeckleObjectUtils::ResolveReference(Obj, ReadTransport, DetachedObject)) + { + return DeserializeBase(DetachedObject, ReadTransport); + } + + FString SpeckleType; + if (!Obj->TryGetStringField(TEXT("speckle_type"), SpeckleType)) return nullptr; + FString ObjectId = ""; + Obj->TryGetStringField(TEXT("id"), ObjectId); + + TSubclassOf BaseType; + + FString WorkingType{}; + FString Remainder = FString(SpeckleType); + + int32 Tries = 200; + while(ensure(Tries-- > 0)) + { + const bool IsLastChance = !UObjectModelRegistry::SplitSpeckleType(Remainder, Remainder, WorkingType); + + if(UObjectModelRegistry::TryGetRegisteredType(WorkingType, BaseType)) + { + UBase* Base = NewObject(GetTransientPackage(), BaseType); + if(Base->Parse(Obj, ReadTransport)) + return Base; + } + + if(IsLastChance) + { + //Try a fallback displayValue object + UBase* Base = NewObject(GetTransientPackage(), UDisplayValueElement::StaticClass()); + if(Base->Parse(Obj, ReadTransport)) + return Base; + + //If not, try a regular Base + Base = NewObject(GetTransientPackage(), UBase::StaticClass()); + if(Base->Parse(Obj, ReadTransport)) + return Base; + + UE_LOG(LogSpeckle, Warning, TEXT("Skipping deserilization of %s id: %s - object could not be deserilaized to Base"), *SpeckleType, *ObjectId ); + return nullptr; + } + + //If we couldn't even deserialize this to a Base, something is quite wrong... + if(WorkingType == TEXT("Base") || BaseType == UBase::StaticClass()) + { + UE_LOG(LogSpeckle, Warning, TEXT("Skipping deserilization of %s id: %s - object could not be deserilaized to Base"), *SpeckleType, *ObjectId ); + return nullptr; + } + } + + return nullptr; +} + +UBase* USpeckleSerializer::DeserializeBaseById(const FString& ObjectId, + const TScriptInterface ReadTransport) +{ + auto Obj = ReadTransport->GetSpeckleObject(ObjectId); + return DeserializeBase(Obj, ReadTransport); +} diff --git a/Source/SpeckleUnreal/Private/Analytics.cpp b/Source/SpeckleUnreal/Private/Analytics.cpp new file mode 100644 index 0000000..cdf604c --- /dev/null +++ b/Source/SpeckleUnreal/Private/Analytics.cpp @@ -0,0 +1,89 @@ + +#include "Mixpanel.h" + +#include "Containers/UnrealString.h" +#include "HttpModule.h" +#include "Kismet/GameplayStatics.h" +#include "LogSpeckle.h" +#include "Interfaces/IHttpResponse.h" +#include "Misc/Base64.h" +#include "Runtime/Launch/Resources/Version.h" +#include "Policies/CondensedJsonPrintPolicy.h" +#include "Serialization/JsonSerializerMacros.h" +#include "Serialization/JsonWriter.h" + +const FString FAnalytics::MixpanelToken = TEXT("acd87c5a50b56df91a795e999812a3a4"); +const FString FAnalytics::MixpanelServer = TEXT("https://analytics.speckle.systems"); +const FString FAnalytics::VersionedApplicationName = FString::Printf(TEXT("Unreal Engine %d.%d"), ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION); + +void FAnalytics::TrackEvent(const FString& Server, const FString& EventName) +{ + const TMap CustomProperties; + TrackEvent( Server, EventName, CustomProperties); +} + +void FAnalytics::TrackEvent(const FString& Server, const FString& EventName, const TMap& CustomProperties) +{ + //Since we don't have access to users email address, we will hash the system user name instead (better than not tracking users at all) + const FString UserID = FString(FPlatformProcess::ComputerName()) + FString(FPlatformProcess::UserName()); + TrackEvent(UserID, Server, EventName, CustomProperties); +} + +void FAnalytics::TrackEvent(const FString& UserID, const FString& Server, const FString& EventName, const TMap& CustomProperties) +{ + + FString HashedUserID = "@" + Hash(UserID); //prepending an @ so we distinguish logged and non-logged users + FString HashedServer = Hash(Server); + + TMap Properties + { + { "distinct_id", HashedUserID }, + { "server_id", HashedServer }, + { "token", MixpanelToken }, + { "hostApp", "Unreal Engine" }, + { "hostAppVersion", VersionedApplicationName }, + { "$os", *UGameplayStatics::GetPlatformName() }, + { "type", "action" } + }; + + + Properties.Append(CustomProperties); + + FString Json; + { + auto Writer = TJsonWriterFactory>::Create(&Json); + FJsonSerializerWriter> Serializer(Writer); + Serializer.StartObject(); + FString EventNameString = EventName; + Serializer.Serialize(TEXT("event"), EventNameString); + Serializer.SerializeMap(TEXT("properties"), Properties); + Serializer.EndObject(); + Writer->Close(); + } + const FString Data = FBase64::Encode(Json); + + // Create Request + const FHttpRequestRef Request = FHttpModule::Get().CreateRequest(); + { + Request->SetURL(MixpanelServer + "/track?ip=1&data=" + Data); + Request->SetHeader("Content-Type", "application/x-www-form-urlencoded"); + Request->SetHeader("Accept", TEXT("text/plain")); + Request->SetVerb("POST"); + } + + Request->OnProcessRequestComplete().BindLambda([](FHttpRequestPtr, FHttpResponsePtr Response, bool) + { + UE_LOG(LogSpeckle, Verbose, TEXT("Recieved Mixpanel resonse %d"), Response->GetResponseCode()); + }); + + const bool RequestSent = Request->ProcessRequest(); + if(!RequestSent) + { + UE_LOG(LogSpeckle, Log, TEXT("Failed to send Mixpanel event to %s"), *MixpanelServer); + } +} + +FString FAnalytics::Hash(const FString& Input) +{ + return FMD5::HashAnsiString(*Input.ToLower()); +} diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/AggregateConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/AggregateConverter.cpp new file mode 100644 index 0000000..7b962f2 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/AggregateConverter.cpp @@ -0,0 +1,137 @@ + +#include "Conversion/Converters/AggregateConverter.h" + +#include "LogSpeckle.h" +#include "Templates/SubclassOf.h" + + +void UAggregateConverter::OnConvertersChangeHandler() +{ + SpeckleTypeMap.Empty(); + + for(int i = 0; i < SpeckleConverters.Num(); i++) + { + const UObject* Converter = SpeckleConverters[i]; + if(Converter != nullptr && !Converter->GetClass()->ImplementsInterface(USpeckleConverter::StaticClass())) + { + UE_LOG(LogSpeckle, Warning, TEXT("Converter {%s} is not a valid converter, Expected to implement interface %s"), *Converter->GetClass()->GetName(), *USpeckleConverter::StaticClass()->GetName()) + SpeckleConverters.RemoveAt(i); + i--; + } + } +} + +#if WITH_EDITOR +void UAggregateConverter::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) +{ + Super::PostEditChangeProperty(PropertyChangedEvent); + + if (PropertyChangedEvent.GetPropertyName() == GET_MEMBER_NAME_CHECKED(UAggregateConverter, SpeckleConverters)) + { + OnConvertersChangeHandler(); + } +} +#endif + +UBase* UAggregateConverter::ConvertToSpeckle_Implementation(const UObject* Object) +{ + //TODO implement ToSpeckle + unimplemented(); + return nullptr; +} + + +UObject* UAggregateConverter::ConvertToNative_Implementation(const UBase* Object, UWorld* World, TScriptInterface& ) +{ + return ConvertToNativeInternal(Object, World); +} + +UObject* UAggregateConverter::ConvertToNativeInternal(const UBase* Object, UWorld* World) +{ + check(IsInGameThread()); + + if(!IsValid(Object)) return nullptr; + + const TSubclassOf Type = Object->GetClass(); + UObject* Converter = GetConverter(Type).GetObject(); + if(!IsValid(Converter)) + { + if(Type != UBase::StaticClass()) + { + UE_LOG(LogSpeckle, Warning, TEXT("Skipping Object %s: No conversion functions exist for %s"), *Object->Id, *Type->GetName()); + } + return nullptr; + } + + UE_LOG(LogSpeckle, Log, TEXT("Converting object of type: %s id: %s"), *Type->GetName(), *Object->Id); + + FEditorScriptExecutionGuard ScriptGuard; + + TScriptInterface MainConverter = this; + + check(Converter->IsValidLowLevel()); + return Execute_ConvertToNative(Converter, Object, World, MainConverter); + +} + +bool UAggregateConverter::CanConvertToNative_Implementation(TSubclassOf BaseType) +{ + return GetConverter(BaseType).GetInterface() != nullptr; +} + +TScriptInterface UAggregateConverter::GetConverter(const TSubclassOf BaseType) +{ + // Check if this SpeckleType has a known converter. + if(SpeckleTypeMap.Contains(BaseType)) + { + return SpeckleTypeMap[BaseType]; + } + + // Try and find one that can convert this SpeckleType. + FEditorScriptExecutionGuard ScriptGuard; + for(UObject* Converter : SpeckleConverters) + { + if(!CheckValidConverter(Converter)) continue; + + if(Execute_CanConvertToNative(Converter, BaseType)) + { + //Found a Converter! Save this mapping for next time. + SpeckleTypeMap.Add(BaseType, Converter); + return Converter; + } + } + + // SpeckleType has no conversions. + SpeckleTypeMap.Add(BaseType, nullptr); + return nullptr; +} + +void UAggregateConverter::FinishConversion_Implementation() +{ + FinishConversion_Internal(); +} + +void UAggregateConverter::FinishConversion_Internal() +{ + for (UObject* Converter : SpeckleConverters) + { + if(!CheckValidConverter(Converter)) continue; + + Execute_FinishConversion(Converter); + } + OnConvertersChangeHandler(); +} + +bool UAggregateConverter::CheckValidConverter(const UObject* Converter, bool LogWarning) +{ + if(Converter == nullptr) return false; + + if(Converter->Implements()) return true; + + if(LogWarning) + { + UE_LOG(LogSpeckle, Warning, TEXT("Converter {%s} is not a valid converter, Expected to implement interface {%s}"), *Converter->GetClass()->GetName(), *USpeckleConverter::StaticClass()->GetName()) + } + + return false; +} diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/BlockConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/BlockConverter.cpp new file mode 100644 index 0000000..a9f501b --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/BlockConverter.cpp @@ -0,0 +1,56 @@ + +#include "Conversion/Converters/BlockConverter.h" + +#include "Objects/Other/BlockInstance.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Engine/World.h" +#include "Objects/Other/RevitInstance.h" + +UBlockConverter::UBlockConverter() +{ + SpeckleTypes.Add(UBlockInstance::StaticClass()); + SpeckleTypes.Add(URevitInstance::StaticClass()); + + BlockInstanceActorType = AActor::StaticClass(); + ActorMobility = EComponentMobility::Static; +} + +UObject* UBlockConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface&) +{ + const UInstance* Block = Cast(SpeckleBase); + if(Block == nullptr) return nullptr; + + return BlockToNative(Block, World); +} + +AActor* UBlockConverter::BlockToNative(const UInstance* Block, UWorld* World) +{ + AActor* BlockActor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(Block->Transform)); + //Return the block actor as is, + //Other converter logic will convert child geometries because UBlockInstance intentionally left them as dynamic properties + return BlockActor; +} + +AActor* UBlockConverter::CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters) +{ + AActor* Actor = World->SpawnActor(BlockInstanceActorType, Transform, SpawnParameters); + + if(!Actor->HasValidRootComponent()) + { + USceneComponent* Scene = NewObject(Actor, "Root"); + Scene->SetRelativeTransform(Transform); + Actor->SetRootComponent(Scene); + Scene->RegisterComponent(); + } + USceneComponent* RootComponent = Actor->GetRootComponent(); + + RootComponent->SetMobility(ActorMobility); + + return Actor; +} + +UBase* UBlockConverter::ConvertToSpeckle_Implementation(const UObject* Object) +{ + unimplemented(); + return nullptr; //TODO implement +} diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/CollectionConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/CollectionConverter.cpp new file mode 100644 index 0000000..6d0d02c --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/CollectionConverter.cpp @@ -0,0 +1,53 @@ + +#include "Conversion/Converters/CollectionConverter.h" + +#include "Objects/Collection.h" + +UCollectionConverter::UCollectionConverter() +{ + SpeckleTypes.Add(UCollection::StaticClass()); + + + ActorType = AActor::StaticClass(); + ActorMobility = EComponentMobility::Static; +} + +UObject* UCollectionConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, + TScriptInterface& AvailableConverters ) +{ + const UCollection* p = Cast(SpeckleBase); + + if(p == nullptr) return nullptr; + + return CollectionToNative(p, World); +} + +AActor* UCollectionConverter::CollectionToNative(const UCollection*, UWorld* World) +{ + AActor* MeshActor = CreateEmptyActor(World); + + + return MeshActor; +} + +AActor* UCollectionConverter::CreateEmptyActor(UWorld* World, const FActorSpawnParameters& SpawnParameters) +{ + AActor* Actor = World->SpawnActor(ActorType, SpawnParameters); + USceneComponent* Scene = NewObject(Actor, "Root"); + Actor->SetRootComponent(Scene); + Scene->RegisterComponent(); + Scene->SetMobility(ActorMobility); + return Actor; +} + + +UBase* UCollectionConverter::ConvertToSpeckle_Implementation(const UObject* Object) +{ + return nullptr; //TODO implement ToSpeckle function +} + + +UCollection* UCollectionConverter::CollectionToSpeckle(const AActor* Object) +{ + return nullptr; //TODO implement ToSpeckle function +} diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/MaterialConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/MaterialConverter.cpp new file mode 100644 index 0000000..fa64510 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/MaterialConverter.cpp @@ -0,0 +1,180 @@ + +#include "Conversion/Converters/MaterialConverter.h" + +#include "AssetRegistry/AssetRegistryModule.h" +#include "Materials/MaterialInstanceConstant.h" +#include "Materials/MaterialInstanceDynamic.h" +#include "Objects/Other/RenderMaterial.h" +#include "UObject/ConstructorHelpers.h" +#include "Materials/MaterialInterface.h" +#include "Misc/Paths.h" +#include "UObject/Package.h" + + +UMaterialConverter::UMaterialConverter() +{ + static ConstructorHelpers::FObjectFinder SpeckleMaterial(TEXT("Material'/SpeckleUnreal/SpeckleMaterial.SpeckleMaterial'")); + static ConstructorHelpers::FObjectFinder SpeckleGlassMaterial(TEXT("Material'/SpeckleUnreal/SpeckleGlassMaterial.SpeckleGlassMaterial'")); + + DefaultMeshMaterial = SpeckleMaterial.Object; + BaseMeshOpaqueMaterial = SpeckleMaterial.Object; + BaseMeshTransparentMaterial = SpeckleGlassMaterial.Object; + +#if WITH_EDITORONLY_DATA + UseConstMaterials = NotPlay; +#endif + + SpeckleTypes.Add(URenderMaterial::StaticClass()); +} + +UObject* UMaterialConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld*, TScriptInterface&) +{ + const URenderMaterial* m = Cast(SpeckleBase); + + if(m == nullptr) return DefaultMeshMaterial; + + return GetMaterial(m); +} + +UMaterialInterface* UMaterialConverter::GetMaterial(const URenderMaterial* SpeckleMaterial) +{ + if(SpeckleMaterial == nullptr || SpeckleMaterial->Id == "") return DefaultMeshMaterial; //Material is invalid + + // 1. Check Overrides + UMaterialInterface* NativeMaterial; + if(TryGetOverride(SpeckleMaterial, NativeMaterial)) + return NativeMaterial; + + // 2. Check transient cache + if(ConvertedMaterials.Contains(SpeckleMaterial->Id)) + { + return ConvertedMaterials[SpeckleMaterial->Id]; + } + + // 3. Check Assets + UPackage* Package = GetPackage(SpeckleMaterial->Id); + + NativeMaterial = Cast(Package->FindAssetInPackage()); + if(IsValid(NativeMaterial)) + { + return NativeMaterial; + } + + // 4. Convert + return RenderMaterialToNative(SpeckleMaterial, Package); +} + +bool UMaterialConverter::TryGetOverride(const URenderMaterial* SpeckleMaterial, UMaterialInterface*& OutMaterial) const +{ + const auto MaterialID = SpeckleMaterial->Id; + + + //Override by id + if(MaterialOverridesById.Contains(MaterialID)) + { + OutMaterial = MaterialOverridesById[MaterialID]; + return true; + } + //Override by name + const FString Name = SpeckleMaterial->Name; + for (const UMaterialInterface* Mat : MaterialOverridesByName) + { + if(ensureAlways(IsValid(Mat)) && Mat->GetName() == Name) + { + OutMaterial = *MaterialOverridesByName.Find(Mat); + return true; + } + } + + + return false; +} + +FString UMaterialConverter::RemoveInvalidFileChars(const FString& InString) const +{ + return FPaths::MakeValidFileName(InString.Replace(TEXT("."), TEXT("_"), ESearchCase::CaseSensitive)); +} + +UMaterialInterface* UMaterialConverter::RenderMaterialToNative(const URenderMaterial* SpeckleMaterial, UPackage* Package) +{ + UMaterialInterface* MaterialBase = SpeckleMaterial->Opacity >= 1 + ? BaseMeshOpaqueMaterial + : BaseMeshTransparentMaterial; + + UMaterialInstance* MaterialInstance; +#if WITH_EDITOR + if (ShouldCreateConstMaterial(UseConstMaterials)) + { + const FName Name = MakeUniqueObjectName(Package, UMaterialInstanceConstant::StaticClass(), *RemoveInvalidFileChars(SpeckleMaterial->Name)); + + //TStrongObjectPtr< UMaterialInstanceConstantFactoryNew > MaterialFact( NewObject< UMaterialInstanceConstantFactoryNew >() ); + //MaterialFact->InitialParent = MaterialBase; + //UMaterialInstanceConstant* ConstMaterial = Cast< UMaterialInstanceConstant >( MaterialFact->FactoryCreateNew( UMaterialInstanceConstant::StaticClass(), Package, Name, RF_Public, nullptr, GWarn ) ); + UMaterialInstanceConstant* ConstMaterial = NewObject(Package, Name, RF_Public | RF_Standalone); + + MaterialInstance = ConstMaterial; + ConstMaterial->SetParentEditorOnly(MaterialBase); + ConstMaterial->SetScalarParameterValueEditorOnly(FMaterialParameterInfo("Opacity"), SpeckleMaterial->Opacity); + ConstMaterial->SetScalarParameterValueEditorOnly(FMaterialParameterInfo("Metallic"), SpeckleMaterial->Metalness); + ConstMaterial->SetScalarParameterValueEditorOnly(FMaterialParameterInfo("Roughness"), SpeckleMaterial->Roughness); + ConstMaterial->SetVectorParameterValueEditorOnly(FMaterialParameterInfo("BaseColor"), SpeckleMaterial->Diffuse); + ConstMaterial->SetVectorParameterValueEditorOnly(FMaterialParameterInfo("EmissiveColor"), SpeckleMaterial->Emissive); + + //ConstMaterial->InitStaticPermutation(); + + ConstMaterial->MarkPackageDirty(); + + FAssetRegistryModule::AssetCreated(MaterialInstance); + } + else +#endif + { + UMaterialInstanceDynamic* DynMaterial = UMaterialInstanceDynamic::Create(MaterialBase, Package, FName(SpeckleMaterial->Name)); + MaterialInstance = DynMaterial; + + DynMaterial->SetScalarParameterValue("Opacity", SpeckleMaterial->Opacity); + DynMaterial->SetScalarParameterValue("Metallic", SpeckleMaterial->Metalness); + DynMaterial->SetScalarParameterValue("Roughness", SpeckleMaterial->Roughness); + DynMaterial->SetVectorParameterValue("BaseColor", SpeckleMaterial->Diffuse); + DynMaterial->SetVectorParameterValue("EmissiveColor", SpeckleMaterial->Emissive); + + DynMaterial->SetFlags(RF_Public); + } + + ConvertedMaterials.Add(SpeckleMaterial->Id, MaterialInstance); + + return MaterialInstance; + +} + +void UMaterialConverter::FinishConversion_Implementation() +{ + ConvertedMaterials.Empty(); +} + +UPackage* UMaterialConverter::GetPackage(const FString& ObjectID ) const +{ + const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle/Materials"), ObjectID); + return CreatePackage(*PackagePath); +} + + +#if WITH_EDITOR +bool UMaterialConverter::ShouldCreateConstMaterial(TEnumAsByte Options) +{ + if(!GIsEditor) return false; + + switch(Options) + { + case Never: + return false; + case NotPlay: + return !FApp::IsGame(); + case Always: + return true; + default: + unimplemented(); + return false; + } +} +#endif \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/PointCloudConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/PointCloudConverter.cpp new file mode 100644 index 0000000..8b8c199 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/PointCloudConverter.cpp @@ -0,0 +1,95 @@ + +#include "Conversion/Converters/PointCloudConverter.h" + +#include "LidarPointCloudActor.h" +#include "LidarPointCloudShared.h" +#include "LidarPointCloudComponent.h" +#include "Objects/Geometry/PointCloud.h" +#include "Engine/World.h" +#include "Runtime/Launch/Resources/Version.h" + +UPointCloudConverter::UPointCloudConverter() +{ + SpeckleTypes.Add(UPointCloud::StaticClass()); + + PointCloudActorType = ALidarPointCloudActor::StaticClass(); + ActorMobility = EComponentMobility::Static; +} + + +UObject* UPointCloudConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface&) +{ + const UPointCloud* p = Cast(SpeckleBase); + + if(p == nullptr) return nullptr; + + return PointCloudToNative(p, World); +} + + +ALidarPointCloudActor* UPointCloudConverter::PointCloudToNative(const UPointCloud* SpecklePointCloud, UWorld* World) +{ + TArray LidarPoints; + + LidarPoints.Reserve(SpecklePointCloud->Points.Num()); + + for(int i = 0; i < SpecklePointCloud->Points.Num(); i++) + { + FColor c = SpecklePointCloud->Colors.Num() > i? SpecklePointCloud->Colors[i] : FColor::White; +#if ENGINE_MAJOR_VERSION >= 5 + FVector3f Point = FVector3f(SpecklePointCloud->Points[i]); +#else + FVector Point = SpecklePointCloud->Points[i]; +#endif + + FLidarPointCloudPoint p(Point, c, true, 0); + LidarPoints.Add(p); + } + + ULidarPointCloud* PointCloud = NewObject(); + + PointCloud->Initialize(FBox(SpecklePointCloud->Points)); + + PointCloud->InsertPoints(LidarPoints, ELidarPointCloudDuplicateHandling::Ignore, false, FVector::ZeroVector); + + PointCloud->CenterPoints(); + PointCloud->RefreshBounds(); + + return CreateActor(World, PointCloud); + +} + + +ALidarPointCloudActor* UPointCloudConverter::CreateActor(UWorld* World, ULidarPointCloud* PointCloudData) +{ + ALidarPointCloudActor* Actor = World->SpawnActor(PointCloudActorType); + Actor->SetPointCloud(PointCloudData); + Actor->GetRootComponent()->SetMobility(ActorMobility); + return Actor; +} + + +UBase* UPointCloudConverter::ConvertToSpeckle_Implementation(const UObject* Object) +{ + const ULidarPointCloudComponent* P = Cast(Object); + + if(P == nullptr) + { + const AActor* A = Cast(Object); + if(A != nullptr) + { + P = A->FindComponentByClass(); + } + } + if(P == nullptr) return nullptr; + + return PointCloudToSpeckle(P); +} + + +UPointCloud* UPointCloudConverter::PointCloudToSpeckle(const ULidarPointCloudComponent* Object) +{ + return nullptr; //TODO implement ToSpeckle function +} + + diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/ProceduralMeshConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/ProceduralMeshConverter.cpp new file mode 100644 index 0000000..2d746c2 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/ProceduralMeshConverter.cpp @@ -0,0 +1,144 @@ + +#include "Conversion/Converters/ProceduralMeshConverter.h" + +#include "ProceduralMeshComponent.h" +#include "Conversion/Converters/MaterialConverter.h" +#include "Materials/MaterialInstance.h" +#include "Objects/DisplayValueElement.h" +#include "Objects/Geometry/Mesh.h" +#include "Objects/Other/RenderMaterial.h" +#include "Objects/Utils/SpeckleObjectUtils.h" + +UProceduralMeshConverter::UProceduralMeshConverter() +{ + SpeckleTypes.Add(UMesh::StaticClass()); + SpeckleTypes.Add(UDisplayValueElement::StaticClass()); + + MeshActorType = AActor::StaticClass(); + ActorMobility = EComponentMobility::Static; +} + +UObject* UProceduralMeshConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, + TScriptInterface& AvailableConverters ) +{ + const UMesh* m = Cast(SpeckleBase); + if(m != nullptr) + return MeshToNative(m, World, AvailableConverters); + + const UDisplayValueElement* d = Cast(SpeckleBase); + if(d) + { + AActor* Parent = CreateEmptyActor(World, FTransform()); + for(const UMesh* Child : d->DisplayValue) + { + AActor* ChildActor = MeshToNative(Child, World, AvailableConverters); + if(IsValid(ChildActor)) + { +#if WITH_EDITOR + ChildActor->SetActorLabel(FString::Printf(TEXT("%s - %s"), *Child->SpeckleType, *Child->Id)); +#endif + ChildActor->GetRootComponent()->SetMobility(ActorMobility); + ChildActor->AttachToActor(Parent, FAttachmentTransformRules::KeepRelativeTransform); + ChildActor->SetOwner(Parent); + } + } + return Parent; + } + return nullptr; +} + +AActor* UProceduralMeshConverter::MeshToNative(const UMesh* SpeckleMesh, + UWorld* World, + TScriptInterface& MaterialConverter) +{ + AActor* MeshActor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(SpeckleMesh->Transform)); + UProceduralMeshComponent* MeshComponent = NewObject(MeshActor, FName("SpeckleMeshComponent")); + MeshComponent->SetupAttachment(MeshActor->GetRootComponent()); + MeshComponent->RegisterComponent(); + + TArray Faces; + + int32 i = 0; + while (i < SpeckleMesh->Faces.Num()) + { + int32 n = SpeckleMesh->Faces[i]; + if(n < 3) n += 3; // 0 -> 3, 1 -> 4 + + if (n == 3) //Triangles + { + Faces.Add(SpeckleMesh->Faces[i + 1]); + Faces.Add(SpeckleMesh->Faces[i + 2]); + Faces.Add(SpeckleMesh->Faces[i + 3]); + } + else if(n == 4) // Quads + { + Faces.Add(SpeckleMesh->Faces[i + 1]); + Faces.Add(SpeckleMesh->Faces[i + 3]); + Faces.Add(SpeckleMesh->Faces[i + 4]); + + Faces.Add(SpeckleMesh->Faces[i + 1]); + Faces.Add(SpeckleMesh->Faces[i + 2]); + Faces.Add(SpeckleMesh->Faces[i + 3]); + } + else + { + // n-gons shall be ignored + } + + i += n + 1; + } + + const TArray Normals; + const TArray Tangents; + + MeshComponent->CreateMeshSection( + 0, + SpeckleMesh->Vertices, + Faces, + Normals, + SpeckleMesh->TextureCoordinates, + SpeckleMesh->VertexColors, + Tangents, + true); + + UMaterialInterface* Material = Cast(Execute_ConvertToNative(MaterialConverter.GetObject(), SpeckleMesh->RenderMaterial, World, MaterialConverter)); + ensure(Material != nullptr); + + MeshComponent->SetMaterial(0, Material); + + return MeshActor; +} + +AActor* UProceduralMeshConverter::CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters) +{ + AActor* Actor = World->SpawnActor(MeshActorType, Transform, SpawnParameters); + USceneComponent* Scene = NewObject(Actor, "Root"); + Actor->SetRootComponent(Scene); + Scene->RegisterComponent(); + Scene->SetMobility(ActorMobility); + return Actor; +} + + +UBase* UProceduralMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object) +{ + const UProceduralMeshComponent* M = Cast(Object); + + if(M == nullptr) + { + const AActor* A = Cast(Object); + if(A != nullptr) + { + M = A->FindComponentByClass(); + } + } + if(M == nullptr) return nullptr; + + return MeshToSpeckle(M); +} + + +UMesh* UProceduralMeshConverter::MeshToSpeckle(const UProceduralMeshComponent* Object) +{ + return nullptr; //TODO implement ToSpeckle function +} diff --git a/Source/SpeckleUnreal/Private/Conversion/Converters/StaticMeshConverter.cpp b/Source/SpeckleUnreal/Private/Conversion/Converters/StaticMeshConverter.cpp new file mode 100644 index 0000000..3d264b9 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/Converters/StaticMeshConverter.cpp @@ -0,0 +1,440 @@ + +#include "Conversion/Converters/StaticMeshConverter.h" + +#include "MeshDescriptionBase.h" +#include "StaticMeshDescription.h" +#include "MeshTypes.h" +#include "StaticMeshOperations.h" +#include "AssetRegistry/AssetRegistryModule.h" +#include "Engine/StaticMeshActor.h" +#include "Objects/Geometry/Mesh.h" +#include "LogSpeckle.h" +#include "API/SpeckleSerializer.h" +#include "Conversion/Converters/MaterialConverter.h" +#include "Misc/ScopedSlowTask.h" +#include "Objects/DisplayValueElement.h" +#include "Objects/Other/RenderMaterial.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Components/StaticMeshComponent.h" +#include "Misc/Paths.h" +#include "UObject/Package.h" +#include "Materials/MaterialInterface.h" + +#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule" + +UStaticMeshConverter::UStaticMeshConverter() +{ + SpeckleTypes.Add(UMesh::StaticClass()); + SpeckleTypes.Add(UDisplayValueElement::StaticClass()); + + HiddenTypes.Add("Objects.BuiltElements.Room"); + +#if WITH_EDITORONLY_DATA + UseFullBuild = true; + DisplayBuildProgressBar = true; + AllowCancelBuild = false; +#endif + Transient = false; + BuildSimpleCollision = true; + + BuildReversedIndexBuffer = true; + UseFullPrecisionUVs = false; + RemoveDegeneratesOnBuild = true; + MinLightmapResolution = 64; + + MeshActorType = AStaticMeshActor::StaticClass(); + ActorMobility = EComponentMobility::Static; +} + +AActor* UStaticMeshConverter::CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters) +{ + AActor* Actor = World->SpawnActor(MeshActorType, Transform, SpawnParameters); + if(Actor->HasValidRootComponent()) + Actor->GetRootComponent()->SetMobility(EComponentMobility::Movable); //Create actor as movable for now, we will change it later to the desired mobility + return Actor; +} + +UObject* UStaticMeshConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface& AvailableConverters) +{ + const UMesh* m = Cast(SpeckleBase); + if(m != nullptr) + { + //Handle Single Mesh + return MeshToNativeActor(m, World, AvailableConverters); + } + + const UDisplayValueElement* d = Cast(SpeckleBase); + if(d != nullptr) + { + //Handle Element with Display Values + return MeshesToNativeActor(d, d->DisplayValue, World, AvailableConverters); + } + + return nullptr; +} + + +AActor* UStaticMeshConverter::MeshToNativeActor(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface& MaterialConverter) +{ + TArray Meshes = {const_cast(SpeckleMesh)}; + return MeshesToNativeActor(SpeckleMesh, Meshes, World, MaterialConverter); +} + +AActor* UStaticMeshConverter::MeshesToNativeActor(const UBase* Parent, const TArray& SpeckleMeshes, UWorld* World, TScriptInterface& RenderMaterialConverter) +{ + check(RenderMaterialConverter.GetInterface() != nullptr); + ensureMsgf(Execute_CanConvertToNative(RenderMaterialConverter.GetObject(), URenderMaterial::StaticClass()), TEXT("StaticMeshConverter expects a valid RenderMaterial converter to be avaiable")); + + + const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle/Geometry"), Parent->Id); + UPackage* Package = CreatePackage(*PackagePath); + + //Find existing mesh + UStaticMesh* Mesh = Cast(Package->FindAssetInPackage()); + + if(!IsValid(Mesh)) + { + //No existing mesh was found, try and convert SpeckleMesh + Mesh = MeshesToNativeMesh(Package, Parent, SpeckleMeshes, RenderMaterialConverter); + } + + FMatrix Transform = FMatrix::Identity; + // For single mesh, we check for transform + //TODO figure out how to handle DisplayValueElement with transform. Maybe we just grab transform from parent unconditionally? How does this affect blocks? + // if(Parent == SpeckleMeshes[0]) + // { + // Transform = SpeckleMeshes[0]->Transform; + // } + + AActor* Actor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(Transform)); + TInlineComponentArray Components; + Actor->GetComponents(Components); + + UStaticMeshComponent* MeshComponent; + if(Components.Num() > 0) MeshComponent = Components[0]; + else + { + // MeshActorType doesn't have a UStaticMeshComponent, so we will add one + MeshComponent = NewObject(Actor, FName("SpeckleMeshComponent")); + MeshComponent->SetupAttachment(Actor->GetRootComponent()); + MeshComponent->RegisterComponent(); + } + + MeshComponent->SetStaticMesh(Mesh); + + for(const FString& t: HiddenTypes) + { + if(Parent->SpeckleType.Contains(t)) + { + MeshComponent->SetVisibility(false); + break; + } + } + + int i = 0; + for(const UMesh* DisplayMesh : SpeckleMeshes) + { + URenderMaterial* MaterialToConvert = DisplayMesh->RenderMaterial; + if(!MaterialToConvert) + { + //Try and grab a material from the parent + const auto* MaterialProperty = Parent->DynamicProperties.Find("renderMaterial"); + const TSharedPtr* MaterialObject; + if(MaterialProperty && (*MaterialProperty)->TryGetObject(MaterialObject)) + { + //TODO giving a nullptr transport is pretty unsafe and relies on the deserializer not to have to dereference a detached property. + MaterialToConvert = Cast(USpeckleSerializer::DeserializeBase(*MaterialObject, nullptr)); + } + } + UMaterialInterface* Material = GetMaterial(MaterialToConvert, World, RenderMaterialConverter); + + ensure(IsValid(Material)); + MeshComponent->SetMaterial(i, Material); + + i++; + } + + if(Actor->HasValidRootComponent()) + Actor->GetRootComponent()->SetMobility(ActorMobility); + + return Actor; +} + + +UMaterialInterface* UStaticMeshConverter::GetMaterial(const URenderMaterial* SpeckleMaterial, UWorld* World, TScriptInterface& MaterialConverter) const +{ + if(!SpeckleMaterial) + { + // Create a fake render material, (since nullptr doesn't have a type, speckle converters don't know how to convert it) + // If the converter wants to handle this specially, The material has an empty Id + SpeckleMaterial = NewObject(GetTransientPackage(), "NullSpeckleMaterial"); + } + return Cast(Execute_ConvertToNative(MaterialConverter.GetObject(), SpeckleMaterial, World, MaterialConverter)); +} + + +UStaticMesh* UStaticMeshConverter::MeshToNativeMesh(UObject* Outer, const UMesh* SpeckleMesh, TScriptInterface& MaterialConverter) +{ + TArray Meshes; + Meshes.Add(const_cast(SpeckleMesh)); + return MeshesToNativeMesh(Outer, SpeckleMesh, Meshes, MaterialConverter); +} + + +UStaticMesh* UStaticMeshConverter::MeshesToNativeMesh(UObject* Outer, const UBase* Parent, const TArray& SpeckleMeshes, TScriptInterface& MaterialConverter) +{ + if(SpeckleMeshes.Num() == 0) return nullptr; + + EObjectFlags ObjectFags = Transient? RF_Transient | RF_Public : RF_Public; + +#if ENGINE_MAJOR_VERSION >= 5 + ObjectFags |= RF_Standalone; //TODO maybe all versions should have RF_Standalone? +#endif + + UStaticMesh* Mesh = NewObject(Outer, FName(Parent->Id), ObjectFags); + + Mesh->InitResources(); + Mesh->SetLightingGuid(); + + UStaticMeshDescription* StaticMeshDescription = Mesh->CreateStaticMeshDescription(Outer); + FMeshDescription& BaseMeshDescription = StaticMeshDescription->GetMeshDescription(); + + //Build Settings +#if WITH_EDITOR + { + FStaticMeshSourceModel& SrcModel = Mesh->AddSourceModel(); + SrcModel.BuildSettings.bRecomputeNormals = true; + SrcModel.BuildSettings.bRecomputeTangents = true; + SrcModel.BuildSettings.bRemoveDegenerates = RemoveDegeneratesOnBuild; + SrcModel.BuildSettings.bUseHighPrecisionTangentBasis = false; + SrcModel.BuildSettings.bBuildReversedIndexBuffer = BuildReversedIndexBuffer; + SrcModel.BuildSettings.bUseFullPrecisionUVs = UseFullPrecisionUVs; + SrcModel.BuildSettings.bGenerateLightmapUVs = GenerateLightmapUV; + SrcModel.BuildSettings.SrcLightmapIndex = 0; + SrcModel.BuildSettings.DstLightmapIndex = 1; + SrcModel.BuildSettings.MinLightmapResolution = MinLightmapResolution; + } +#endif + + UStaticMesh::FBuildMeshDescriptionsParams MeshParams; + GenerateMeshParams(MeshParams); + + for(const UMesh* SpeckleMesh : SpeckleMeshes) + { + const size_t NumberOfVertices = SpeckleMesh->Vertices.Num(); + const size_t NumberOfFacesIndices = SpeckleMesh->Faces.Num(); + + // Convert Vertices + if(NumberOfVertices == 0 || NumberOfFacesIndices == 0) continue; + + StaticMeshDescription->ReserveNewVertices(NumberOfVertices); + + TArray Vertices; + Vertices.Reserve(NumberOfVertices); + + for(const FVector VertexPosition : SpeckleMesh->Vertices) + { + const FVertexID VertID = StaticMeshDescription->CreateVertex(); + StaticMeshDescription->SetVertexPosition(VertID, VertexPosition); + Vertices.Add(VertID); + } + + // Convert Material + UMaterialInterface* Material = GetMaterial(SpeckleMesh->RenderMaterial, GetWorld(), MaterialConverter); + + const FName MaterialSlotName = Mesh->AddMaterial(Material);; + BaseMeshDescription.PolygonGroupAttributes().RegisterAttribute(MeshAttribute::PolygonGroup::ImportedMaterialSlotName, 1, MaterialSlotName, EMeshAttributeFlags::None); + + // Convert Faces + const FPolygonGroupID PolygonGroupID = StaticMeshDescription->CreatePolygonGroup(); + + StaticMeshDescription->SetPolygonGroupMaterialSlotName(PolygonGroupID, MaterialSlotName); + +#if ENGINE_MAJOR_VERSION >= 5 + StaticMeshDescription->VertexInstanceAttributes().RegisterAttribute(MeshAttribute::VertexInstance::TextureCoordinate, 2, FVector2f::ZeroVector, EMeshAttributeFlags::None); +#else + StaticMeshDescription->VertexInstanceAttributes().RegisterAttribute(MeshAttribute::VertexInstance::TextureCoordinate, 2, FVector2D::ZeroVector, EMeshAttributeFlags::None); +#endif + { + // Reserve space assuming faces will all be triangles //TODO (maybe it's better to assume something higher?) + const int32 EstimatedNumberOfFaces = SpeckleMesh->Faces.Num() / 4 * 3; + StaticMeshDescription->ReserveNewTriangles(EstimatedNumberOfFaces); + StaticMeshDescription->ReserveNewPolygons(EstimatedNumberOfFaces); + StaticMeshDescription->ReserveNewVertexInstances(FGenericPlatformMath::Max(EstimatedNumberOfFaces * 3, SpeckleMesh->Vertices.Num())); + } + + int32 i = 0; + while (i < NumberOfFacesIndices) + { + int32 n = SpeckleMesh->Faces[i]; + if(n < 3) n += 3; // 0 -> 3, 1 -> 4 + + TArray VertexInstances; + VertexInstances.Reserve(n); + TSet Verts; + Verts.Reserve(n); + for(int j = 0; j < n; j ++) + { + int32 VertIndex = SpeckleMesh->Faces[i + 1 + j]; + + if(VertIndex < 0 || VertIndex >= Vertices.Num()) + { + UE_LOG(LogSpeckle, Warning, TEXT("Invalid Polygon while creating mesh %s - index %d was outside the bounds of the vertex array, face is ignored"), *SpeckleMesh->Id, VertIndex); + continue; + } + + FVertexID Vert = Vertices[VertIndex]; + bool AlreadyInSet; + Verts.Add(Vert, &AlreadyInSet); + + if(AlreadyInSet) + { + UE_LOG(LogSpeckle, Warning, TEXT("Invalid Polygon while creating mesh %s - vertex at index %d appears more than once in a face, duplicate vertices will be ignored"), *SpeckleMesh->Id, VertIndex); + continue; + } + FVertexInstanceID VertexInstance = StaticMeshDescription->CreateVertexInstance(Vert); + + VertexInstances.Add(VertexInstance); + + if(SpeckleMesh->TextureCoordinates.Num() > VertIndex) + StaticMeshDescription->SetVertexInstanceUV(VertexInstance, SpeckleMesh->TextureCoordinates[VertIndex]); + + //if(SpeckleMesh->VertexColors.Num() > VertIndex) + // //TODO set vertex colors + } + + i += n + 1; + if(VertexInstances.Num() < 3) + { + UE_LOG(LogTemp, Warning, TEXT("Invalid Polygon while creating mesh %s - face has fewer than 3 verts, this face will be ignored"), *SpeckleMesh->Id); + continue; + } + + + TArray Edges; + Edges.Reserve(n); + + const FPolygonID PolygonID = StaticMeshDescription->CreatePolygon(PolygonGroupID, VertexInstances, Edges); + + for (const FEdgeID EdgeID : Edges) + { + StaticMeshDescription->GetEdgeHardnesses()[EdgeID] = true; + } + } + } + + if(StaticMeshDescription->Vertices().Num() == 0 + || StaticMeshDescription->VertexInstances().Num() == 0 + || StaticMeshDescription->Triangles().Num() == 0) + { + UE_LOG(LogSpeckle, Warning, TEXT("Skipping %s $s, converted mesh is empty!"), *Parent->SpeckleType, *Parent->Id); + return nullptr; + } + + BaseMeshDescription.TriangulateMesh(); + +#if ENGINE_MAJOR_VERSION >= 5 + FStaticMeshOperations::ComputeTriangleTangentsAndNormals(BaseMeshDescription); +#else + BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Normal, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); + BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Tangent, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); + BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Binormal, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); + BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Center, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); + FStaticMeshOperations::ComputePolygonTangentsAndNormals(BaseMeshDescription); +#endif + + FStaticMeshOperations::ComputeTangentsAndNormals(BaseMeshDescription, EComputeNTBsFlags::Normals | EComputeNTBsFlags::Tangents); + + + //Mesh->PreEditChange(nullptr); + +#if ENGINE_MAJOR_VERSION >= 5 || ( ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 27 ) + Mesh->SetLightMapCoordinateIndex(1); +#else + Mesh->LightMapCoordinateIndex = 1; +#endif + + Mesh->BuildFromMeshDescriptions(TArray{&BaseMeshDescription}, MeshParams); + +#if WITH_EDITOR + if(UseFullBuild) + { + FScopeLock Lock(&Lock_StaticMeshesToBuild); + StaticMeshesToBuild.Add(Mesh); + } + + if (!FApp::IsGame()) + { + Mesh->MarkPackageDirty(); + FAssetRegistryModule::AssetCreated(Mesh); + } +#endif + //Mesh->PostEditChange(); //This doesn't seem to be required + + return Mesh; +} + +void UStaticMeshConverter::GenerateMeshParams(UStaticMesh::FBuildMeshDescriptionsParams& MeshParams) const +{ + MeshParams.bBuildSimpleCollision = BuildSimpleCollision; + MeshParams.bCommitMeshDescription = true; + MeshParams.bMarkPackageDirty = true; + MeshParams.bUseHashAsGuid = false; + +#if !WITH_EDITOR && ENGINE_MAJOR_VERSION >= 5 + MeshParams.bFastBuild = true; +#endif +} + + +UBase* UStaticMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object) +{ + const UStaticMeshComponent* M = Cast(Object); + + if(M == nullptr) + { + const AActor* A = Cast(Object); + if(A != nullptr) + { + M = A->FindComponentByClass(); + } + } + if(M == nullptr) return nullptr; + + return MeshToSpeckle(M); +} + + +UBase* UStaticMeshConverter::MeshToSpeckle(const UStaticMeshComponent* Object) +{ + return nullptr; //TODO implement ToSpeckle function +} + + +void UStaticMeshConverter::FinishConversion_Implementation() +{ + if(StaticMeshesToBuild.Num() <= 0) return; + + FScopeLock Lock(&Lock_StaticMeshesToBuild); + +#if WITH_EDITOR + + FFormatNamedArguments Args; + Args.Add( TEXT("Path"), FText::FromString( GetPathName() ) ); + const FText StatusUpdate = FText::Format( LOCTEXT("BeginStaticMeshBuildingTask", "({Path}) Building"), Args ); + FScopedSlowTask Progress(StaticMeshesToBuild.Num(), StatusUpdate, DisplayBuildProgressBar); + + Progress.MakeDialog(AllowCancelBuild); + auto ProgressAction = [&Progress](UStaticMesh*) -> bool + { + Progress.EnterProgressFrame(1); + return !Progress.ShouldCancel(); + }; + + UStaticMesh::BatchBuild(StaticMeshesToBuild, !DisplayBuildProgressBar, ProgressAction); +#endif + + StaticMeshesToBuild.Empty(); +} + +#undef LOCTEXT_NAMESPACE \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/Conversion/SpeckleConverterComponent.cpp b/Source/SpeckleUnreal/Private/Conversion/SpeckleConverterComponent.cpp new file mode 100644 index 0000000..d687d24 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Conversion/SpeckleConverterComponent.cpp @@ -0,0 +1,198 @@ + +#include "Conversion/SpeckleConverterComponent.h" + +#include "ActorEditorUtils.h" +#include "API/SpeckleSerializer.h" +#include "Conversion/Converters/AggregateConverter.h" +#include "Conversion/Converters/BlockConverter.h" +#include "Conversion/Converters/CollectionConverter.h" +#include "Conversion/Converters/PointCloudConverter.h" +#include "Conversion/Converters/StaticMeshConverter.h" +#include "Conversion/Converters/MaterialConverter.h" +#include "Misc/ScopedSlowTask.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "UObject/ConstructorHelpers.h" +#include "Dom/JsonValue.h" + +#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule" + +USpeckleConverterComponent::USpeckleConverterComponent() +{ + //TODO consider using an object library for default converters + static ConstructorHelpers::FObjectFinder MeshConverter(TEXT("StaticMeshConverter'/SpeckleUnreal/Converters/DefaultStaticMeshConverter.DefaultStaticMeshConverter'")); + static ConstructorHelpers::FObjectFinder PointCloudConverter(TEXT("PointCloudConverter'/SpeckleUnreal/Converters/DefaultPointCloudConverter.DefaultPointCloudConverter'")); + static ConstructorHelpers::FObjectFinder BlockConverter(TEXT("BlockConverter'/SpeckleUnreal/Converters/DefaultBlockConverter.DefaultBlockConverter'")); + static ConstructorHelpers::FObjectFinder MaterialConverter(TEXT("MaterialConverter'/SpeckleUnreal/Converters/DefaultMaterialConverter.DefaultMaterialConverter'")); + static ConstructorHelpers::FObjectFinder CollectionConverter(TEXT("CollectionConverter'/SpeckleUnreal/Converters/DefaultCollectionConverter.DefaultCollectionConverter'")); + static ConstructorHelpers::FObjectFinder CameraConverter(TEXT("CameraConverter'/SpeckleUnreal/Converters/DefaultCameraConverter.DefaultCameraConverter'")); + //static ConstructorHelpers::FObjectFinder LightConverter(TEXT("LightConverter'/SpeckleUnreal/Converters/DefaultLightConverter.DefaultLightConverter'")); + + SpeckleConverter = CreateDefaultSubobject(TEXT("Objects Converter")); + + SpeckleConverter->SpeckleConverters.Add(MeshConverter.Object); + SpeckleConverter->SpeckleConverters.Add(PointCloudConverter.Object); + SpeckleConverter->SpeckleConverters.Add(BlockConverter.Object); + SpeckleConverter->SpeckleConverters.Add(MaterialConverter.Object); + SpeckleConverter->SpeckleConverters.Add(CollectionConverter.Object); + SpeckleConverter->SpeckleConverters.Add(CameraConverter.Object); + //SpeckleConverter->SpeckleConverters.Add(LightConverter.Object); + + PrimaryComponentTick.bCanEverTick = false; +} + +AActor* USpeckleConverterComponent::RecursivelyConvertToNative(AActor* AOwner, const UBase* Base, + const TScriptInterface& LocalTransport, bool DisplayProgressBar, TArray& OutActors) +{ + float ObjectsToConvert{}; + if(Base->TotalChildrenCount > 0) + { + ObjectsToConvert = Base->TotalChildrenCount; + } + else + { + Base->TryGetDynamicNumber("totalChildrenCount", ObjectsToConvert); + } + if(ObjectsToConvert <= 1) + { + ObjectsToConvert = 99999; //A large number + } + + // Progress bar + FScopedSlowTask Progress(ObjectsToConvert + 2, + LOCTEXT("SpeckleConvertoNative","Converting Speckle Objects to Native"), DisplayProgressBar); + +#if WITH_EDITOR + Progress.MakeDialog(true, false); +#endif + + AActor* RootActor = RecursivelyConvertToNative_Internal(AOwner, Base, LocalTransport, &Progress, OutActors); + + FinishConversion(); + return RootActor; +} + +AActor* USpeckleConverterComponent::RecursivelyConvertToNative_Internal(AActor* AOwner, const UBase* Base, + const TScriptInterface& LocalTransport, + FSlowTask* Task, + TArray& OutActors) +{ + check(IsValid(AOwner)); + if(!IsValid(Base)) return nullptr; + + // Convert Speckle Object + UObject* Converted = SpeckleConverter->ConvertToNativeInternal(Base, AOwner->GetWorld()); + AttachConvertedToOwner(AOwner, Base, Converted); + + // Handle new actors + AActor* ConvertedAsActor = Cast(Converted); + AActor* NextOwner = IsValid(ConvertedAsActor) ? ConvertedAsActor : AOwner; + if(NextOwner != AOwner) + { + OutActors.Add(NextOwner); + OutActors.Append(NextOwner->Children); + } + + Task->EnterProgressFrame(1); + if(Task->ShouldCancel()) return AOwner; + + //Convert Children + TMap> PotentialChildren = Base->DynamicProperties; + + for (const auto& Kvp : PotentialChildren) + { + if(Task->ShouldCancel()) break; + + ConvertChild(Kvp.Value, NextOwner, LocalTransport, Task, OutActors); + } + return AOwner; +} + +void USpeckleConverterComponent::ConvertChild(const TSharedPtr Object, AActor* AOwner, + const TScriptInterface& LocalTransport, FSlowTask* Task, + TArray& OutActors) +{ + //Handle child object + const TSharedPtr* ChildObj; + if (Object->TryGetObject(ChildObj)) + { + const UBase* Child = USpeckleSerializer::DeserializeBase(*ChildObj, LocalTransport); + RecursivelyConvertToNative_Internal(AOwner, Child, LocalTransport, Task, OutActors); + return; + } + + //Handle child array object + const TArray>* ChildArr; + if (Object->TryGetArray(ChildArr)) + { + for (const auto& v : *ChildArr) + { + ConvertChild(v, AOwner, LocalTransport, Task, OutActors); + } + } +}; + + +void USpeckleConverterComponent::AttachConvertedToOwner(AActor* AOwner, const UBase* Base, UObject* Converted) +{ + + // Case Actor + { + AActor* NativeActor = Cast(Converted); + if(IsValid(NativeActor)) + { + #if WITH_EDITOR + { + FString Name = USpeckleObjectUtils::GetFriendlyObjectName(Base); + FText NameErrors; + + if(!FActorEditorUtils::ValidateActorName(FText::FromString(Name), NameErrors)) + { + Name = USpeckleObjectUtils::GetBoringObjectName(Base); + } + + NativeActor->SetActorLabel(Name); + } + #endif + + // Ensure actor has a valid mobility for its owner + if(NativeActor->HasValidRootComponent()) + { + uint8 CurrentMobility = NativeActor->GetRootComponent()->Mobility; + uint8 OwnerMobility = AOwner->GetRootComponent()->Mobility; + + if(CurrentMobility < OwnerMobility) + { + NativeActor->GetRootComponent()->SetMobility(AOwner->GetRootComponent()->Mobility); + } + } + + NativeActor->AttachToActor(AOwner, FAttachmentTransformRules::KeepRelativeTransform); + NativeActor->SetOwner(AOwner); + return; + } + } + + // Case ActorComponent + { + UActorComponent* NativeComponent = Cast(Converted); + if(IsValid(NativeComponent)) + { + if(!AOwner->HasValidRootComponent()) AOwner->SetRootComponent(NewObject(AOwner)); + + USceneComponent* SceneComponent = Cast(Converted); + if(IsValid(SceneComponent)) SceneComponent->SetupAttachment(AOwner->GetRootComponent()); + + NativeComponent->RegisterComponent(); + return; + } + } + +} + + +void USpeckleConverterComponent::FinishConversion() +{ + SpeckleConverter->FinishConversion_Internal(); +} + +#undef LOCTEXT_NAMESPACE \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/LogSpeckle.cpp b/Source/SpeckleUnreal/Private/LogSpeckle.cpp new file mode 100644 index 0000000..3b7ab81 --- /dev/null +++ b/Source/SpeckleUnreal/Private/LogSpeckle.cpp @@ -0,0 +1,5 @@ + +#include "LogSpeckle.h" +#include "Logging/LogMacros.h" + +DEFINE_LOG_CATEGORY(LogSpeckle); diff --git a/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealPointCloud.cpp b/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealPointCloud.cpp deleted file mode 100644 index 9476557..0000000 --- a/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealPointCloud.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - - -#include "NativeActors/SpeckleUnrealPointCloud.h" - -#include "LidarPointCloudComponent.h" -#include "Objects/PointCloud.h" - -// Sets default values -ASpeckleUnrealPointCloud::ASpeckleUnrealPointCloud() : ALidarPointCloudActor() -{ - PrimaryActorTick.bCanEverTick = false; - - RootComponent = CreateDefaultSubobject("Root");; - RootComponent->SetMobility(EComponentMobility::Static); -} - -void ASpeckleUnrealPointCloud::SetData_Implementation(const UPointCloud* SpecklePointCloud, ASpeckleUnrealManager* Manager) -{ - TArray LidarPoints; - - LidarPoints.Reserve(SpecklePointCloud->Points.Num()); - - for(int i = 0; i < SpecklePointCloud->Points.Num(); i++) - { - FColor c = SpecklePointCloud->Colors.Num() > i? SpecklePointCloud->Colors[i] : FColor::White; - FLidarPointCloudPoint p = FLidarPointCloudPoint(SpecklePointCloud->Points[i], c, true, 0); - LidarPoints.Add(p); - } - - ULidarPointCloud* PointCloud = NewObject(); - - PointCloud->Initialize(FBox(SpecklePointCloud->Points)); - - PointCloud->InsertPoints(LidarPoints, ELidarPointCloudDuplicateHandling::Ignore, false, FVector::ZeroVector); - - PointCloud->CenterPoints(); - PointCloud->RefreshBounds(); - - this->SetPointCloud(PointCloud); -} - diff --git a/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealProceduralMesh.cpp b/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealProceduralMesh.cpp deleted file mode 100644 index 8cda636..0000000 --- a/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealProceduralMesh.cpp +++ /dev/null @@ -1,103 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#include "NativeActors/SpeckleUnrealProceduralMesh.h" - -#include "StaticMeshDescription.h" -#include "SpeckleUnrealManager.h" -#include "AssetRegistry/AssetRegistryModule.h" -#include "Objects/Mesh.h" -#include "Objects/RenderMaterial.h" - - -// Sets default values -ASpeckleUnrealProceduralMesh::ASpeckleUnrealProceduralMesh() : ASpeckleUnrealActor() -{ - MeshComponent = CreateDefaultSubobject(FName("SpeckleMeshComponent")); - MeshComponent->SetupAttachment(RootComponent); -} - -void ASpeckleUnrealProceduralMesh::SetMesh_Implementation(const UMesh* SpeckleMesh, ASpeckleUnrealManager* Manager) -{ - MeshComponent->ClearAllMeshSections(); - - TArray Faces; - - int32 i = 0; - while (i < SpeckleMesh->Faces.Num()) - { - int32 n = SpeckleMesh->Faces[i]; - if(n < 3) n += 3; // 0 -> 3, 1 -> 4 - - if (n == 3) //Triangles - { - Faces.Add(SpeckleMesh->Faces[i + 3]); - Faces.Add(SpeckleMesh->Faces[i + 2]); - Faces.Add(SpeckleMesh->Faces[i + 1]); - } - else if(n == 4) // Quads - { - Faces.Add(SpeckleMesh->Faces[i + 4]); - Faces.Add(SpeckleMesh->Faces[i + 3]); - Faces.Add(SpeckleMesh->Faces[i + 1]); - - Faces.Add(SpeckleMesh->Faces[i + 3]); - Faces.Add(SpeckleMesh->Faces[i + 2]); - Faces.Add(SpeckleMesh->Faces[i + 1]); - } - else - { - // n-gons shall be ignored - } - - i += n + 1; - } - - const TArray Normals; - const TArray Tangents; - - MeshComponent->CreateMeshSection( - 0, - SpeckleMesh->Vertices, - Faces, - Normals, - SpeckleMesh->TextureCoordinates, - SpeckleMesh->VertexColors, - Tangents, - true); - - MeshComponent->SetMaterial(0, GetMaterial(SpeckleMesh->RenderMaterial, Manager)); -} - -UMaterialInterface* ASpeckleUnrealProceduralMesh::GetMaterial(const URenderMaterial* SpeckleMaterial, ASpeckleUnrealManager* Manager) -{ - UMaterialInterface* ExistingMaterial; - if(Manager->TryGetMaterial(SpeckleMaterial, true, ExistingMaterial)) - return ExistingMaterial; //Return existing material - - UMaterialInterface* MaterialBase = SpeckleMaterial->Opacity >= 1 - ? Manager->BaseMeshOpaqueMaterial - : Manager->BaseMeshTransparentMaterial; - - const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle"), Manager->StreamID, TEXT("Materials"), SpeckleMaterial->Id); - UPackage* Package = CreatePackage(*PackagePath); - - UMaterialInstanceDynamic* DynMaterial = UMaterialInstanceDynamic::Create(MaterialBase, Package, FName(SpeckleMaterial->Name)); - - DynMaterial->SetFlags(RF_Public); - - DynMaterial->SetScalarParameterValue("Opacity", SpeckleMaterial->Opacity); - DynMaterial->SetScalarParameterValue("Metallic", SpeckleMaterial->Metalness); - DynMaterial->SetScalarParameterValue("Roughness", SpeckleMaterial->Roughness); - DynMaterial->SetVectorParameterValue("BaseColor", SpeckleMaterial->Diffuse); - DynMaterial->SetVectorParameterValue("EmissiveColor", SpeckleMaterial->Emissive); - - Manager->ConvertedMaterials.Add(SpeckleMaterial->Id, DynMaterial); - - if (GetWorld()->WorldType == EWorldType::PIE) - { - FAssetRegistryModule::AssetCreated(DynMaterial); - } - - return DynMaterial; - -} \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealStaticMesh.cpp b/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealStaticMesh.cpp deleted file mode 100644 index 0da2575..0000000 --- a/Source/SpeckleUnreal/Private/NativeActors/SpeckleUnrealStaticMesh.cpp +++ /dev/null @@ -1,216 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#include "NativeActors/SpeckleUnrealStaticMesh.h" - -#include "MeshDescriptionBase.h" -#include "StaticMeshDescription.h" -#include "MeshTypes.h" -#include "SpeckleUnrealManager.h" -#include "StaticMeshOperations.h" -#include "AssetRegistry/AssetRegistryModule.h" -#include "Materials/MaterialInstanceConstant.h" -#include "Objects/RenderMaterial.h" - - -ASpeckleUnrealStaticMesh::ASpeckleUnrealStaticMesh() : ASpeckleUnrealActor() -{ - MeshComponent = NewObject(RootComponent, FName("SpeckleMeshComponent"), RF_Public); - MeshComponent->SetMobility(EComponentMobility::Stationary); - MeshComponent->SetupAttachment(RootComponent); - - Transient = false; - UseFullBuild = true; - BuildSimpleCollision = true; -} - -void ASpeckleUnrealStaticMesh::SetMesh_Implementation(const UMesh* SpeckleMesh, ASpeckleUnrealManager* Manager) -{ - - //Create Mesh Asset - const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle"), Manager->StreamID, TEXT("Geometry"),SpeckleMesh->Id); - UPackage* Package = CreatePackage(*PackagePath); - - const EObjectFlags ObjectFags = Transient? RF_Transient | RF_Public : RF_Public; - - UStaticMesh* Mesh = NewObject(Package, FName(SpeckleMesh->Id), ObjectFags); - - Mesh->InitResources(); - Mesh->SetLightingGuid(); - - UStaticMeshDescription* StaticMeshDescription = Mesh->CreateStaticMeshDescription(RootComponent); - FMeshDescription& BaseMeshDescription = StaticMeshDescription->GetMeshDescription(); - - //Build Settings -#if WITH_EDITOR - { - FStaticMeshSourceModel& SrcModel = Mesh->AddSourceModel(); - SrcModel.BuildSettings.bRecomputeNormals = false; - SrcModel.BuildSettings.bRecomputeTangents = false; - SrcModel.BuildSettings.bRemoveDegenerates = false; - SrcModel.BuildSettings.bUseHighPrecisionTangentBasis = false; - SrcModel.BuildSettings.bUseFullPrecisionUVs = false; - SrcModel.BuildSettings.bGenerateLightmapUVs = true; - SrcModel.BuildSettings.SrcLightmapIndex = 0; - SrcModel.BuildSettings.DstLightmapIndex = 1; - } -#endif - - UStaticMesh::FBuildMeshDescriptionsParams MeshParams; - MeshParams.bBuildSimpleCollision = BuildSimpleCollision; - MeshParams.bCommitMeshDescription = true; - MeshParams.bMarkPackageDirty = true; - MeshParams.bUseHashAsGuid = false; - - //Set Mesh Data - UMaterialInterface* Material = GetMaterial(SpeckleMesh->RenderMaterial, Manager); - - const FName MaterialSlotName = Mesh->AddMaterial(Material);; - BaseMeshDescription.PolygonGroupAttributes().RegisterAttribute(MeshAttribute::PolygonGroup::ImportedMaterialSlotName, 1, MaterialSlotName, EMeshAttributeFlags::None); - { - const size_t NumberOfVertices = SpeckleMesh->Vertices.Num(); - StaticMeshDescription->ReserveNewVertices(NumberOfVertices); - - TArray Vertices; - Vertices.Reserve(NumberOfVertices); - - for(const FVector VertexPosition : SpeckleMesh->Vertices) - { - const FVertexID VertID = StaticMeshDescription->CreateVertex(); - StaticMeshDescription->SetVertexPosition(VertID, VertexPosition); - Vertices.Add(VertID); - } - - //Convert Faces - const FPolygonGroupID PolygonGroupID = StaticMeshDescription->CreatePolygonGroup(); - - StaticMeshDescription->SetPolygonGroupMaterialSlotName(PolygonGroupID, MaterialSlotName); - - StaticMeshDescription->VertexInstanceAttributes().RegisterAttribute(MeshAttribute::VertexInstance::TextureCoordinate, 2, FVector2D::ZeroVector, EMeshAttributeFlags::None); - - - StaticMeshDescription->ReserveNewTriangles(SpeckleMesh->Faces.Num() * 3); //Reserve space assuming faces will all be triangles - StaticMeshDescription->ReserveNewPolygons(SpeckleMesh->Faces.Num()); - StaticMeshDescription->ReserveNewVertexInstances(SpeckleMesh->Faces.Num() * 3); //Reserve space assuming faces will all be triangles - - int32 i = 0; - while (i < SpeckleMesh->Faces.Num()) - { - int32 n = SpeckleMesh->Faces[i]; - if(n < 3) n += 3; // 0 -> 3, 1 -> 4 - - TArray VertexInstances; - VertexInstances.Reserve(n); - TSet Verts; - Verts.Reserve(n); - for(int j = 0; j < n; j ++) - { - int32 VertIndex = SpeckleMesh->Faces[i + n - j]; - FVertexID Vert = Vertices[VertIndex]; - bool AlreadyInSet; - Verts.Add(Vert, &AlreadyInSet); - - if(AlreadyInSet) - { - UE_LOG(LogTemp, Warning, TEXT("Invalid Polygon while creating mesh %s - vertex at index %d appears more than once in a face, duplicate vertices will be ignored"), *SpeckleMesh->Id, VertIndex); - continue; - } - FVertexInstanceID VertexInstance = StaticMeshDescription->CreateVertexInstance(Vert); - - VertexInstances.Add(VertexInstance); - - if(SpeckleMesh->TextureCoordinates.Num() > VertIndex) - StaticMeshDescription->SetVertexInstanceUV(VertexInstance, SpeckleMesh->TextureCoordinates[VertIndex]); - - //if(SpeckleMesh->VertexColors.Num() > VertIndex) - // //TODO set vertex colors - } - i += n + 1; - if(VertexInstances.Num() < 3) - { - UE_LOG(LogTemp, Warning, TEXT("Invalid Polygon while creating mesh %s - face has fewer than 3 verts, this face will be ignored"), *SpeckleMesh->Id); - continue; - } - - - TArray Edges; - Edges.Reserve(n); - - const FPolygonID PolygonID = StaticMeshDescription->CreatePolygon(PolygonGroupID, VertexInstances, Edges); - - for (const FEdgeID EdgeID : Edges) - { - StaticMeshDescription->GetEdgeHardnesses()[EdgeID] = true; - } - - StaticMeshDescription->ComputePolygonTriangulation(PolygonID); - } - - - BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Normal, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); - BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Tangent, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); - BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Binormal, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); - BaseMeshDescription.PolygonAttributes().RegisterAttribute(MeshAttribute::Polygon::Center, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient); - - FStaticMeshOperations::ComputePolygonTangentsAndNormals(BaseMeshDescription); - FStaticMeshOperations::ComputeTangentsAndNormals(BaseMeshDescription, EComputeNTBsFlags::Normals | EComputeNTBsFlags::Tangents); - } - - - - //Mesh->PreEditChange(nullptr); - - Mesh->LightMapCoordinateIndex = 1; - Mesh->BuildFromMeshDescriptions(TArray{&BaseMeshDescription}, MeshParams); - -#if WITH_EDITOR - if(UseFullBuild) Mesh->Build(true); //This makes conversion time much slower, but is needed for generating lightmap UVs -#endif - - if (GetWorld()->WorldType == EWorldType::PIE) - { - FAssetRegistryModule::AssetCreated(Mesh); - } - //Mesh->PostEditChange(); //This doesn't seem to be required - - MeshComponent->SetStaticMesh(Mesh); - - MeshComponent->SetMaterialByName(MaterialSlotName, Material); -} - - -UMaterialInterface* ASpeckleUnrealStaticMesh::GetMaterial(const URenderMaterial* SpeckleMaterial, ASpeckleUnrealManager* Manager) -{ - if(SpeckleMaterial->Id == "") return Manager->DefaultMeshMaterial; //Material is invalid - - UMaterialInterface* ExistingMaterial; - if(Manager->TryGetMaterial(SpeckleMaterial, true, ExistingMaterial)) - return ExistingMaterial; //Return existing material - - - UMaterialInterface* MaterialBase = SpeckleMaterial->Opacity >= 1 - ? Manager->BaseMeshOpaqueMaterial - : Manager->BaseMeshTransparentMaterial; - - const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle"), Manager->StreamID, TEXT("Materials"), SpeckleMaterial->Id); - UPackage* Package = CreatePackage(*PackagePath); - - UMaterialInstanceDynamic* DynMaterial = UMaterialInstanceDynamic::Create(MaterialBase, Package, FName(SpeckleMaterial->Name)); - - DynMaterial->SetFlags(RF_Public); - - DynMaterial->SetScalarParameterValue("Opacity", SpeckleMaterial->Opacity); - DynMaterial->SetScalarParameterValue("Metallic", SpeckleMaterial->Metalness); - DynMaterial->SetScalarParameterValue("Roughness", SpeckleMaterial->Roughness); - DynMaterial->SetVectorParameterValue("BaseColor", SpeckleMaterial->Diffuse); - DynMaterial->SetVectorParameterValue("EmissiveColor", SpeckleMaterial->Emissive); - - Manager->ConvertedMaterials.Add(SpeckleMaterial->Id, DynMaterial); - - if (GetWorld()->WorldType == EWorldType::PIE) - { - FAssetRegistryModule::AssetCreated(DynMaterial); - } - - return DynMaterial; - -} diff --git a/Source/SpeckleUnreal/Private/Objects/Collection.cpp b/Source/SpeckleUnreal/Private/Objects/Collection.cpp new file mode 100644 index 0000000..db64133 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/Collection.cpp @@ -0,0 +1,20 @@ + +#include "Objects/Collection.h" + + + + +bool UCollection::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + if(!Super::Parse(Obj, ReadTransport)) return false; + + // Parse Name property + if(!Obj->TryGetStringField(TEXT("name"), Name)) return false; + //DynamicProperties.Remove(TEXT("name")); //Don't remove from dynamic, as we pick this up to name the actor + + // Parse collectionType + if(!Obj->TryGetStringField(TEXT("collectionType"), CollectionType)) return false; + DynamicProperties.Remove(TEXT("collectionType")); + + return true; +} diff --git a/Source/SpeckleUnreal/Private/Objects/DisplayValueElement.cpp b/Source/SpeckleUnreal/Private/Objects/DisplayValueElement.cpp new file mode 100644 index 0000000..409099f --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/DisplayValueElement.cpp @@ -0,0 +1,54 @@ + +#include "Objects/DisplayValueElement.h" + +#include "API/SpeckleSerializer.h" +#include "Objects/Geometry/Mesh.h" + + +TArray UDisplayValueElement::DisplayValueAliasStrings = { + "displayValue", + "@displayValue", +}; + + +bool UDisplayValueElement::AddDisplayValue(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + UMesh* DisplayMesh = Cast(USpeckleSerializer::DeserializeBase(Obj, ReadTransport)); + const bool Valid = IsValid(DisplayMesh); + if(Valid) + this->DisplayValue.Add(DisplayMesh); + return Valid; +} + +bool UDisplayValueElement::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + if(!Super::Parse(Obj, ReadTransport)) return false; + + //Find display values + for(const FString& Alias : DisplayValueAliasStrings) + { + const TSharedPtr* SubObjectPtr; + if (Obj->TryGetObjectField(Alias, SubObjectPtr)) + { + AddDisplayValue(*SubObjectPtr, ReadTransport); + DynamicProperties.Remove(Alias); + continue; + } + + const TArray>* SubArrayPtr; + if (Obj->TryGetArrayField(Alias, SubArrayPtr)) + { + for (const auto& ArrayElement : *SubArrayPtr) + { + const TSharedPtr* ArraySubObjPtr; + if (ArrayElement->TryGetObject(ArraySubObjPtr)) + { + AddDisplayValue(*ArraySubObjPtr, ReadTransport); + } + } + DynamicProperties.Remove(Alias); + } + } + + return DisplayValue.Num() > 0; +} diff --git a/Source/SpeckleUnreal/Private/Objects/Mesh.cpp b/Source/SpeckleUnreal/Private/Objects/Geometry/Mesh.cpp similarity index 54% rename from Source/SpeckleUnreal/Private/Objects/Mesh.cpp rename to Source/SpeckleUnreal/Private/Objects/Geometry/Mesh.cpp index ded23ad..6ebbbf1 100644 --- a/Source/SpeckleUnreal/Private/Objects/Mesh.cpp +++ b/Source/SpeckleUnreal/Private/Objects/Geometry/Mesh.cpp @@ -1,67 +1,63 @@ -// Fill out your copyright notice in the Description page of Project Settings. +#include "Objects/Geometry/Mesh.h" -#include "Objects/Mesh.h" +#include "Objects/Other/RenderMaterial.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Transports/Transport.h" -#include "SpeckleUnrealManager.h" - -void UMesh::Parse(const TSharedPtr Obj, const ASpeckleUnrealManager* Manager) +bool UMesh::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) { - Super::Parse(Obj, Manager); - - const float ScaleFactor = Manager->ParseScaleFactor(Units); + if(!Super::Parse(Obj, ReadTransport)) return false; + const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units); //Parse optional Transform + if(USpeckleObjectUtils::TryParseTransform(Obj, Transform)) + { + Transform.ScaleTranslation(FVector(ScaleFactor)); + DynamicProperties.Remove(TEXT("transform")); + } + else { Transform = FMatrix::Identity; - - const TArray>* TransformData = nullptr; - if(Obj->HasField("properties") && Obj->GetObjectField("properties")->TryGetArrayField("transform", TransformData)) - { - for(int32 Row = 0; Row < 4; Row++) - for(int32 Col = 0; Col < 4; Col++) - { - Transform.M[Row][Col] = TransformData->operator[](Row * 4 + Col)->AsNumber(); - } - Transform = Transform.GetTransposed(); - Transform.ScaleTranslation(FVector(ScaleFactor)); - } } + //Parse Vertices { - TArray> ObjectVertices = Manager->CombineChunks(Obj->GetArrayField("vertices")); + TArray> ObjectVertices = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField(TEXT("vertices")), ReadTransport); const int32 NumberOfVertices = ObjectVertices.Num() / 3; Vertices.Reserve(NumberOfVertices); for (size_t i = 0, j = 0; i < NumberOfVertices; i++, j += 3) { - Vertices.Add(Transform.InverseTransformPosition(FVector + Vertices.Add(FVector ( ObjectVertices[j].Get()->AsNumber(), - ObjectVertices[j + 1].Get()->AsNumber(), + -ObjectVertices[j + 1].Get()->AsNumber(), ObjectVertices[j + 2].Get()->AsNumber() - ) * ScaleFactor )); + ) * ScaleFactor ); } + DynamicProperties.Remove(TEXT("vertices")); } //Parse Faces { - const TArray> FaceVertices = Manager->CombineChunks(Obj->GetArrayField("faces")); + const TArray> FaceVertices = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField(TEXT("faces")), ReadTransport); Faces.Reserve(FaceVertices.Num()); - for(const auto VertIndex : FaceVertices) + for(const auto& VertIndex : FaceVertices) { Faces.Add(VertIndex->AsNumber()); } + DynamicProperties.Remove(TEXT("faces")); } //Parse TextureCoords { const TArray>* TextCoordArray; - if(Obj->TryGetArrayField("textureCoordinates", TextCoordArray)) + if(Obj->TryGetArrayField(TEXT("textureCoordinates"), TextCoordArray)) { - TArray> TexCoords = Manager->CombineChunks(*TextCoordArray); + TArray> TexCoords = USpeckleObjectUtils::CombineChunks(*TextCoordArray, ReadTransport); TextureCoordinates.Reserve(TexCoords.Num() / 2); @@ -71,17 +67,18 @@ void UMesh::Parse(const TSharedPtr Obj, const ASpeckleUnrealManager ( TexCoords[i].Get()->AsNumber(), TexCoords[i + 1].Get()->AsNumber() - )); + )); } + DynamicProperties.Remove(TEXT("textureCoordinates")); } } //Parse VertexColors { const TArray>* ColorArray; - if(Obj->TryGetArrayField("colors", ColorArray)) + if(Obj->TryGetArrayField(TEXT("colors"), ColorArray)) { - TArray> Colors = Manager->CombineChunks(*ColorArray); + TArray> Colors = USpeckleObjectUtils::CombineChunks(*ColorArray, ReadTransport); VertexColors.Reserve(Colors.Num()); @@ -89,18 +86,25 @@ void UMesh::Parse(const TSharedPtr Obj, const ASpeckleUnrealManager { VertexColors.Add(FColor(Colors[i].Get()->AsNumber())); } + DynamicProperties.Remove(TEXT("colors")); } } + + //Parse Optional RenderMaterial + if (Obj->HasField(TEXT("renderMaterial"))) + { + RenderMaterial = NewObject(); + RenderMaterial->Parse(Obj->GetObjectField(TEXT("renderMaterial")), ReadTransport); + DynamicProperties.Remove(TEXT("renderMaterial")); + } AlignVerticesWithTexCoordsByIndex(); + + return Vertices.Num() > 0 && Faces.Num() > 0; } -/** - * If not already so, this method will align vertices - * such that a vertex and its corresponding texture coordinates have the same index. - * See "https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Mesh.cs" - */ + void UMesh::AlignVerticesWithTexCoordsByIndex() { if(TextureCoordinates.Num() == 0) return; diff --git a/Source/SpeckleUnreal/Private/Objects/Geometry/PointCloud.cpp b/Source/SpeckleUnreal/Private/Objects/Geometry/PointCloud.cpp new file mode 100644 index 0000000..b63bf5f --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/Geometry/PointCloud.cpp @@ -0,0 +1,57 @@ + +#include "Objects/Geometry/PointCloud.h" + +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Transports/Transport.h" + +bool UPointCloud::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + if(!Super::Parse(Obj, ReadTransport)) return false; + + const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units); + + //Parse Points + { + TArray> ObjectPoints = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField(TEXT("points")), ReadTransport); + + Points.Reserve(ObjectPoints.Num() / 3); + for (int32 i = 2; i < ObjectPoints.Num(); i += 3) + { + Points.Add(FVector + ( + ObjectPoints[i - 2].Get()->AsNumber(), + ObjectPoints[i - 1].Get()->AsNumber(), + ObjectPoints[i].Get()->AsNumber() + ) * ScaleFactor); + } + DynamicProperties.Remove("points"); + } + + + //Parse Colors + { + TArray> ObjectColors = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField(TEXT("colors")), ReadTransport); + + Colors.Reserve(ObjectColors.Num()); + for (int32 i = 0; i < ObjectColors.Num(); i += 1) + { + Colors.Add( FColor(ObjectColors[i].Get()->AsNumber()) ); + } + DynamicProperties.Remove("colors"); + } + + //Parse Sizes + { + TArray> ObjectSizes = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField(TEXT("sizes")), ReadTransport); + + Sizes.Reserve(ObjectSizes.Num()); + for (int32 i = 0; i < ObjectSizes.Num(); i += 1) + { + Sizes.Add( ObjectSizes[i].Get()->AsNumber() * ScaleFactor); + } + DynamicProperties.Remove("sizes"); + } + + return Points.Num() >= 0; +} + diff --git a/Source/SpeckleUnreal/Private/Objects/ObjectModelRegistry.cpp b/Source/SpeckleUnreal/Private/Objects/ObjectModelRegistry.cpp new file mode 100644 index 0000000..c139096 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/ObjectModelRegistry.cpp @@ -0,0 +1,101 @@ + +#include "Objects/ObjectModelRegistry.h" + +#include "Objects/Base.h" +#include "Templates/SubclassOf.h" +#include "UObject/UObjectIterator.h" + +TMap> UObjectModelRegistry::TypeRegistry; + +void UObjectModelRegistry::GenerateTypeRegistry() +{ + //TypeRegistry.Reset(); + TypeRegistry.Empty(); + //TypeRegistry = TMap>(); + //check(TypeRegistry.IsSet()); + + //Find every class : UBase and add to Registry + for (TObjectIterator It; It; ++It) + { + const UClass* Class = *It; + if (Class->IsChildOf(UBase::StaticClass()) && + !Class->HasAnyClassFlags(CLASS_Abstract)) + { + const FString& SpeckleType = Class->GetDefaultObject()->SpeckleType; + const FString TypeName = GetTypeName(SpeckleType); + + ensureAlwaysMsgf(!TypeRegistry.Contains(TypeName), + TEXT("Base class: %s conflicts with: %s for TypeName: %s"), + *Class->GetName(), + *TypeRegistry[SpeckleType]->GetName(), + *SpeckleType); + + TypeRegistry.Add(TypeName, *It); + } + } +} + + +bool UObjectModelRegistry::SplitSpeckleType(const FString& SpeckleType, FString& OutRemainder, FString& OutTypeName, const FString& Split) +{ + if(SpeckleType.Split(Split, &OutRemainder, &OutTypeName, ESearchCase::CaseSensitive, ESearchDir::FromEnd)) + { + return true; + } + else + { + OutTypeName = SpeckleType; + return false; + } +} + +FString UObjectModelRegistry::GetTypeName(const FString& SpeckleType) +{ + FString Discard, Ret; + SplitSpeckleType(SpeckleType, Discard, Ret); + return Ret; +} + +FString UObjectModelRegistry::GetSimplifiedTypeName(const FString& SpeckleType) +{ + FString Discard, Ret; + SplitSpeckleType(SpeckleType,Discard, Ret, "."); + return Ret; +} + +TSubclassOf UObjectModelRegistry::GetAtomicType(const FString& SpeckleType) +{ + + FString WorkingType; + FString Remainder = FString(SpeckleType); + + while(SplitSpeckleType(Remainder, Remainder, WorkingType)) + { + TSubclassOf Type; + if(TryGetRegisteredType(WorkingType, Type)) + { + return Type; + } + } + return UBase::StaticClass(); +} + +TSubclassOf UObjectModelRegistry::GetRegisteredType(const FString& TypeName) +{ + TSubclassOf Type = nullptr; + TryGetRegisteredType(TypeName, Type); + return Type; +} + +bool UObjectModelRegistry::TryGetRegisteredType(const FString& TypeName, TSubclassOf& OutType) +{ + if(TypeRegistry.Num() == 0) GenerateTypeRegistry(); + + + const bool Contains = TypeRegistry.Contains(TypeName); + if(Contains) + { + OutType = *TypeRegistry.Find(TypeName); + } + return Contains; +} diff --git a/Source/SpeckleUnreal/Private/Objects/Other/BlockInstance.cpp b/Source/SpeckleUnreal/Private/Objects/Other/BlockInstance.cpp new file mode 100644 index 0000000..6ac8ed5 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/Other/BlockInstance.cpp @@ -0,0 +1,67 @@ + +#include "Objects/Other/BlockInstance.h" +#include "LogSpeckle.h" + +#include "API/SpeckleSerializer.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Transports/Transport.h" + +bool UBlockInstance::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + if(!Super::Parse(Obj, ReadTransport)) return false; + + const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units); + + //Transform + if(!USpeckleObjectUtils::TryParseTransform(Obj, Transform)) return false; + Transform.ScaleTranslation(FVector(ScaleFactor)); + DynamicProperties.Remove(TEXT("Transform")); + + + //Geometries + //NOTE: This logic differs greatly from sharp/py implementations + const TSharedPtr* DefPtr; + if(!(Obj->TryGetObjectField(TEXT("definition"), DefPtr) || Obj->TryGetObjectField(TEXT("blockDefinition"), DefPtr) )) return false; + + const FString RefID = DefPtr->operator->()->GetStringField(TEXT("referencedId")); + const TSharedPtr Definition = ReadTransport->GetSpeckleObject(RefID); + + if(!Obj->TryGetStringField(TEXT("name"), Name)) + { + if(Definition->TryGetStringField(TEXT("name"), Name)) + { + //The instance has no name, so we'll steal it from the definition + DynamicProperties.Add(TEXT("name"), Definition->TryGetField(TEXT("name"))); + } + } + + const auto Geometries = Definition->GetArrayField(TEXT("geometry")); + + if(Geometries.Num() <= 0) + { + UE_LOG(LogSpeckle, Warning, TEXT("Block definition has no geometry. id: %s"), *RefID) + return false; + } + + for(const auto& Geo : Geometries) + { + const TSharedPtr MeshReference = Geo->AsObject(); + const FString ChildId = MeshReference->GetStringField(TEXT("referencedId")); + + if(ReadTransport->HasObject(ChildId)) + { + UBase* Child = USpeckleSerializer::DeserializeBase(ReadTransport->GetSpeckleObject(ChildId), ReadTransport); + if(IsValid(Child)) + Geometry.Add(Child); + } + else UE_LOG(LogSpeckle, Warning, TEXT("Block definition references an unknown object id: %s"), *ChildId) + } + DynamicProperties.Remove(TEXT("geometry")); + + // Intentionally don't remove blockDefinition from dynamic properties, + // because we want the converter to create the child geometries for us + //DynamicProperties.Remove(TEXT("blockDefinition")); + + return true; + +} diff --git a/Source/SpeckleUnreal/Private/Objects/Other/RevitInstance.cpp b/Source/SpeckleUnreal/Private/Objects/Other/RevitInstance.cpp new file mode 100644 index 0000000..0a94af4 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/Other/RevitInstance.cpp @@ -0,0 +1,74 @@ + +#include "Objects/Other/RevitInstance.h" +#include "LogSpeckle.h" + +#include "API/SpeckleSerializer.h" +#include "Objects/Utils/SpeckleObjectUtils.h" +#include "Transports/Transport.h" + +bool URevitInstance::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + if(!Super::Parse(Obj, ReadTransport)) return false; + + const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units); + + //Transform + if(!USpeckleObjectUtils::TryParseTransform(Obj, Transform)) return false; + Transform.ScaleTranslation(FVector(ScaleFactor)); + DynamicProperties.Remove(TEXT("Transform")); + + + //Geometries + //NOTE: This logic differs greatly from sharp/py implementations + const TSharedPtr* DefPtr; + if(!Obj->TryGetObjectField(TEXT("definition"), DefPtr)) return false; + + const FString RefID = DefPtr->operator->()->GetStringField(TEXT("referencedId")); + const TSharedPtr Definition = ReadTransport->GetSpeckleObject(RefID); + + const FString NameKey = TEXT("name"); + if(!Obj->TryGetStringField(NameKey, Name)) + { + if(Definition->TryGetStringField(NameKey, Name)) + { + //The instance has no name, so we'll steal it from the definition + DynamicProperties.Add(NameKey, Definition->TryGetField(NameKey)); + } + } + auto Geometries = TArray>(); + const TArray>* ElementsPtr; + if(Definition->TryGetArrayField(TEXT("elements"), ElementsPtr)) + Geometries.Append(*ElementsPtr); + const TArray>* DisplayValuePtr; + if(Definition->TryGetArrayField(TEXT("displayValue"), DisplayValuePtr)) + Geometries.Append(*DisplayValuePtr); + + + if(Geometries.Num() <= 0) + { + UE_LOG(LogSpeckle, Warning, TEXT("Instance definition has no geometry. id: %s"), *RefID) + return false; + } + + for(const auto& Geo : Geometries) + { + const TSharedPtr MeshReference = Geo->AsObject(); + const FString ChildId = MeshReference->GetStringField(TEXT("referencedId")); + + if(ReadTransport->HasObject(ChildId)) + { + UBase* Child = USpeckleSerializer::DeserializeBase(ReadTransport->GetSpeckleObject(ChildId), ReadTransport); + if(IsValid(Child)) + Geometry.Add(Child); + } + else UE_LOG(LogSpeckle, Warning, TEXT("Block definition references an unknown object id: %s"), *ChildId) + } + DynamicProperties.Remove(TEXT("geometry")); + + // Intentionally don't remove blockDefinition from dynamic properties, + // because we want the converter to create the child geometries for us + //DynamicProperties.Remove("blockDefinition"); + + return true; + +} diff --git a/Source/SpeckleUnreal/Private/Objects/Other/View3D.cpp b/Source/SpeckleUnreal/Private/Objects/Other/View3D.cpp new file mode 100644 index 0000000..02b962b --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/Other/View3D.cpp @@ -0,0 +1,35 @@ + +#include "Objects/Other/View3D.h" + +#include "Objects/Utils/SpeckleObjectUtils.h" + +bool UView3D::Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) +{ + if(!Super::Parse(Obj, ReadTransport)) return false; + + const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units); + + // Parse optional Name property + if(Obj->TryGetStringField(TEXT("name"), Name)) { } + + // Parse Origin + if(!USpeckleObjectUtils::ParseVectorProperty(Obj, TEXT("origin"), ReadTransport, Origin)) return false; + Origin *= ScaleFactor; + DynamicProperties.Remove(TEXT("origin")); + + // Parse UpDirection + if(!USpeckleObjectUtils::ParseVectorProperty(Obj, "upDirection", ReadTransport, UpDirection)) return false; + UpDirection *= ScaleFactor; + DynamicProperties.Remove(TEXT("upDirection")); + + // Parse ForwardDirection + if(!USpeckleObjectUtils::ParseVectorProperty(Obj, TEXT("forwardDirection"), ReadTransport, ForwardDirection)) return false; + ForwardDirection *= ScaleFactor; + DynamicProperties.Remove(TEXT("forwardDirection")); + + // Parse IsOrthogonal + if(!Obj->TryGetBoolField(TEXT("isOrthogonal"), IsOrthogonal)) return false; + DynamicProperties.Remove(TEXT("isOrthogonal")); + + return true; +} diff --git a/Source/SpeckleUnreal/Private/Objects/PointCloud.cpp b/Source/SpeckleUnreal/Private/Objects/PointCloud.cpp deleted file mode 100644 index b1e5477..0000000 --- a/Source/SpeckleUnreal/Private/Objects/PointCloud.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - - -#include "Objects/PointCloud.h" - -#include "SpeckleUnrealManager.h" - -void UPointCloud::Parse(const TSharedPtr Obj, const ASpeckleUnrealManager* Manager) -{ - Super::Parse(Obj, Manager); - - const float ScaleFactor = Manager->ParseScaleFactor(Units); - - //Parse Points - { - TArray> ObjectPoints = Manager->CombineChunks(Obj->GetArrayField("points")); - - Points.Reserve(ObjectPoints.Num() / 3); - for (int32 i = 2; i < ObjectPoints.Num(); i += 3) - { - Points.Add(FVector - ( - -ObjectPoints[i - 2].Get()->AsNumber(), - ObjectPoints[i - 1].Get()->AsNumber(), - ObjectPoints[i].Get()->AsNumber() - ) * ScaleFactor); - } - } - - - //Parse Colors - { - TArray> ObjectColors = Manager->CombineChunks(Obj->GetArrayField("colors")); - - Colors.Reserve(ObjectColors.Num()); - for (int32 i = 0; i < ObjectColors.Num(); i += 1) - { - Colors.Add( FColor(ObjectColors[i].Get()->AsNumber()) ); - } - } - - //Parse Sizes - { - TArray> ObjectSizes = Manager->CombineChunks(Obj->GetArrayField("sizes")); - - Sizes.Reserve(ObjectSizes.Num()); - for (int32 i = 0; i < ObjectSizes.Num(); i += 1) - { - Sizes.Add( ObjectSizes[i].Get()->AsNumber() * ScaleFactor); - } - } - -} - diff --git a/Source/SpeckleUnreal/Private/Objects/Utils/SpeckleObjectUtils.cpp b/Source/SpeckleUnreal/Private/Objects/Utils/SpeckleObjectUtils.cpp new file mode 100644 index 0000000..d94b268 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Objects/Utils/SpeckleObjectUtils.cpp @@ -0,0 +1,197 @@ + +#include "Objects/Utils/SpeckleObjectUtils.h" + +#include "LogSpeckle.h" +#include "API/SpeckleSerializer.h" +#include "Engine/World.h" +#include "Objects/ObjectModelRegistry.h" +#include "Objects/Geometry/Mesh.h" +#include "Transports/Transport.h" +#include "Serialization/JsonWriter.h" +#include "Serialization/JsonSerializer.h" + +TArray> USpeckleObjectUtils::CombineChunks(const TArray>& ArrayField, const TScriptInterface Transport) +{ + TArray> ObjectPoints; + + for(int32 i = 0; i < ArrayField.Num(); i++) + { + FString Index; + if(ArrayField[i]->AsObject()->TryGetStringField(TEXT("referencedId"), Index)) + { + if(!ensureAlwaysMsgf(Transport->HasObject(Index), TEXT("Failed to Dechunk array, Could not find chunk %s in transport"), *Index)) + continue; + + const auto Chunk = Transport->GetSpeckleObject(Index)->GetArrayField(TEXT("data"));; + ObjectPoints.Append(Chunk); + } + else + { + return ArrayField; //Array was never chunked to begin with + } + } + return ObjectPoints; +} + +bool USpeckleObjectUtils::ResolveReference(const TSharedPtr Object, const TScriptInterface Transport, TSharedPtr& OutObject) +{ + FString SpeckleType; + FString ReferenceID; + + if (Object->TryGetStringField(TEXT("speckle_type"), SpeckleType) + && SpeckleType == TEXT("reference") + && Object->TryGetStringField(TEXT("referencedId"),ReferenceID)) + { + check(Transport != nullptr && Transport.GetObject() != nullptr) + + OutObject = Transport->GetSpeckleObject(ReferenceID); + return OutObject != nullptr; + } + return false; +} + +float USpeckleObjectUtils::ParseScaleFactor(const FString& UnitsString) +{ + static const auto ParseUnits = [](const FString& LUnits) -> float + { + if (LUnits == "millimeters" || LUnits == "millimeter" || LUnits == "millimetres" || LUnits == "millimetre" || LUnits == "mm") + return 0.1; + if (LUnits == "centimeters" || LUnits == "centimeter" ||LUnits == "centimetres" || LUnits == "centimetre" || LUnits == "cm") + return 1; + if (LUnits == "meters" || LUnits == "meter" || LUnits == "metres" || LUnits == "metre" || LUnits == "m") + return 100; + if (LUnits == "kilometers" || LUnits == "kilometres" || LUnits == "km") + return 100000; + + if (LUnits == "inches" || LUnits == "inch" || LUnits == "in") + return 2.54; + if (LUnits == "feet" || LUnits == "foot" || LUnits == "ft") + return 30.48; + if (LUnits == "yards" || LUnits == "yard"|| LUnits == "yd") + return 91.44; + if (LUnits == "miles" || LUnits == "mile" || LUnits == "mi") + return 160934.4; + + if (LUnits == "us_ft" || LUnits == "ussurveyfeet") + return 12000.0 / 3937.0; + + return 100; + }; + + return ParseUnits(UnitsString.ToLower()); // * WorldToCentimeters; //TODO take into account world units +} + +FTransform USpeckleObjectUtils::CreateTransform(UPARAM(ref) const FMatrix& TransformMatrix) +{ + FTransform Transform(TransformMatrix); + Transform.ScaleTranslation(FVector(1,-1,1)); + FVector Rot = Transform.GetRotation().Euler(); + FVector NewRot(-Rot.X, Rot.Y, -Rot.Z); + Transform.SetRotation(FQuat::MakeFromEuler(NewRot)); + return Transform; +} + +bool USpeckleObjectUtils::TryParseTransform(const TSharedPtr SpeckleObject, FMatrix& OutMatrix) +{ + const TSharedPtr* TransformObject; + const TArray>* TransformData; + + if(SpeckleObject->TryGetArrayField(TEXT("transform"), TransformData)) //Handle transform as array + { } + else if(SpeckleObject->TryGetObjectField(TEXT("transform"), TransformObject) + && (*TransformObject)->TryGetArrayField(TEXT("matrix"), TransformData)) //Handle transform as object + { } + else return false; + + FMatrix TransformMatrix; + for(int32 Row = 0; Row < 4; Row++) + for(int32 Col = 0; Col < 4; Col++) + { + TransformMatrix.M[Row][Col] = TransformData->operator[](Row * 4 + Col)->AsNumber(); + } + OutMatrix = TransformMatrix.GetTransposed(); + return true; +} + +bool USpeckleObjectUtils::ParseVectorProperty(const TSharedPtr Base, const FString& PropertyName, + const TScriptInterface ReadTransport, FVector& OutObject) +{ + const TSharedPtr* OriginObject; + if(Base->TryGetObjectField(PropertyName, OriginObject) + && ParseVector(*OriginObject, ReadTransport, OutObject)) + { + return true; + } + + return false; +} + +bool USpeckleObjectUtils::ParseVector(const TSharedPtr Object, + const TScriptInterface Transport, FVector& OutObject) +{ + if(!ensure(Object != nullptr)) return false; + + TSharedPtr Obj; + if(!ResolveReference(Object, Transport, Obj)) Obj = Object; + + double x = 0, y = 0, z = 0; + + if(!(Obj->TryGetNumberField(TEXT("x"), x) + && Obj->TryGetNumberField(TEXT("y"), y) + && Obj->TryGetNumberField(TEXT("z"), z))) return false; + + OutObject = FVector(x,y,z); + //return true; + + UMesh* Mesh; + return ParseSpeckleObject(Obj, Transport, Mesh); +} + +template +bool USpeckleObjectUtils::ParseSpeckleObject(const TSharedPtr Object, + const TScriptInterface Transport, TBase*& OutObject) +{ + static_assert(TIsDerivedFrom::IsDerived, TEXT("Type TBase must inherit UBase")); + + TSharedPtr Obj; + if(!ResolveReference(Object, Transport, Obj)) Obj = Object; + + UBase* b = USpeckleSerializer::DeserializeBase(Object, Transport); + OutObject = Cast(b); + return OutObject == nullptr; +} + + +AActor* USpeckleObjectUtils::SpawnActorInWorld(const UObject* WorldContextObject, const TSubclassOf Class, UPARAM(ref) const FTransform& Transform) +{ + return WorldContextObject->GetWorld()->SpawnActor(Class, &Transform, FActorSpawnParameters()); +} + +FString USpeckleObjectUtils::DisplayAsString(const FString& msg, const TSharedPtr Obj) +{ + FString OutputString; + TSharedRef> Writer = TJsonWriterFactory<>::Create(&OutputString); + FJsonSerializer::Serialize(Obj.ToSharedRef(), Writer); + UE_LOG(LogSpeckle, Display, TEXT("resulting jsonString from %s -> %s"), *msg, *OutputString); + return OutputString; +} + +FString USpeckleObjectUtils::GetFriendlyObjectName(const UBase* SpeckleObject) +{ + FString Prefix; + if(!(SpeckleObject->TryGetDynamicString(TEXT("name"), Prefix) + || SpeckleObject->TryGetDynamicString(TEXT("Name"), Prefix) + || SpeckleObject->TryGetDynamicString(TEXT("Family"), Prefix))) + { + Prefix = UObjectModelRegistry::GetSimplifiedTypeName(SpeckleObject->SpeckleType); + } + + return FString::Printf(TEXT("%s -- %s"), *Prefix, *SpeckleObject->Id); + +} + +FString USpeckleObjectUtils::GetBoringObjectName(const UBase* SpeckleObject) +{ + const FString Prefix = UObjectModelRegistry::GetSimplifiedTypeName(SpeckleObject->SpeckleType); + return FString::Printf(TEXT("%s -- %s"), *Prefix, *SpeckleObject->Id); +} \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/ReceiveSelectionComponent.cpp b/Source/SpeckleUnreal/Private/ReceiveSelectionComponent.cpp new file mode 100644 index 0000000..f6a5a75 --- /dev/null +++ b/Source/SpeckleUnreal/Private/ReceiveSelectionComponent.cpp @@ -0,0 +1,427 @@ + +#include "ReceiveSelectionComponent.h" + +#include "API/Models/SpeckleUser.h" +#include "API/ClientAPI.h" +#include "JsonObjectConverter.h" +#include "LogSpeckle.h" + +#if WITH_EDITOR +void UReceiveSelectionComponent::PostEditChangeProperty(FPropertyChangedEvent& e) +{ + Super::PostEditChangeProperty(e); + + const FName PropertyName = (e.Property != nullptr) ? e.Property->GetFName() : NAME_None; + PropertyChangeHandler(PropertyName); +} +#endif + +void UReceiveSelectionComponent::PropertyChangeHandler(const FName& PropertyName) +{ + if(bManualMode) return; + + if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, bManualMode)) + { + Refresh(); + } + else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, AuthToken) + || PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, ServerUrl)) + { + IsAccountValid = !AuthToken.IsEmpty() && !ServerUrl.IsEmpty(); + if(IsAccountValid) + { + //TODO maybe we should check URL is a valid URL? + ServerUrl.TrimEndInline(); + while(ServerUrl.RemoveFromEnd("/")) { } + AuthToken.TrimEndInline(); + } + + UpdateStreams(); + } + else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, SelectedStreamText) + && !SelectedStreamText.IsEmpty()) + { + IsStreamValid = Streams.Contains(SelectedStreamText); + if(IsStreamValid) + { + SelectStream(SelectedStreamText); + } + else UpdateStreams(); + } + else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, SelectedBranchText) + && !SelectedBranchText.IsEmpty()) + { + IsBranchValid = Branches.Contains(SelectedBranchText); + if(IsBranchValid) + { + SelectBranch(SelectedBranchText); + } + else UpdateBranches(); + } + else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, SelectedCommitText) + && !SelectedCommitText.IsEmpty()) + { + IsCommitValid = Commits.Contains(SelectedCommitText); + if(IsCommitValid) + { + SelectCommit(SelectedCommitText); + } + else UpdateCommits(); + } +} + + +void UReceiveSelectionComponent::Refresh() +{ + IsAccountValid = !AuthToken.IsEmpty() && !ServerUrl.IsEmpty(); + + UpdateStreams(); +} + + +bool UReceiveSelectionComponent::TryGetSelectedCommit(FSpeckleCommit& OutCommit) const +{ + if(!bManualMode && IsCommitValid) + { + OutCommit = Commits.FindRef(SelectedCommitText); + return true; + } + return false; +} + +bool UReceiveSelectionComponent::TryGetSelectedBranch(FSpeckleBranch& OutBranch) const +{ + if(!bManualMode && IsBranchValid) + { + OutBranch = Branches.FindRef(SelectedBranchText); + return true; + } + return false; +} + +bool UReceiveSelectionComponent::TryGetSelectedStream(FSpeckleStream& OutStream) const +{ + if(!bManualMode && IsStreamValid) + { + OutStream = Streams.FindRef(SelectedStreamText); + return true; + } + return false; +} + +void UReceiveSelectionComponent::OpenURLInBrowser() const +{ + const FString URL = GetUrl(); + + if(!ensure(FPlatformProcess::CanLaunchURL(*URL))) return; + + FString LaunchErrors; + FPlatformProcess::LaunchURL(*URL, nullptr, &LaunchErrors); + + if(LaunchErrors.IsEmpty()) + { + UE_LOG(LogSpeckle, Log, TEXT("Launched URL \"%s\" in browser"), *URL); + } + else + { + UE_LOG(LogSpeckle, Warning, TEXT("Failed to launched URL \"%s\" in browser - %s"), *URL, *LaunchErrors); + } + +} + +bool UReceiveSelectionComponent::IsSelectionComplete(FString& OutStatusMessage) const +{ + if(bManualMode) + { + if(ServerUrl.IsEmpty()) OutStatusMessage = TEXT("Server Url is invalid, must specify a valid url"); + else if(StreamId.IsEmpty()) OutStatusMessage = TEXT("Stream id is invalid, must specify a streamId"); + else if(ObjectId.IsEmpty()) OutStatusMessage = TEXT("Object id is invalid, must specify a objectId"); + else + { + OutStatusMessage = TEXT("Ready to recieve object"); + return true; + } + } + else + { + if(!IsAccountValid) OutStatusMessage = TEXT("Account is invalid, please specify a valid server URL and token. (tokens can be created from your Speckle profiles page)"); + else if(!IsStreamValid) OutStatusMessage = TEXT("Selected stream is invalid"); + else if(!IsBranchValid) OutStatusMessage = TEXT("Selected branch is invalid"); + else if(!IsCommitValid) OutStatusMessage = TEXT("Selected commit is invalid"); + else + { + ensure(!ServerUrl.IsEmpty()); + ensure(!StreamId.IsEmpty()); + ensure(!ObjectId.IsEmpty()); + OutStatusMessage = TEXT("Ready to recieve commit"); + return true; + } + } + return false; +} + +FString UReceiveSelectionComponent::GetUrl() const +{ + if(bManualMode) + { + return FString::Printf(TEXT("%s/streams/%s/objects/%s"), + *ServerUrl, *StreamId, *ObjectId); + } + + if(!IsStreamValid) return ServerUrl; + + if(!IsBranchValid) + return FString::Printf(TEXT("%s/streams/%s/"), + *ServerUrl, *GetSelectedStream().ID); + + if(!IsCommitValid) + return FString::Printf(TEXT("%s/streams/%s/branches/%s"), + *ServerUrl, *GetSelectedStream().ID, *GetSelectedBranch().Name); + + return FString::Printf(TEXT("%s/streams/%s/commits/%s"), + *ServerUrl, *GetSelectedStream().ID, *GetSelectedCommit().ID); +} + +TArray UReceiveSelectionComponent::GetStreamsOptions() const +{ + TArray Options; + Streams.GetKeys(Options); + return Options; +} + +bool UReceiveSelectionComponent::SelectStream(const FString& DisplayId) +{ + const bool IsValid = !DisplayId.IsEmpty() && Streams.Contains(DisplayId); + if(IsValid && !bManualMode) + { + SelectedStreamText = DisplayId; + IsStreamValid = true; + StreamId = GetSelectedStream().ID; + } + else + { + SelectedStreamText = ""; + IsStreamValid = false; + } + UpdateBranches(); + return IsStreamValid; +} + +void UReceiveSelectionComponent::UpdateStreams() +{ + Streams.Reset(); + SelectStream(""); + + if(!IsAccountValid || bManualMode) return; + + const FString LogName(__FUNCTION__); + const FString Payload = FString::Printf(TEXT("{\"query\": \"query{activeUser{id streams(limit: %d){items{id name}}}}\"}"), Limit); + + //Response Handling + auto OnComplete = [&](const FString& ResponseJson) + { + if(bManualMode) return; + + FSpeckleUser Response; + + if(!ensure(FJsonObjectConverter::JsonObjectStringToUStruct(*ResponseJson, &Response, 0, 0))) return; + + const TArray& AvailableStreams = Response.Streams.Items; + //Assemble stream map + Streams.Reserve(AvailableStreams.Num()); + for(const auto& s : Response.Streams.Items) + { + FString DisplayId = FString::Printf(TEXT("%s - %s"), *s.Name, *s.ID); + Streams.Add(DisplayId, s); + } + + //Set default selection + if(AvailableStreams.Num() > 0) + { + const FSpeckleStream& s = AvailableStreams[0]; + FString DisplayId = FString::Printf(TEXT("%s - %s"), *s.Name, *s.ID); + + SelectStream(DisplayId); + } + + UE_LOG(LogSpeckle, Verbose, TEXT("%s was successful"), *LogName); + }; + FAPIResponceDelegate CompleteDelegate; + CompleteDelegate.BindLambda(OnComplete); + + //On error + FErrorDelegate ErrorDelegate; + ErrorDelegate.BindStatic(LogError, LogName); + + FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, "activeUser", Payload, LogName, CompleteDelegate, ErrorDelegate); + +} + +FSpeckleStream UReceiveSelectionComponent::GetSelectedStream() const +{ + return Streams[SelectedStreamText]; +} + +TArray UReceiveSelectionComponent::GetBranchOptions() +{ + TArray Options; + Branches.GetKeys(Options); + return Options; +} + +bool UReceiveSelectionComponent::SelectBranch(const FString& DisplayId) +{ + const bool IsValid = !DisplayId.IsEmpty() && Branches.Contains(DisplayId); + if(IsValid && !bManualMode) + { + SelectedBranchText = DisplayId; + IsBranchValid = true; + } + else + { + SelectedBranchText = ""; + IsBranchValid=false; + } + UpdateCommits(); + return IsBranchValid; +} + + +void UReceiveSelectionComponent::UpdateBranches() +{ + Branches.Reset(); + SelectBranch(""); + + if(!IsStreamValid || bManualMode) return; + + const FString LogName(__FUNCTION__); + const FString Payload = FString::Printf(TEXT("{\"query\": \"query{stream(id: \\\"%s\\\"){branches(limit: %d){items{id name}}}}\"}"), *GetSelectedStream().ID, Limit); + + //Response Handling + auto OnComplete = [&](const FString& ResponseJson) + { + if(bManualMode) return; + + FSpeckleStream Response; + + if(!ensure(FJsonObjectConverter::JsonObjectStringToUStruct(*ResponseJson, &Response, 0, 0))) return; + + const TArray& AvailableBranches = Response.Branches.Items; + + //Assemble stream map + Branches.Reserve(AvailableBranches.Num()); + for(const auto& b : AvailableBranches) + { + FString DisplayId = FString::Printf(TEXT("%s"), *b.Name); + Branches.Add(DisplayId, b); + } + + UE_LOG(LogSpeckle, Verbose, TEXT("%s was successful"), *LogName); + + //Set default selection + if(AvailableBranches.Num() > 0) + { + const FSpeckleBranch& b = AvailableBranches[0]; + FString DisplayId = FString::Printf(TEXT("%s"), *b.Name); + + SelectBranch(DisplayId); + } + }; + FAPIResponceDelegate CompleteDelegate; + CompleteDelegate.BindLambda(OnComplete); + + //On error + FErrorDelegate ErrorDelegate; + ErrorDelegate.BindStatic(LogError, LogName); + + FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, "stream", Payload,LogName, CompleteDelegate, ErrorDelegate); +} + + +FSpeckleBranch UReceiveSelectionComponent::GetSelectedBranch() const +{ + return Branches[SelectedBranchText]; +} + +TArray UReceiveSelectionComponent::GetCommitOptions() +{ + TArray Options; + Commits.GetKeys(Options); + return Options; +} + +bool UReceiveSelectionComponent::SelectCommit(const FString& DisplayId) +{ + const bool IsValid = !DisplayId.IsEmpty() && Commits.Contains(DisplayId); + if(IsValid && !bManualMode) + { + SelectedCommitText = DisplayId; + IsCommitValid = true; + ObjectId = GetSelectedCommit().ReferencedObject; + } + else + { + SelectedCommitText = ""; + IsCommitValid=false; + ObjectId = ""; + } + return IsCommitValid; +} + +void UReceiveSelectionComponent::UpdateCommits() +{ + Commits.Reset(); + SelectCommit(""); + + if(!IsBranchValid || bManualMode) return; + + const FString LogName(__FUNCTION__); + const FString Payload = FString::Printf(TEXT("{\"query\": \"query{stream(id: \\\"%s\\\"){branch(name: \\\"%s\\\"){commits(limit: %d){items{id message referencedObject}}}}}\"}"), *GetSelectedStream().ID, *GetSelectedBranch().Name, Limit); + + //Response Handling + auto OnComplete = [&](const FString& ResponseJson) + { + if(bManualMode) return; + + FSpeckleStream Response; + + if(!ensure(FJsonObjectConverter::JsonObjectStringToUStruct(*ResponseJson, &Response, 0, 0))) return; + + const TArray& AvailableCommits = Response.Branch.Commits.Items; + + //Assemble stream map + for(const auto& c :AvailableCommits) + { + FString DisplayId = FString::Printf(TEXT("%s - %s"), *c.Message, *c.ID); + Commits.Add(DisplayId, c); + } + + UE_LOG(LogSpeckle, Verbose, TEXT("%s was successful"), *LogName); + + //Set default selection + if(AvailableCommits.Num() > 0) + { + const FSpeckleCommit& c = AvailableCommits[0]; + FString DisplayId = FString::Printf(TEXT("%s - %s"), *c.Message, *c.ID); + SelectCommit(DisplayId); + } + }; + FAPIResponceDelegate CompleteDelegate; + CompleteDelegate.BindLambda(OnComplete); + + //On error + FErrorDelegate ErrorDelegate; + ErrorDelegate.BindStatic(LogError, LogName); + + FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, "stream", Payload,LogName, CompleteDelegate, ErrorDelegate); +} + +FSpeckleCommit UReceiveSelectionComponent::GetSelectedCommit() const +{ + return Commits[SelectedCommitText]; +} + +void UReceiveSelectionComponent::LogError(const FString& Message, const FString LogName) +{ + UE_LOG(LogSpeckle, Warning, TEXT("%s: %s"), *LogName, *Message) +} diff --git a/Source/SpeckleUnreal/Private/SpeckleUnreal.cpp b/Source/SpeckleUnreal/Private/SpeckleUnreal.cpp index df1b496..7166c9c 100644 --- a/Source/SpeckleUnreal/Private/SpeckleUnreal.cpp +++ b/Source/SpeckleUnreal/Private/SpeckleUnreal.cpp @@ -1,4 +1,3 @@ -// Copyright Epic Games, Inc. All Rights Reserved. #include "SpeckleUnreal.h" @@ -6,13 +5,14 @@ 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 + // 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. + // 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 diff --git a/Source/SpeckleUnreal/Private/SpeckleUnrealActor.cpp b/Source/SpeckleUnreal/Private/SpeckleUnrealActor.cpp deleted file mode 100644 index 1c71a2f..0000000 --- a/Source/SpeckleUnreal/Private/SpeckleUnrealActor.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - - -#include "SpeckleUnrealActor.h" - -// Sets default values -ASpeckleUnrealActor::ASpeckleUnrealActor() -{ - PrimaryActorTick.bCanEverTick = false; - - Scene = CreateDefaultSubobject("Root"); - RootComponent = Scene; - Scene->SetMobility(EComponentMobility::Static); -} - - diff --git a/Source/SpeckleUnreal/Private/SpeckleUnrealLayer.cpp b/Source/SpeckleUnreal/Private/SpeckleUnrealLayer.cpp deleted file mode 100644 index e489195..0000000 --- a/Source/SpeckleUnreal/Private/SpeckleUnrealLayer.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - - -#include "SpeckleUnrealLayer.h" - -USpeckleUnrealLayer::USpeckleUnrealLayer() -{ - -} - -void USpeckleUnrealLayer::Init(FString NewLayerName, int32 NewStartIndex, int32 NewObjectCount) -{ - LayerName = NewLayerName; - LayerColor = FLinearColor(FMath::FRandRange(0, 1), FMath::FRandRange(0, 1), FMath::FRandRange(0, 1), 1); - StartIndex = NewStartIndex; - ObjectCount = NewObjectCount; -} \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/SpeckleUnrealManager.Convert.cpp b/Source/SpeckleUnreal/Private/SpeckleUnrealManager.Convert.cpp deleted file mode 100644 index fe8e539..0000000 --- a/Source/SpeckleUnreal/Private/SpeckleUnrealManager.Convert.cpp +++ /dev/null @@ -1,291 +0,0 @@ -#include "SpeckleUnrealManager.h" -#include "Objects/Mesh.h" -#include "Objects/PointCloud.h" - -#include "Objects/RenderMaterial.h" - - -void ASpeckleUnrealManager::ImportObjectFromCache(AActor* AOwner, const TSharedPtr SpeckleObject, const TSharedPtr ParentObject) -{ - if (!SpeckleObject->HasField("speckle_type")) - return; - if (SpeckleObject->GetStringField("speckle_type") == "reference" && SpeckleObject->HasField("referencedId")) { - TSharedPtr ReferencedObj; - if (SpeckleObjects.Contains(SpeckleObject->GetStringField("referencedId"))) - ImportObjectFromCache(AOwner, SpeckleObjects[SpeckleObject->GetStringField("referencedId")], ParentObject); - return; - } - if (!SpeckleObject->HasField("id")) - return; - - - const FString ObjectId = SpeckleObject->GetStringField("id"); - const FString SpeckleType = SpeckleObject->GetStringField("speckle_type"); - - AActor* Native = nullptr; - - - - if(SpeckleType == "Objects.Geometry.Mesh") - { - Native = CreateMesh(SpeckleObject, ParentObject); - } - else if(SpeckleType == "Objects.Geometry.Pointcloud") - { - Native = CreatePointCloud(SpeckleObject); - } - else if(SpeckleType == "Objects.Other.BlockInstance") - { - Native = CreateBlockInstance(SpeckleObject); - } - else if(SpeckleType == "Objects.Other.BlockDefinition") - { - return; //Ignore block definitions, Block instances will create geometry instead. - } - - - if(IsValid(Native)) - { - -#if WITH_EDITOR - Native->SetActorLabel(FString::Printf(TEXT("%s - %s"), *SpeckleType, *ObjectId)); -#endif - - Native->AttachToActor(AOwner, FAttachmentTransformRules::KeepRelativeTransform); - Native->SetOwner(AOwner); - - InProgressObjectsCache.Add(Native); - } - else - { - Native = AOwner; - } - - - //Convert Children - for (const auto& Kv : SpeckleObject->Values) - { - - const TSharedPtr* SubObjectPtr; - if (Kv.Value->TryGetObject(SubObjectPtr)) - { - ImportObjectFromCache(Native, *SubObjectPtr, SpeckleObject); - continue; - } - - const TArray>* SubArrayPtr; - if (Kv.Value->TryGetArray(SubArrayPtr)) - { - for (const auto& ArrayElement : *SubArrayPtr) - { - const TSharedPtr* ArraySubObjPtr; - if (!ArrayElement->TryGetObject(ArraySubObjPtr)) - continue; - ImportObjectFromCache(Native, *ArraySubObjPtr, SpeckleObject); - } - } - } -} - -bool ASpeckleUnrealManager::TryGetMaterial(const URenderMaterial* SpeckleMaterial, const bool AcceptMaterialOverride, UMaterialInterface*& OutMaterial) -{ - const auto MaterialID = SpeckleMaterial->Id; - - if(AcceptMaterialOverride) - { - //Override by id - if(MaterialOverridesById.Contains(MaterialID)) - { - OutMaterial = MaterialOverridesById[MaterialID]; - return true; - } - //Override by name - const FString Name = SpeckleMaterial->Name; - for (const UMaterialInterface* Mat : MaterialOverridesByName) - { - if(Mat->GetName() == Name) - { - OutMaterial = MaterialOverridesById[MaterialID]; - return true; - } - } - } - - - if(ConvertedMaterials.Contains(MaterialID)) - { - OutMaterial = ConvertedMaterials[MaterialID]; - return true; - } - - return false; -} - - - -TArray> ASpeckleUnrealManager::CombineChunks(const TArray>& ArrayField) const -{ - TArray> ObjectPoints; - - for(int32 i = 0; i < ArrayField.Num(); i++) - { - FString Index; - if(ArrayField[i]->AsObject()->TryGetStringField("referencedId", Index)) - { - const auto Chunk = SpeckleObjects[Index]->GetArrayField("data"); - ObjectPoints.Append(Chunk); - } - else - { - return ArrayField; //Array was never chunked to begin with - } - } - return ObjectPoints; -} - -float ASpeckleUnrealManager::ParseScaleFactor(const FString& Units) const -{ - static const auto ParseUnits = [](const FString& LUnits) -> float - { - if (LUnits == "millimeters" || LUnits == "millimeter" || LUnits == "millimetres" || LUnits == "millimetre" || LUnits == "mm") - return 0.1; - if (LUnits == "centimeters" || LUnits == "centimeter" ||LUnits == "centimetres" || LUnits == "centimetre" || LUnits == "cm") - return 1; - if (LUnits == "meters" || LUnits == "meter" || LUnits == "metres" || LUnits == "metre" || LUnits == "m") - return 100; - if (LUnits == "kilometers" || LUnits == "kilometres" || LUnits == "km") - return 100000; - - if (LUnits == "inches" || LUnits == "inch" || LUnits == "in") - return 2.54; - if (LUnits == "feet" || LUnits == "foot" || LUnits == "ft") - return 30.48; - if (LUnits == "yards" || LUnits == "yard"|| LUnits == "yd") - return 91.44; - if (LUnits == "miles" || LUnits == "mile" || LUnits == "mi") - return 160934.4; - - return 100; - }; - - return ParseUnits(Units.ToLower()) * WorldToCentimeters; -} - - -ASpeckleUnrealActor* ASpeckleUnrealManager::CreateMesh(const TSharedPtr Obj, const TSharedPtr Parent) -{ - const FString ObjId = Obj->GetStringField("id"); - UE_LOG(LogTemp, Log, TEXT("Creating mesh for object %s"), *ObjId); - - - UMesh* Mesh = NewObject(); - Mesh->Parse(Obj, this); - - ASpeckleUnrealActor* ActorInstance = World->SpawnActor(MeshActor, FTransform(Mesh->Transform)); - - - - // Material priority (low to high): DefaultMeshMaterial, Material set on parent, Converted RenderMaterial set on mesh, MaterialOverridesByName match, MaterialOverridesById match - URenderMaterial* Material = NewObject(); - - if (Obj->HasField("renderMaterial")) - { - Material->Parse(Obj->GetObjectField("renderMaterial"), this); - } - else if (Parent && Parent->HasField("renderMaterial")) - { - Material->Parse(Parent->GetObjectField("renderMaterial"), this); - } - - Mesh->RenderMaterial = Material; - - if(ActorInstance->GetClass()->ImplementsInterface(USpeckleMesh::StaticClass())) - { - FEditorScriptExecutionGuard ScriptGuard; - ISpeckleMesh::Execute_SetMesh(ActorInstance, Mesh, this); - } - else - { - UE_LOG(LogTemp, Warning, TEXT("%s does not implement $s interface"), MeshActor , USpeckleMesh::StaticClass()); - } - - return ActorInstance; -} - -AActor* ASpeckleUnrealManager::CreatePointCloud(const TSharedPtr Obj) -{ - const FString ObjId = Obj->GetStringField("id"); - UE_LOG(LogTemp, Log, TEXT("Creating PointCloud for object %s"), *ObjId); - - - UPointCloud* Base = NewObject(); - Base->Parse(Obj, this); - - AActor* ActorInstance = World->SpawnActor(PointCloudActor); - - if(ActorInstance->GetClass()->ImplementsInterface(USpecklePointCloud::StaticClass())) - { - FEditorScriptExecutionGuard ScriptGuard; - ISpecklePointCloud::Execute_SetData(ActorInstance, Base, this); - } - else - { - UE_LOG(LogTemp, Warning, TEXT("%s does not implement $s interface"), PointCloudActor , USpecklePointCloud::StaticClass()); - } - - return ActorInstance; -} - - - -ASpeckleUnrealActor* ASpeckleUnrealManager::CreateBlockInstance(const TSharedPtr Obj) -{ - //Transform - const FString Units = Obj->GetStringField("units"); - const float ScaleFactor = ParseScaleFactor(Units); - - const TArray>* TransformData; - if(!Obj->TryGetArrayField("transform", TransformData)) return nullptr; - - - FMatrix TransformMatrix; - for(int32 Row = 0; Row < 4; Row++) - for(int32 Col = 0; Col < 4; Col++) - { - TransformMatrix.M[Row][Col] = TransformData->operator[](Row * 4 + Col)->AsNumber(); - } - TransformMatrix = TransformMatrix.GetTransposed(); - TransformMatrix.ScaleTranslation(FVector(ScaleFactor)); - - //Block Instance - const FString ObjectId = Obj->GetStringField("id"), SpeckleType = Obj->GetStringField("speckle_type"); - - ASpeckleUnrealActor* BlockInstance = World->SpawnActor(ASpeckleUnrealActor::StaticClass(), FTransform(TransformMatrix)); - - - //Block Definition - const TSharedPtr* BlockDefinitionReference; - if(!Obj->TryGetObjectField("blockDefinition", BlockDefinitionReference)) return nullptr; - - const FString RefID = BlockDefinitionReference->operator->()->GetStringField("referencedId"); - - const TSharedPtr BlockDefinition = SpeckleObjects[RefID]; - - //For now just recreate mesh, eventually we should use instanced static mesh - const auto Geometries = BlockDefinition->GetArrayField("geometry"); - - for(const auto Child : Geometries) - { - const TSharedPtr MeshReference = Child->AsObject(); - const FString MeshID = MeshReference->GetStringField("referencedId"); - - //It is important that ParentObject is the BlockInstance not the BlockDefinition to keep NativeIDs of meshes unique between Block Instances - ImportObjectFromCache(BlockInstance, SpeckleObjects[MeshID], Obj); - } - - - return BlockInstance; -} - - - diff --git a/Source/SpeckleUnreal/Private/SpeckleUnrealManager.cpp b/Source/SpeckleUnreal/Private/SpeckleUnrealManager.cpp index 27083ec..1ff5aa2 100644 --- a/Source/SpeckleUnreal/Private/SpeckleUnrealManager.cpp +++ b/Source/SpeckleUnreal/Private/SpeckleUnrealManager.cpp @@ -1,194 +1,146 @@ + #include "SpeckleUnrealManager.h" -#include "Kismet/GameplayStatics.h" +#include "ReceiveSelectionComponent.h" +#include "API/Operations/ReceiveOperation.h" +#include "Transports/MemoryTransport.h" +#include "Transports/ServerTransport.h" +#include "LogSpeckle.h" +#include "API/SpeckleSerializer.h" +#include "Conversion/SpeckleConverterComponent.h" +#include "Misc/ScopedSlowTask.h" +#include "Objects/Base.h" +#include "Mixpanel.h" +#include "API/SpeckleAPIFunctions.h" +#include "Engine/Engine.h" + +#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule" + // Sets default values ASpeckleUnrealManager::ASpeckleUnrealManager() { - static ConstructorHelpers::FObjectFinder SpeckleMaterial(TEXT("Material'/SpeckleUnreal/SpeckleMaterial.SpeckleMaterial'")); - static ConstructorHelpers::FObjectFinder SpeckleGlassMaterial(TEXT("Material'/SpeckleUnreal/SpeckleGlassMaterial.SpeckleGlassMaterial'")); - - //When the object is constructed, Get the HTTP module - Http = &FHttpModule::Get(); - - SetRootComponent(CreateDefaultSubobject("Root")); - RootComponent->SetRelativeScale3D(FVector(-1,1,1)); - RootComponent->SetMobility(EComponentMobility::Static); - - DefaultMeshMaterial = SpeckleMaterial.Object; - BaseMeshOpaqueMaterial = SpeckleMaterial.Object; - BaseMeshTransparentMaterial = SpeckleGlassMaterial.Object; + SetRootComponent(CreateDefaultSubobject(TEXT("Root"))); + RootComponent->SetRelativeScale3D(FVector(1,1,1)); + RootComponent->SetMobility(EComponentMobility::Static); + + Converter = CreateDefaultSubobject(FName("Converter")); + ReceiveSelection = CreateDefaultSubobject(FName("ReceiveSelection")); + KeepCache = true; + DisplayProgressBar = true; } -// Called when the game starts or when spawned void ASpeckleUnrealManager::BeginPlay() { Super::BeginPlay(); - - if (ImportAtRuntime) - ImportSpeckleObject(); - + + if(ImportAtRuntime) Receive(); } -/*Import the Speckle object*/ -void ASpeckleUnrealManager::ImportSpeckleObject() +void ASpeckleUnrealManager::Receive() { - const FString UserAgent = FString::Printf(TEXT("Unreal Engine (%s) / %d.%d.%d"), *UGameplayStatics::GetPlatformName(), ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION, ENGINE_PATCH_VERSION); - -#if !SUPPRESS_SPECKLE_ANALYTICS - + // Check object to receive has been specified properly + FString StatusMessage; + if(!ReceiveSelection->IsSelectionComplete(StatusMessage)) + { + HandleError(StatusMessage); + return; + } - const FString HostApplication = FString::Printf(TEXT("Unreal%%20Engine%%20%d"), ENGINE_MAJOR_VERSION); - const FString Action = "receive/manual"; - FString SpeckleUserID = "No%20SUUID"; - -#if PLATFORM_WINDOWS - const FString UserPath = UKismetSystemLibrary::GetPlatformUserDir().LeftChop(10); //remove "Documents/" - const FString Dir = FString::Printf(TEXT("%sAppData/Roaming/Speckle/suuid"), *UserPath); - FFileHelper::LoadFileToString(SpeckleUserID, *Dir); -#endif - //TODO MACOS - - //Track page view - const FString ViewURL = FString::Printf( - TEXT("https://speckle.matomo.cloud/matomo.php?idsite=2&rec=1&apiv=1&uid=%s&action_name=%s&url=http://connectors/%s/%s&urlref=http://connectors/%s/%s&_cvar=%%7B%%22hostApplication%%22:%%20%%22%s%%22%%7D"), - *SpeckleUserID, - *Action, - *HostApplication, - *Action, - *HostApplication, - *Action, - *HostApplication - ); - - const FHttpRequestRef ViewTrackingRequest = Http->CreateRequest(); - ViewTrackingRequest->SetVerb("POST"); - ViewTrackingRequest->SetURL(ViewURL); - ViewTrackingRequest->SetHeader("User-Agent", UserAgent); - ViewTrackingRequest->ProcessRequest(); - - //Track receive action - const FString EventURL = FString::Printf( - TEXT("https://speckle.matomo.cloud/matomo.php?idsite=2&rec=1&apiv=1&uid=%s&_cvar=%%7B%%22hostApplication%%22:%%20%%22%s%%22%%7D&e_c=%s&e_a=%s"), - *SpeckleUserID, - *HostApplication, - *HostApplication, - *Action - ); - - const FHttpRequestRef EventTrackingRequest = Http->CreateRequest(); - EventTrackingRequest->SetVerb("POST"); - EventTrackingRequest->SetURL(EventURL); - EventTrackingRequest->SetHeader("User-Agent", UserAgent); + // Delete all actors from previous receive operations + DeleteObjects(); - EventTrackingRequest->ProcessRequest(); + const FString ServerUrl = ReceiveSelection->ServerUrl; + const FString AuthToken = ReceiveSelection->AuthToken; + const FString StreamId = ReceiveSelection->StreamId; + const FString ObjectId = ReceiveSelection->ObjectId; -#endif + FAnalytics::TrackEvent( ServerUrl, TEXT("NodeRun"), TMap { {TEXT("name"), StaticClass()->GetName() }, {TEXT("worldType"), FString::FromInt(GetWorld()->WorldType)}}); + FString Message = FString::Printf(TEXT("Fetching Objects from Speckle Server: %s"), *ServerUrl); + PrintMessage(Message); + // Setup network transports + UServerTransport* ServerTransport = UServerTransport::CreateServerTransport(ServerUrl, StreamId, AuthToken); - const FString url = ServerUrl + "/objects/" + StreamID + "/" + ObjectID; - GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, "[Speckle] Downloading: " + url); - - const 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->SetHeader("User-Agent", UserAgent); - 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) + if(!KeepCache && LocalObjectCache) { - GEngine->AddOnScreenDebugMessage(1, 5.0f, FColor::Red, FString::Printf(TEXT("Error response. Response code %d"), responseCode)); - return; + LocalObjectCache.GetObjectRef()->ConditionalBeginDestroy(); + LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport(); } + if(!LocalObjectCache) LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport(); - FString response = Response->GetContentAsString(); + // Setup delegate callbacks + FTransportErrorDelegate ErrorDelegate; + ErrorDelegate.BindUObject(this, &ASpeckleUnrealManager::HandleError); + FTransportCopyObjectCompleteDelegate CompleteDelegate; + CompleteDelegate.BindUObject(this, &ASpeckleUnrealManager::HandleReceive, DisplayProgressBar); - // 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 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 (const auto& line : lines) + // Send request for objects + ServerTransport->CopyObjectAndChildren(ObjectId, LocalObjectCache, CompleteDelegate, ErrorDelegate); + + // Read receipt (if receiving a commit object) + FSpeckleCommit Commit; + if(ReceiveSelection->TryGetSelectedCommit(Commit)) { - FString objectId, objectJson; - if (!line.Split("\t", &objectId, &objectJson)) - continue; - TSharedPtr jsonObject; - TSharedRef> jsonReader = TJsonReaderFactory<>::Create(objectJson); - if (!FJsonSerializer::Deserialize(jsonReader, jsonObject)) - continue; - - SpeckleObjects.Add(objectId, jsonObject); + //TODO read receipt + USpeckleAPIFunctions::CommitReceived(Commit); } +} - GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, FString::Printf(TEXT("[Speckle] Converting %d objects..."), lineCount)); - //World Units setup - WorldToCentimeters = 1; //Default value of 1uu = 1cm - AWorldSettings* WorldSettings; - if(IsValid(World = GetWorld() ) - && IsValid(WorldSettings = World->GetWorldSettings()) ) +void ASpeckleUnrealManager::HandleReceive(TSharedPtr RootObject, bool DisplayProgress) +{ + if(RootObject == nullptr) return; + + const UBase* Res = USpeckleSerializer::DeserializeBase(RootObject, LocalObjectCache); + if(IsValid(Res)) { - WorldToCentimeters = WorldSettings->WorldToMeters / 100; + Converter->RecursivelyConvertToNative(this, Res, LocalObjectCache, DisplayProgress, Actors); + + FString Message = FString::Printf(TEXT("Converted %d Actors"), Actors.Num()); + PrintMessage(Message); } - - - ImportObjectFromCache(this, SpeckleObjects[ObjectID]); - - for (const auto& m : CreatedObjectsCache) + else { - if(AActor* a = Cast(m)) - a->Destroy(); - else - m->ConditionalBeginDestroy(); + FString Id; + RootObject->TryGetStringField(TEXT("id"), Id); + FString Message = FString::Printf(TEXT("Failed to deserialise root object: %s"), *Id); + HandleError(Message); } +} - CreatedObjectsCache = InProgressObjectsCache; - InProgressObjectsCache.Empty(); - - GEngine->AddOnScreenDebugMessage(0, 5.0f, FColor::Green, FString::Printf(TEXT("[Speckle] Objects imported successfully. Created %d Actors"), CreatedObjectsCache.Num())); - +void ASpeckleUnrealManager::HandleError(FString& Message) +{ + PrintMessage(Message, true); } +void ASpeckleUnrealManager::PrintMessage(FString& Message, bool IsError) const +{ + if(IsError) + { + UE_LOG(LogSpeckle, Error, TEXT("%s"), *Message); + } + else + { + UE_LOG(LogSpeckle, Log, TEXT("%s"), *Message); + } + + FColor Color = IsError? FColor::Red : FColor::Green; + GEngine->AddOnScreenDebugMessage(0, 5.0f, Color, Message); +} void ASpeckleUnrealManager::DeleteObjects() { - ConvertedMaterials.Empty(); + Converter->FinishConversion(); - for (const auto& m : CreatedObjectsCache) + for (AActor* a : Actors) { - if(AActor* a = Cast(m)) - a->Destroy(); - else - m->ConditionalBeginDestroy(); - + if(IsValid(a)) a->Destroy(); } - CreatedObjectsCache.Empty(); + Actors.Empty(); } + +#undef LOCTEXT_NAMESPACE \ No newline at end of file diff --git a/Source/SpeckleUnreal/Private/Tests/ReceiveSelectionComponentTest.cpp b/Source/SpeckleUnreal/Private/Tests/ReceiveSelectionComponentTest.cpp new file mode 100644 index 0000000..4dcf6be --- /dev/null +++ b/Source/SpeckleUnreal/Private/Tests/ReceiveSelectionComponentTest.cpp @@ -0,0 +1,77 @@ + +#include "LogSpeckle.h" +#include "Misc/AutomationTest.h" +#include "ReceiveSelectionComponent.h" +#include "Tests/AutomationCommon.h" + +#if WITH_DEV_AUTOMATION_TESTS + + +class UMock : public UReceiveSelectionComponent +{ + friend class FReceiveSelectionComponentTest; + friend class FCheckValidSelection; + friend class FCheckLimitMatch; +}; + +DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckValidSelection, FAutomationTestBase*, Test, UMock*, SelectionComponent); +bool FCheckValidSelection::Update() +{ + const UMock* s = SelectionComponent; + + Test->TestTrue(TEXT("Account valid on set"), s->IsAccountValid); + Test->TestTrue(TEXT("Stream valid on set"), s->IsStreamValid); + Test->TestTrue(TEXT("Branch valid on set"), s->IsBranchValid); + Test->TestTrue(TEXT("Commit valid on set"), s->IsCommitValid); + return true; +} + +DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckLimitMatch, FAutomationTestBase*, Test, UMock*, SelectionComponent); +bool FCheckLimitMatch::Update() +{ + const UMock* s = SelectionComponent; + + Test->TestTrue(TEXT("Fetched streams is less than limit"), s->Streams.Num() <= s->Limit); + Test->TestTrue(TEXT("Fetched branches is less than limit"), s->Branches.Num() <= s->Limit); + Test->TestTrue(TEXT("Fetched commits is less than limit"), s->Commits.Num() <= s->Limit); + return true; +} + + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FReceiveSelectionComponentTest, "SpeckleUnreal.ReceiveSelectionComponentTest", EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FReceiveSelectionComponentTest::RunTest(const FString& Parameters) +{ +#ifdef TEST_AUTH_TOKEN + UMock* s = NewObject(); + + + //Test initialisation + TestFalse(TEXT("Account valid on initialise"), s->IsAccountValid); + TestFalse(TEXT("Stream valid on initialise"), s->IsStreamValid); + TestFalse(TEXT("Branch valid on initialise"), s->IsBranchValid); + TestFalse(TEXT("Commit valid on initialise"), s->IsCommitValid); + + + s->AuthToken = TEST_AUTH_TOKEN; + s->ServerUrl = TEXT("https://latest.speckle.systems"); + s->bManualMode = false; + s->Refresh(); + + //wait 5 seconds for HTTP requests to finish + ADD_LATENT_AUTOMATION_COMMAND(FWaitLatentCommand(5.0f)); + + ADD_LATENT_AUTOMATION_COMMAND(FCheckValidSelection(this, s)); + ADD_LATENT_AUTOMATION_COMMAND(FCheckLimitMatch(this, s)); + + return true; + +#else + TestTrue(TEXT("TEST_AUTH_TOKEN definition exists"), false); + + return false; +#endif + +} +#endif + diff --git a/Source/SpeckleUnreal/Private/Tests/Transports/MemoryTransportTest.cpp b/Source/SpeckleUnreal/Private/Tests/Transports/MemoryTransportTest.cpp new file mode 100644 index 0000000..1f46605 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Tests/Transports/MemoryTransportTest.cpp @@ -0,0 +1,61 @@ + +#include "Misc/AutomationTest.h" +#include "Objects/Base.h" +#include "Transports/MemoryTransport.h" + + +#if WITH_DEV_AUTOMATION_TESTS + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMemoryTransportTest, "SpeckleUnreal.Transports.MemoryTransport", EAutomationTestFlags::EditorContext | EAutomationTestFlags::SmokeFilter) + + +bool FMemoryTransportTest::RunTest(const FString& Parameters) +{ + UMemoryTransport* Transport = UMemoryTransport::CreateEmptyMemoryTransport(); + // Test Construction + { + TestNotNull(TEXT("Constructed object"), Transport); + TestTrue(TEXT("Constructed object is valid"), IsValid(Transport)); + } + + TSharedPtr MockObj = MakeShareable(new FJsonObject()); + FString TestId = TEXT("testidlalalala"); + FString TestPayloadName = TEXT("Playload"); + FString TestPayload = TEXT("MyPayloadValue!"); + MockObj->SetStringField(TestPayloadName, TestPayload); + + // Test Save + { + Transport->SaveObject(TestId, MockObj); + TestTrue(TEXT("Transport with save object to HasObject"), Transport->HasObject(TestId)); + + auto Value = Transport->GetSpeckleObject(TestId); + TestNotNull(TEXT("Return of getting saved object"), Value.Get()); + TestEqual(TEXT("Return of getting saved object"), Value, MockObj); + TestTrue(TEXT("Returned object to have payload"), Value->HasField(TestPayloadName)); + TestEqual(TEXT("Returned object's playload"), Value->GetStringField(TestPayloadName), TestPayload); + } + + // Test Ids are missing + { + TArray MissingIds = { + TEXT("NoObjectsWithThisId"), + TEXT("testidla"), + TEXT("testidlalalalaextrala"), + TEXT("testidrararara"), + TEXT(""), + }; + + for(const FString& Id : MissingIds) + { + TestFalse(TEXT("transport has unknown id -") + Id, Transport->HasObject(Id)); + auto ValueM = Transport->GetSpeckleObject(Id); + TestNull(TEXT("return of unknown id -") + Id, ValueM.Get()); + } + } + + return true; +} + + +#endif diff --git a/Source/SpeckleUnreal/Private/Transports/MemoryTransport.cpp b/Source/SpeckleUnreal/Private/Transports/MemoryTransport.cpp new file mode 100644 index 0000000..27ba7c9 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Transports/MemoryTransport.cpp @@ -0,0 +1,21 @@ + +#include "Transports/MemoryTransport.h" + +#include "LogSpeckle.h" + +bool UMemoryTransport::HasObject(const FString& ObjectId) const +{ + return SpeckleObjects.Contains(ObjectId); +} + + +TSharedPtr UMemoryTransport::GetSpeckleObject(const FString& ObjectId) const +{ + return SpeckleObjects.FindRef(ObjectId); +} + +void UMemoryTransport::SaveObject(const FString& ObjectId, const TSharedPtr SerializedObject) +{ + SpeckleObjects.Add(ObjectId, SerializedObject); + UE_LOG(LogSpeckle, Verbose, TEXT("Added %s to in memory transport, now %d objects total "), *ObjectId, SpeckleObjects.Num()); +} diff --git a/Source/SpeckleUnreal/Private/Transports/ServerTransport.cpp b/Source/SpeckleUnreal/Private/Transports/ServerTransport.cpp new file mode 100644 index 0000000..67ac9f9 --- /dev/null +++ b/Source/SpeckleUnreal/Private/Transports/ServerTransport.cpp @@ -0,0 +1,267 @@ + +#include "Transports/ServerTransport.h" + +#include "LogSpeckle.h" +#include "Mixpanel.h" +#include "Runtime/Launch/Resources/Version.h" +#include "JsonObjectConverter.h" +#include "HttpModule.h" +#include "Interfaces/IHttpRequest.h" +#include "Interfaces/IHttpResponse.h" +#include "Policies/CondensedJsonPrintPolicy.h" + + +TSharedPtr UServerTransport::GetSpeckleObject(const FString& ObjectId) const +{ + unimplemented(); + return nullptr; +} + +void UServerTransport::SaveObject(const FString& ObjectId, const TSharedPtr SerializedObject) +{ + unimplemented(); //TODO implement +} + +bool UServerTransport::HasObject(const FString& ObjectId) const +{ + unimplemented(); //TODO implement + return false; +} + +void UServerTransport::HandleRootObjectResponse(const FString& RootObjSerialized, + TScriptInterface TargetTransport, + const FString& ObjectId) const +{ + TSharedPtr RootObj; + if(!LoadJson(RootObjSerialized, RootObj)) + { + FString Message = FString::Printf(TEXT("A Root Object %s was recieved but was invalid and could not be deserialied"), *ObjectId); + InvokeOnError(Message); + return; + } + + TargetTransport->SaveObject(ObjectId, RootObj); + + // Find children are not already in the target transport + const auto Closures = RootObj->GetObjectField(TEXT("__closure"))->Values; + + TArray ChildrenIds; + Closures.GetKeys(ChildrenIds); + TArray NewChildrenIds; + for(const FString& Id : ChildrenIds) + { + if(TargetTransport->HasObject(Id)) continue; + + NewChildrenIds.Add(Id); + } + + + FetchChildren(TargetTransport, ObjectId, NewChildrenIds); +} + + +void UServerTransport::CopyObjectAndChildren(const FString& ObjectId, + TScriptInterface TargetTransport, + const FTransportCopyObjectCompleteDelegate& OnCompleteAction, + const FTransportErrorDelegate& OnErrorAction) +{ + this->OnComplete = OnCompleteAction; + this->OnError = OnErrorAction; + + // Create Request for Root Object + const FHttpRequestRef Request = FHttpModule::Get().CreateRequest(); + const FString Endpoint = FString::Printf(TEXT("%s/objects/%s/%s/single"), *ServerUrl, *StreamId, *ObjectId); + Request->SetVerb(TEXT("GET")); + Request->SetURL(Endpoint); + Request->SetHeader(TEXT("Accept"), TEXT("text/plain")); + if(!AuthToken.IsEmpty()) + Request->SetHeader(TEXT("Authorization"),FString::Printf(TEXT("Bearer %s"), *AuthToken)); + Request->SetHeader(TEXT("apollographql-client-name"), TEXT("Unreal Engine")); + Request->SetHeader(TEXT("apollographql-client-version"), SPECKLE_CONNECTOR_VERSION); + + // Response Callback +#if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3 + auto ResponseHandler = [=, this](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable +#else + auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable +#endif + + { + if(!bWasSuccessful) + { + FString Message = FString::Printf(TEXT("Request for root object at %s was unsuccessful: %s"), *Response->GetURL(), *Response->GetContentAsString()); + InvokeOnError(Message); + return; + } + + const int32 ResponseCode = Response->GetResponseCode(); + if (ResponseCode != 200) + { + FString Message = FString::Printf(TEXT("Request for root object at %s failed with HTTP response %d"), *Response->GetURL(), ResponseCode); + InvokeOnError(Message); + return; + } + + HandleRootObjectResponse(Response->GetContentAsString(), TargetTransport, ObjectId); + }; + + Request->OnProcessRequestComplete().BindLambda(ResponseHandler); + + // Send request + const bool RequestSent = Request->ProcessRequest(); + + if(!RequestSent) + { + FString Message = FString::Printf(TEXT("Request for root object at %s failed: \nHTTP request failed to start"), *Endpoint); + InvokeOnError(Message); + return; + } + UE_LOG(LogSpeckle, Verbose, TEXT("GET Request sent for root object at %s, awaiting response"), *Endpoint ); + FAnalytics::TrackEvent(ServerUrl, "Receive"); +} + +void UServerTransport::FetchChildren(TScriptInterface TargetTransport, const FString& ObjectId, + const TArray& ChildrenIds, int32 CStart) const +{ + // Check if all children have been fetched + if(ChildrenIds.Num() <= CStart) + { + UE_LOG(LogSpeckle, Log, TEXT("Finished fetching child Speckle objects")); + ensureAlwaysMsgf(this->OnComplete.ExecuteIfBound(TargetTransport->GetSpeckleObject(ObjectId)), + TEXT("Complete handler was not bound properly")); + return; + } + + // Assemble list of ids to ask for in this request + // We want to avoid making requests too large + const int32 CEnd = FGenericPlatformMath::Min(ChildrenIds.Num(), CStart + MaxNumberOfObjectsPerRequest); + FString ChildrenIdsString; + { + auto Writer = TJsonWriterFactory>::Create(&ChildrenIdsString); + Writer->WriteArrayStart(); + for (int32 i = CStart; i < CEnd; i++) + { + Writer->WriteValue(ChildrenIds[i]); + } Writer->WriteArrayEnd(); + Writer->Close(); + } + + FString Body; + { + auto Writer = TJsonWriterFactory>::Create(&Body); + Writer->WriteObjectStart(); + Writer->WriteValue(TEXT("objects"), ChildrenIdsString); + Writer->WriteObjectEnd(); + Writer->Close(); + } + + // Create Request + const FHttpRequestRef Request = FHttpModule::Get().CreateRequest(); + { + const FString EndPoint = FString::Printf(TEXT("%s/api/getobjects/%s"), *ServerUrl, *StreamId); + Request->SetVerb(TEXT("POST")); + Request->SetURL(EndPoint); + Request->SetHeader(TEXT("Accept"), TEXT("text/plain")); + if(!AuthToken.IsEmpty()) + Request->SetHeader(TEXT("Authorization"), FString::Printf(TEXT("Bearer %s"), *AuthToken)); + Request->SetHeader(TEXT("Content-Type"), TEXT("application/json")); + Request->SetContentAsString(Body); + } + + // Response Callback +#if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3 + auto ResponseHandler = [=, this](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable +#else + auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable +#endif + { + // Request Fail + if(!bWasSuccessful) + { + FString Message = FString::Printf(TEXT("Request for children of root object %s/%s failed: %s"), + *StreamId, *ObjectId, *Response->GetContentAsString()); + InvokeOnError(Message); + return; + } + + // Any HTTP Fail + const int32 ResponseCode = Response->GetResponseCode(); + if (ResponseCode != 200) + { + FString Message = FString::Printf( + TEXT("Request for children of root object %s/%s failed:\nHTTP response %d"), + *StreamId, *ObjectId, ResponseCode); + InvokeOnError(Message); + return; + } + + // Success: Start parsing + TArray Lines; + const int32 LineCount = SplitLines(Response->GetContentAsString(), Lines); + + UE_LOG(LogSpeckle, Verbose, TEXT("Parsing %d downloaded objects..."), LineCount) + + // Warning: Fewer/More objects then expected + if(LineCount != CEnd - CStart) + { + UE_LOG(LogSpeckle, Warning, TEXT("Requested %d objects, but received %d"), CEnd - CStart, LineCount); + } + + // Load JSON as objects + for (const FString& Line : Lines) + { + FString Id, ObjectJson; + if (!Line.Split("\t", &Id, &ObjectJson)) + continue; + + TSharedPtr JsonObject; + if(!LoadJson(ObjectJson, JsonObject)) continue; + + TargetTransport->SaveObject(Id, JsonObject); + } + + UE_LOG(LogSpeckle, Log, TEXT("Processed %d/%d Child objects"), CEnd, ChildrenIds.Num()) + + //Iterate again for any missing children + FetchChildren(TargetTransport, ObjectId, ChildrenIds, CEnd); + }; + + Request->OnProcessRequestComplete().BindLambda(ResponseHandler); + + // Send request for children + const bool RequestSent = Request->ProcessRequest(); + + if(!RequestSent) + { + FString Message = FString::Printf(TEXT("Failed to fetch children of root object %s/%s:\nHTTP request failed to start"), *StreamId, *ObjectId); + InvokeOnError(Message); + return; + } + + + UE_LOG(LogSpeckle, Verbose, TEXT("Requesting %d child objects"), CEnd - CStart); +} + + +void UServerTransport::InvokeOnError(FString& Message) const +{ + ensureAlwaysMsgf(this->OnError.ExecuteIfBound(Message), TEXT("ServerTransport: Unhandled error - %s"), *Message); +} + +int32 UServerTransport::SplitLines(const FString& Content, TArray& OutLines) +{ + int32 LineCount = 0; + for (const TCHAR* ptr = *Content; *ptr; ptr++) + if (*ptr == '\n') + LineCount++; + OutLines.Reserve(LineCount); + Content.ParseIntoArray(OutLines, TEXT("\n"), true); + return LineCount; +} + +bool UServerTransport::LoadJson(const FString& StringJson, TSharedPtr& OutJsonObject) +{ + TSharedRef> Reader = TJsonReaderFactory<>::Create(StringJson); + return FJsonSerializer::Deserialize(Reader, OutJsonObject); +} + diff --git a/Source/SpeckleUnreal/Public/API/ClientAPI.h b/Source/SpeckleUnreal/Public/API/ClientAPI.h new file mode 100644 index 0000000..ba326a8 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/ClientAPI.h @@ -0,0 +1,52 @@ + +#pragma once + +#include "Interfaces/IHttpRequest.h" +#include "Dom/JsonObject.h" + +DECLARE_DELEGATE_OneParam(FErrorDelegate, const FString&); +DECLARE_DELEGATE_OneParam(FAPIResponceDelegate, const FString&); + +/** +* C++ wrapper of Speckle's GraphQL API +* Encapsulates sending HTTP requests with GraphQL Queries for specific resources +* +* Used to send GraphQL requests for commits, branches, streams, user info, collaborators etc. +* +* See `API/Operations` for usage examples +*/ +class FClientAPI +{ + + public: + + /** + * Creates and sends a graphql query to the specified url. + * Will check HTTP response for errors, + * and unpack the response "data" object. + * @param ServerUrl URL of the Speckle Server endpoint + * @param AuthToken + * @param ResponsePropertyName Property name of the requested object. This will be the first name in the query (e.g. "stream", "streams", "user", etc) + * @param PostPayload The POST payload containing the GraphQL request + * @param RequestLogName Friendly name for this request (for error handling and logging) + * @param OnCompleteAction Callback invoked on successful completion of the request, with the request object (as a JSON string) + * @param OnErrorAction Callback invoked on any fatal error with, the error message. + */ + static void MakeGraphQLRequest(const FString& ServerUrl, const FString& AuthToken, const FString& ResponsePropertyName, + const FString& PostPayload, const FString& RequestLogName, + const FAPIResponceDelegate OnCompleteAction, const FErrorDelegate OnErrorAction); + + + +//protected: + + /// Helper function for creating post requests with a GraphQL query + static FHttpRequestRef CreatePostRequest(const FString& ServerUrl, FString AuthToken, const FString& PostPayload, + const FString& Encoding = TEXT("gzip")); + + static bool GetResponseAsJSON(const FHttpResponsePtr Response, const FString& RequestLogName, TSharedPtr& OutObject, const TFunctionRef OnErrorAction); + + static bool CheckForOperationErrors(const TSharedPtr GraphQLResponse, FString& OutErrorMessage); + static bool CheckRequestFailed(bool bWasSuccessful, FHttpResponsePtr Response, const FString& RequestName, const TFunctionRef OnErrorAction); + + }; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/API/Models/SpeckleBranch.h b/Source/SpeckleUnreal/Public/API/Models/SpeckleBranch.h new file mode 100644 index 0000000..3556062 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Models/SpeckleBranch.h @@ -0,0 +1,45 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "SpeckleCommit.h" +#include "SpeckleBranch.generated.h" + +/* +* GraphQL model for Branch data +* Properties are only when they explicitly requested (through the GraphQL request) +* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs +*/ +USTRUCT(BlueprintType) +struct FSpeckleBranch +{ + GENERATED_BODY() + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString ID; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Name; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Description; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FSpeckleCommits Commits; + +}; + +USTRUCT(BlueprintType) +struct FSpeckleBranches +{ + GENERATED_BODY(); + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + int32 TotalCount = 0; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Cursor; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + TArray Items; +}; diff --git a/Source/SpeckleUnreal/Public/API/Models/SpeckleCollaborator.h b/Source/SpeckleUnreal/Public/API/Models/SpeckleCollaborator.h new file mode 100644 index 0000000..1af2684 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Models/SpeckleCollaborator.h @@ -0,0 +1,29 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "SpeckleCollaborator.generated.h" + +/* +* GraphQL model for Collaborator data +* Properties are only when they explicitly requested (through the GraphQL request) +* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs +*/ +USTRUCT(BlueprintType) +struct FSpeckleCollaborator +{ + GENERATED_BODY() + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Id; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Name; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Role; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Avatar; + +}; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/API/Models/SpeckleCommit.h b/Source/SpeckleUnreal/Public/API/Models/SpeckleCommit.h new file mode 100644 index 0000000..ad2a6d6 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Models/SpeckleCommit.h @@ -0,0 +1,65 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "SpeckleCommit.generated.h" + +/* +* GraphQL model for Commit data +* Properties are only when they explicitly requested (through the GraphQL request) +* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs +*/ +USTRUCT(BlueprintType) +struct FSpeckleCommit +{ + GENERATED_BODY(); + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString ID; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Message; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString BranchName; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString AuthorName; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString AuthorId; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString AuthorAvatar; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString CreatedAt; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString SourceApplication; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models", DisplayName="Referenced Object Id") + FString ReferencedObject; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString TotalChildrenCount; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + TArray Parents; + +}; + +USTRUCT(BlueprintType) +struct FSpeckleCommits +{ + GENERATED_BODY(); + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + int32 TotalCount = 0; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Cursor; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + TArray Items; +}; diff --git a/Source/SpeckleUnreal/Public/API/Models/SpeckleStream.h b/Source/SpeckleUnreal/Public/API/Models/SpeckleStream.h new file mode 100644 index 0000000..dfe67e6 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Models/SpeckleStream.h @@ -0,0 +1,77 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "SpeckleBranch.h" +#include "SpeckleCollaborator.h" + +#include "SpeckleStream.generated.h" + +/* +* GraphQL model for Stream data +* Properties are only when they explicitly requested (through the GraphQL request) +* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs +*/ +USTRUCT(BlueprintType) +struct FSpeckleStream +{ + GENERATED_BODY() + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models", DisplayName="Stream Id") + FString ID; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FString Name; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FString Description; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + bool IsPublic = false; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FString Role; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FString CreatedAt; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FString UpdatedAt; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FString FavoritedDate; + + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + TArray Collaborators; + + // Object properties are only set if explicitly requested by a custom GraphQL request + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FSpeckleBranches Branches; + + // Object properties are only set if explicitly requested by a custom GraphQL request + UPROPERTY(BlueprintReadOnly, DisplayName="Branch (Request Only)", Category="Speckle|API Models", AdvancedDisplay) + FSpeckleBranch Branch; + + // Object properties are only set if explicitly requested by a custom GraphQL request + UPROPERTY(BlueprintReadOnly, DisplayName="Commit (Request Only)", Category="Speckle|API Models", AdvancedDisplay) + FSpeckleCommit Commit; + + // Object properties are only set if explicitly requested by a custom GraphQL request + UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models") + FSpeckleCommits Commits; +}; + +USTRUCT(BlueprintType) +struct FSpeckleStreams +{ + GENERATED_BODY(); + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + int32 TotalCount = 0; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Cursor; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + TArray Items; +}; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/API/Models/SpeckleUser.h b/Source/SpeckleUnreal/Public/API/Models/SpeckleUser.h new file mode 100644 index 0000000..e8d9567 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Models/SpeckleUser.h @@ -0,0 +1,47 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "SpeckleStream.h" +#include "SpeckleUser.generated.h" + +/* +* GraphQL model for User data +* Properties are only when they explicitly requested (through the GraphQL request) +* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs +*/ +USTRUCT(BlueprintType) +struct FSpeckleUser +{ + GENERATED_BODY() + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Id; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Email; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Name; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Bio; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Company; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Avatar; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + bool Verified = false; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FString Role; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FSpeckleStreams Streams; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models") + FSpeckleStreams FavoriteStreams; +}; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/API/Operations/ReceiveOperation.h b/Source/SpeckleUnreal/Public/API/Operations/ReceiveOperation.h new file mode 100644 index 0000000..d1e0890 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Operations/ReceiveOperation.h @@ -0,0 +1,58 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintAsyncActionBase.h" + +#include "ReceiveOperation.generated.h" + +class ITransport; +class UBase; +class FJsonObject; + +DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FRecieveOperationHandler, UBase*, RootBase, FString, ErrorMessage); + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API UReceiveOperation : public UBlueprintAsyncActionBase +{ + GENERATED_BODY() + +public: + + UPROPERTY(BlueprintAssignable) + FRecieveOperationHandler OnReceiveSuccessfully; + + /// Called when the total number of children is known + //UPROPERTY(BlueprintAssignable) + //FRecieveOperationHandler OnChildrenCountKnown; + + /// Called when some deserilization progress is made and TotalConverted has changed + //UPROPERTY(BlueprintAssignable) + //FRecieveOperationHandler OnProgress; + + /// Called when receive operation has aborted due to some error + UPROPERTY(BlueprintAssignable) + FRecieveOperationHandler OnError; + + UFUNCTION(BlueprintCallable, BlueprintInternalUseOnly, Category = "Speckle|Operations", meta = (WorldContext = "WorldContextObject")) + static UReceiveOperation* ReceiveOperation(UObject* WorldContextObject, const FString& ObjectId, + TScriptInterface RemoteTransport, TScriptInterface LocalTransport); + + + virtual void Activate() override; + + +protected: + void Receive(); + + FString ObjectId; + TScriptInterface RemoteTransport; + TScriptInterface LocalTransport; + + void HandleReceive(TSharedPtr Object); + + void HandleError(FString& Message); +}; diff --git a/Source/SpeckleUnreal/Public/API/Operations/SpeckleStreamAPIOperation.h b/Source/SpeckleUnreal/Public/API/Operations/SpeckleStreamAPIOperation.h new file mode 100644 index 0000000..70bd746 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/Operations/SpeckleStreamAPIOperation.h @@ -0,0 +1,62 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintAsyncActionBase.h" + +#include "SpeckleStreamAPIOperation.generated.h" + + +DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FAPIResponseHandler, FString, JsonResponse, FString, ErrorMessage); + +/** + * Allows sending GraphQL queries to the Speckle GraphQL API + * + */ +UCLASS() +class SPECKLEUNREAL_API USpeckleStreamAPIOperation : public UBlueprintAsyncActionBase +{ + GENERATED_BODY() + +public: + + UPROPERTY(BlueprintAssignable) + FAPIResponseHandler OnReceiveSuccessfully; + + UPROPERTY(BlueprintAssignable) + FAPIResponseHandler OnError; + + /** + * Sends an GraphQL queries to a speckle server's "/graphql" endpoint + * E.g. for fetching stream/branch/commit/user info. + * + * @param ServerUrl The URL of the Speckle server + * @param AuthToken The auth token of the user (optional for unprivilaged requests) + * @param GraphQlQuery The GraphQl query (starting with `query{ }`) + * @param ResponsePropertyName The name of the root property being requested. (e.g. for a "query{user{...}" query, then the property name is "user") + * @param RequestLogName A friendly name for this request (logging and analytics) + */ + UFUNCTION(BlueprintCallable, BlueprintInternalUseOnly, Category = "Speckle|Operations") + static USpeckleStreamAPIOperation* SpeckleStreamAPIOperation( + const FString& ServerUrl, + const FString& AuthToken, + const FString& GraphQlQuery, + const FString& ResponsePropertyName, + const FString& RequestLogName); + + virtual void Activate() override; + +protected: + void Request(); + + FString ServerUrl; + FString AuthToken; + FString Query; + FString RequestLogName; + FString ResponsePropertyName; + + void HandleReceive(const FString& ResponseJson); + + void HandleError(const FString& Message); + +}; diff --git a/Source/SpeckleUnreal/Public/API/SpeckleAPIFunctions.h b/Source/SpeckleUnreal/Public/API/SpeckleAPIFunctions.h new file mode 100644 index 0000000..0b79067 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/SpeckleAPIFunctions.h @@ -0,0 +1,30 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintFunctionLibrary.h" + +#include "SpeckleAPIFunctions.generated.h" + +struct FSpeckleCommit; +/** + * Blueprint function library for Speckle API + */ +UCLASS() +class SPECKLEUNREAL_API USpeckleAPIFunctions : public UBlueprintFunctionLibrary +{ + GENERATED_BODY() + +public: + + UFUNCTION(BlueprintCallable, CustomThunk, Category="Speckle|API", meta=(CustomStructureParam="OutStruct", ExpandBoolAsExecs="ReturnValue")) + static UPARAM(DisplayName = "WasSucessful") bool DeserializeResponse(const FString& JsonString, int32& OutStruct); + DECLARE_FUNCTION(execDeserializeResponse); + + static bool GenericDeserializeResponse(const FString& JsonString, const UScriptStruct* StructType, void* OutStruct); + + static void CommitReceived(FSpeckleCommit& Commit); + + + +}; diff --git a/Source/SpeckleUnreal/Public/API/SpeckleSerializer.h b/Source/SpeckleUnreal/Public/API/SpeckleSerializer.h new file mode 100644 index 0000000..c61fe73 --- /dev/null +++ b/Source/SpeckleUnreal/Public/API/SpeckleSerializer.h @@ -0,0 +1,25 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintFunctionLibrary.h" + + +#include "SpeckleSerializer.generated.h" + +class UBase; +class ITransport; +class FJsonObject; + +UCLASS() +class USpeckleSerializer : public UBlueprintFunctionLibrary +{ + GENERATED_BODY() +public: + + UFUNCTION(BlueprintPure, Category="Speckle|Serialization") + static UBase* DeserializeBaseById(const FString& ObjectId, const TScriptInterface ReadTransport); + + static UBase* DeserializeBase(const TSharedPtr Obj, const TScriptInterface ReadTransport); + +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/AggregateConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/AggregateConverter.h new file mode 100644 index 0000000..bdf15bd --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/AggregateConverter.h @@ -0,0 +1,58 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "UObject/Object.h" +#include "Conversion/SpeckleConverter.h" + +#include "AggregateConverter.generated.h" + +/** + * An Aggregate Converter stores multiple ISpeckleConverter instances. + * This allows you to use many converters as one + */ +UCLASS() + +class SPECKLEUNREAL_API UAggregateConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + +protected: + + // A lazily initialised mapping of SpeckleType -> converters. + TMap, TScriptInterface> SpeckleTypeMap; + +public: + + // Array of converters, must be of type ISpeckleConverter + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle|Conversion") + TArray SpeckleConverters; + + UFUNCTION(BlueprintCallable, Category="Speckle|Conversion") + virtual UObject* ConvertToNativeInternal(const UBase* Object, UWorld* World); + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface&) override; + + virtual bool CanConvertToNative_Implementation(TSubclassOf BaseType) override; + + + virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override; + + + UFUNCTION(BlueprintCallable, Category="Speckle|Conversion") + virtual TScriptInterface GetConverter(const TSubclassOf BaseType); + + // Validates a given object is a valid ISpeckleConverter + static bool CheckValidConverter(const UObject* Converter, bool LogWarning = true); + + void FinishConversion_Internal(); + virtual void FinishConversion_Implementation() override; + + // Validates changes to SpeckleConverters property, Should be called after modifying SpeckleConverters + UFUNCTION(BlueprintCallable, Category="Speckle|Conversion") + virtual void OnConvertersChangeHandler(); + +#if WITH_EDITOR + virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; +#endif + +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/BlockConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/BlockConverter.h new file mode 100644 index 0000000..d6578d1 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/BlockConverter.h @@ -0,0 +1,43 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "UObject/Object.h" +#include "Conversion/SpeckleConverter.h" +#include "Engine/EngineTypes.h" +#include "Engine/World.h" + +#include "BlockConverter.generated.h" + +class UInstance; + +/** + * Converts Speckle Block Instance objects empty native actors with transform. + * The Block Definition can then be converted by other converters + */ +UCLASS() +class SPECKLEUNREAL_API UBlockConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + + CONVERTS_SPECKLE_TYPES() +public: + + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TSubclassOf BlockInstanceActorType; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TEnumAsByte ActorMobility; + + UBlockConverter(); + + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface& AvailableConverters) override; + virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override; + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual AActor* BlockToNative(const UInstance* Block, UWorld* World); + +protected: + virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters()); +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/CollectionConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/CollectionConverter.h new file mode 100644 index 0000000..1b5445d --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/CollectionConverter.h @@ -0,0 +1,53 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Conversion/SpeckleConverter.h" +#include "Engine/EngineTypes.h" +#include "Engine/World.h" + +#include "CollectionConverter.generated.h" + +class UCollection; + + +/** + * Converts Speckle Mesh objects into native actors with a procedural mesh component. + * + * Compared with the StaticMeshConverter, this converter has some serious limitations + * - Cannot convert displayValues, + * - N-gon faces will be ignored, + * - Meshes are transient, and won't persist on level reload + */ +UCLASS() +class SPECKLEUNREAL_API UCollectionConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + + CONVERTS_SPECKLE_TYPES() + +public: + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TSubclassOf ActorType; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TEnumAsByte ActorMobility; + + // Sets default values for this actor's properties + UCollectionConverter(); + + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, + TScriptInterface& AvailableConverters) override; + + virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override; + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual AActor* CollectionToNative(const UCollection* SpeckleCollection, UWorld* World); + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UCollection* CollectionToSpeckle(const AActor* Object); + + virtual AActor* CreateEmptyActor(UWorld* World, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters()); + +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/MaterialConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/MaterialConverter.h new file mode 100644 index 0000000..3ad124d --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/MaterialConverter.h @@ -0,0 +1,98 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Conversion/SpeckleConverter.h" +#include "UObject/Object.h" + +#include "MaterialConverter.generated.h" + +class URenderMaterial; +class UMaterialInterface; + +UENUM() +enum EConstMaterialOptions +{ + Never UMETA(DisplayName = "Never"), + NotPlay UMETA(DisplayName = "Editor Not Playing"), + Always UMETA(DisplayName = "Editor And PIE"), +}; + + +/** + * Converts Speckle RenderMaterial objects into native Materials + */ +UCLASS(BlueprintType, Blueprintable) +class SPECKLEUNREAL_API UMaterialConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + + CONVERTS_SPECKLE_TYPES() + +public: + + /// Material to be applied to meshes when no RenderMaterial can be converted + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + UMaterialInterface* DefaultMeshMaterial; + + /// Material Parent for converted opaque materials*/ + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + UMaterialInterface* BaseMeshOpaqueMaterial; + + /// Material Parent for converted materials with an opacity less than one + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + UMaterialInterface* BaseMeshTransparentMaterial; + +#if WITH_EDITORONLY_DATA + /// Specify when to create Constant materials that can only be created with Editor. + /// Otherwise will create dynamic materials + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TEnumAsByte UseConstMaterials; +#endif + + /// When generating meshes, materials in this TMap will be used + /// instead of converted ones if the key matches the ID of the Object's RenderMaterial. (Takes priority over name matching) + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ToNative|Overrides", DisplayName = "By Speckle ID") + TMap MaterialOverridesById; + + /// When generating meshes, materials in this TSet will be used instead of converted ones if the material name matches the name of the Object's RenderMaterial + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ToNative|Overrides", DisplayName = "By Name") + TSet MaterialOverridesByName; + +public: + + UMaterialConverter(); + + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld*, TScriptInterface&) override; + + UFUNCTION(BlueprintCallable, Category="ToNative|Overrides") + virtual bool TryGetOverride(const URenderMaterial* SpeckleMaterial, UMaterialInterface*& OutMaterial) const; + + + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UMaterialInterface* GetMaterial(const URenderMaterial* SpeckleMaterial); + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UMaterialInterface* RenderMaterialToNative(const URenderMaterial* SpeckleMaterial, UPackage* Package); + + virtual void FinishConversion_Implementation() override; + +protected: + + /** Transient cache of materials converted from stream RenderMaterial objects */ + UPROPERTY(AdvancedDisplay, BlueprintReadOnly, Transient, Category="ToNative|Cache") + TMap ConvertedMaterials; + + UFUNCTION(BlueprintCallable, BlueprintPure, Category="ToNative") + virtual UPackage* GetPackage(const FString& ObjectID) const; + + UFUNCTION(BlueprintCallable, BlueprintPure, Category="ToNative") + virtual FString RemoveInvalidFileChars(const FString& InString) const; + +#if WITH_EDITOR + UFUNCTION(BlueprintCallable, BlueprintPure, Category="ToNative") + static bool ShouldCreateConstMaterial(TEnumAsByte Options); +#endif + +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/PointCloudConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/PointCloudConverter.h new file mode 100644 index 0000000..30ebb7e --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/PointCloudConverter.h @@ -0,0 +1,47 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Conversion/SpeckleConverter.h" +#include "Engine/EngineTypes.h" + +#include "PointCloudConverter.generated.h" + +class ULidarPointCloudComponent; +class ALidarPointCloudActor; +class ULidarPointCloud; +class UPointCloud; + +/** + * Converts Speckle Point Cloud objects into LidarPointClouds + */ +UCLASS() +class SPECKLEUNREAL_API UPointCloudConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + + CONVERTS_SPECKLE_TYPES() + + +public: + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TSubclassOf PointCloudActorType; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TEnumAsByte ActorMobility; + + UPointCloudConverter(); + + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface&) override; + virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override; + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual ALidarPointCloudActor* PointCloudToNative(const UPointCloud* SpecklePointCloud, UWorld* World); + + UFUNCTION(BlueprintCallable, Category="ToSpeckle") + virtual UPointCloud* PointCloudToSpeckle(const ULidarPointCloudComponent* Object); + +protected: + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual ALidarPointCloudActor* CreateActor(UWorld* World, ULidarPointCloud* PointCloudData); +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/ProceduralMeshConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/ProceduralMeshConverter.h new file mode 100644 index 0000000..a78933c --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/ProceduralMeshConverter.h @@ -0,0 +1,57 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Conversion/SpeckleConverter.h" +#include "Engine/EngineTypes.h" +#include "Engine/World.h" + +#include "ProceduralMeshConverter.generated.h" + +class UMaterialConverter; +class UProceduralMeshComponent; +class UMesh; +class URenderMaterial; + + +/** + * Converts Speckle Mesh objects into native actors with a procedural mesh component. + * + * Compared with the StaticMeshConverter, this converter has some serious limitations + * - Cannot convert displayValues, + * - N-gon faces will be ignored, + * - Meshes are transient, and won't persist on level reload + */ +UCLASS() +class SPECKLEUNREAL_API UProceduralMeshConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + + CONVERTS_SPECKLE_TYPES() + +public: + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TSubclassOf MeshActorType; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TEnumAsByte ActorMobility; + + // Sets default values for this actor's properties + UProceduralMeshConverter(); + + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, + TScriptInterface& AvailableConverters) override; + + virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override; + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual AActor* MeshToNative(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface& MaterialConverter); + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UMesh* MeshToSpeckle(const UProceduralMeshComponent* Object); + + virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform, + const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters()); + +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/Converters/StaticMeshConverter.h b/Source/SpeckleUnreal/Public/Conversion/Converters/StaticMeshConverter.h new file mode 100644 index 0000000..dbd90a6 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/Converters/StaticMeshConverter.h @@ -0,0 +1,117 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Conversion/SpeckleConverter.h" +#include "Engine/EngineTypes.h" +#include "Engine/World.h" +#include "Engine/StaticMesh.h" + +#include "StaticMeshConverter.generated.h" + +class UMaterialConverter; +class AStaticMeshActor; +class UMesh; +class URenderMaterial; + + +/** + * Converts Speckle Mesh objects into native Actors with a StaticMesh component + * + * Can convert multiple Speckle Mesh objects (eg with different materials) in one StaticMesh + */ +UCLASS() +class SPECKLEUNREAL_API UStaticMeshConverter : public UObject, public ISpeckleConverter +{ + GENERATED_BODY() + + CONVERTS_SPECKLE_TYPES() + +public: + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TSet HiddenTypes; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TSubclassOf MeshActorType; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + TEnumAsByte ActorMobility; + +#if WITH_EDITORONLY_DATA + // If true, will use the full Editor Only build process + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + bool UseFullBuild; + + // When true, will display FSlowTask progress of editor only build process + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative|EditorOnly") + bool DisplayBuildProgressBar; + + // When true, will allow cancellation of FSlowTask progress of editor only build process + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative|EditorOnly") + bool AllowCancelBuild; +#endif + + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + bool BuildSimpleCollision; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative") + bool Transient; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative") + bool GenerateLightmapUV; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative") + int32 MinLightmapResolution; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative") + bool BuildReversedIndexBuffer; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative") + bool UseFullPrecisionUVs; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative") + bool RemoveDegeneratesOnBuild; +public: + // Sets default values for this actor's properties + UStaticMeshConverter(); + + virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface& AvailableConverters) override; + virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override; + virtual void FinishConversion_Implementation() override; + + // Converts a multiple Speckle Meshes to a native actor of type MeshActorType + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual AActor* MeshesToNativeActor(const UBase* Parent, const TArray& SpeckleMeshes, UWorld* World, TScriptInterface& RenderMaterialConverter); + + // Converts a single Speckle Mesh to a native actor of type MeshActorType + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual AActor* MeshToNativeActor(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface& MaterialConverter); + + virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform = FTransform::Identity, const FActorSpawnParameters& SpawnParameters = + FActorSpawnParameters()); + + UFUNCTION(BlueprintCallable, Category="ToSpeckle") + virtual UBase* MeshToSpeckle(const UStaticMeshComponent* Object); + + +protected: + + FCriticalSection Lock_StaticMeshesToBuild; + + UPROPERTY(BlueprintReadWrite, Transient, Category="ToNative") + TArray StaticMeshesToBuild; + + virtual void GenerateMeshParams(UStaticMesh::FBuildMeshDescriptionsParams& MeshParams) const; + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UMaterialInterface* GetMaterial(const URenderMaterial* SpeckleMaterial, UWorld* World, + TScriptInterface& MaterialConverter) const; + + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UStaticMesh* MeshesToNativeMesh(UObject* Outer, const UBase* Parent, const TArray& SpeckleMeshes, TScriptInterface + & MaterialConverter); + UFUNCTION(BlueprintCallable, Category="ToNative") + virtual UStaticMesh* MeshToNativeMesh(UObject* Outer, const UMesh* SpeckleMesh, TScriptInterface& MaterialConverter); +}; diff --git a/Source/SpeckleUnreal/Public/Conversion/SpeckleConverter.h b/Source/SpeckleUnreal/Public/Conversion/SpeckleConverter.h new file mode 100644 index 0000000..4d46d15 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/SpeckleConverter.h @@ -0,0 +1,53 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" +#include "UObject/Interface.h" +#include "Templates/SubclassOf.h" + +#include "SpeckleConverter.generated.h" + + +UINTERFACE(BlueprintType) +class SPECKLEUNREAL_API USpeckleConverter : public UInterface +{ + GENERATED_BODY() +}; + +/** + * Interface for conversion functions (ToSpeckle and ToNative) of a specific speckle type(s). + * + * Implementors of this interface provide conversion functions of specific types : Base + */ +class SPECKLEUNREAL_API ISpeckleConverter +{ + GENERATED_BODY() + +public: + /// Will return true if this converter can convert a given BaseType + UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative") + bool CanConvertToNative(TSubclassOf BaseType); + + /// Tries to convert a given SpeckleBase into a native Actor + UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative") + UObject* ConvertToNative(const UBase* SpeckleBase, UWorld* World, UPARAM(ref) TScriptInterface& AvailableConverters); + + /// Tries to convert a given Actor or Component into a Speckle Base + /// NOT IMPLEMENTED!!! + UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToSpeckle") + UBase* ConvertToSpeckle(const UObject* Object); + + /// Clean up any cached assets that now may be unused + UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative") + void FinishConversion(); + +}; + +#define CONVERTS_SPECKLE_TYPES() \ +protected: \ + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Conversion") \ + TSet> SpeckleTypes; \ +public: \ + virtual bool CanConvertToNative_Implementation(TSubclassOf BaseType) override { return SpeckleTypes.Contains(BaseType); } \ +private: \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/Conversion/SpeckleConverterComponent.h b/Source/SpeckleUnreal/Public/Conversion/SpeckleConverterComponent.h new file mode 100644 index 0000000..35a87ed --- /dev/null +++ b/Source/SpeckleUnreal/Public/Conversion/SpeckleConverterComponent.h @@ -0,0 +1,52 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Components/ActorComponent.h" + +#include "SpeckleConverterComponent.generated.h" + + +class ITransport; +class ISpeckleConverter; +class UBase; +class UAggregateConverter; +class FJsonValue; +struct FSlowTask; + +/** + * An Actor Component for encapsulating recursive conversion of Speckle Objects + */ +UCLASS(ClassGroup=(Speckle), meta=(BlueprintSpawnableComponent), HideCategories=(Activation, Collision, Cooking, Tags)) +class SPECKLEUNREAL_API USpeckleConverterComponent : public UActorComponent +{ + GENERATED_BODY() + +public: + + // Array of converters + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle|Conversion") + UAggregateConverter* SpeckleConverter; + + // Sets default values for this component's properties + USpeckleConverterComponent(); + + // Converts the given Base and all children into native actors. + UFUNCTION(BlueprintCallable, Category="Speckle|Conversion") + UPARAM(DisplayName = "RootActor") AActor* RecursivelyConvertToNative(AActor* AOwner, const UBase* Base, + const TScriptInterface& LocalTransport, bool DisplayProgressBar, TArray& OutActors); + + UFUNCTION(BlueprintCallable, Category="Speckle|Conversion") + virtual void FinishConversion(); + +protected: + + virtual AActor* RecursivelyConvertToNative_Internal(AActor* AOwner, const UBase* Base, const TScriptInterface& LocalTransport, FSlowTask* Task, TArray& OutActors); + + virtual void ConvertChild(const TSharedPtr Object, AActor* AOwner, const TScriptInterface& LocalTransport, FSlowTask* Task, TArray& OutActors); + + UFUNCTION(BlueprintCallable, Category="Speckle|Conversion") + virtual void AttachConvertedToOwner(AActor* AOwner, const UBase* Base, UObject* Converted); +}; + + diff --git a/Source/SpeckleUnreal/Public/LogSpeckle.h b/Source/SpeckleUnreal/Public/LogSpeckle.h new file mode 100644 index 0000000..bb78288 --- /dev/null +++ b/Source/SpeckleUnreal/Public/LogSpeckle.h @@ -0,0 +1,5 @@ + +#pragma once +#include "CoreMinimal.h" + +DECLARE_LOG_CATEGORY_EXTERN(LogSpeckle, Log, All); \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/Mixpanel.h b/Source/SpeckleUnreal/Public/Mixpanel.h new file mode 100644 index 0000000..704e33d --- /dev/null +++ b/Source/SpeckleUnreal/Public/Mixpanel.h @@ -0,0 +1,20 @@ + +#pragma once + +#include "CoreMinimal.h" + +/// Anonymous telemetry to help us understand how to make a better Speckle. +/// This really helps us to deliver a better open source project and product! +class FAnalytics +{ +protected: + static const FString MixpanelToken; + static const FString MixpanelServer; + static const FString VersionedApplicationName; + +public: + static void TrackEvent(const FString& Server, const FString& EventName); + static void TrackEvent(const FString& Server, const FString& EventName, const TMap& CustomProperties); + static void TrackEvent(const FString& UserID, const FString& Server, const FString& EventName, const TMap& CustomProperties); + static FString Hash(const FString& Input); +}; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/NativeActors/Interfaces/SpeckleMesh.h b/Source/SpeckleUnreal/Public/NativeActors/Interfaces/SpeckleMesh.h deleted file mode 100644 index f696d41..0000000 --- a/Source/SpeckleUnreal/Public/NativeActors/Interfaces/SpeckleMesh.h +++ /dev/null @@ -1,32 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "UObject/Interface.h" -#include "SpeckleMesh.generated.h" - -class ASpeckleUnrealManager; -class UMesh; - -// This class does not need to be modified. -UINTERFACE() -class USpeckleMesh : public UInterface -{ - GENERATED_BODY() -}; - -/** - * - */ -class SPECKLEUNREAL_API ISpeckleMesh -{ - GENERATED_BODY() - - // Add interface functions to this class. This is the class that will be inherited to implement this interface. -public: - - UFUNCTION(BlueprintNativeEvent) - void SetMesh(const UMesh* SpeckleMesh, ASpeckleUnrealManager* Manager); - -}; diff --git a/Source/SpeckleUnreal/Public/NativeActors/Interfaces/SpecklePointCloud.h b/Source/SpeckleUnreal/Public/NativeActors/Interfaces/SpecklePointCloud.h deleted file mode 100644 index 17f3732..0000000 --- a/Source/SpeckleUnreal/Public/NativeActors/Interfaces/SpecklePointCloud.h +++ /dev/null @@ -1,32 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "UObject/Interface.h" -#include "SpecklePointCloud.generated.h" - -class ASpeckleUnrealManager; -class UPointCloud; - -// This class does not need to be modified. -UINTERFACE() -class USpecklePointCloud : public UInterface -{ - GENERATED_BODY() -}; - -/** - * - */ -class SPECKLEUNREAL_API ISpecklePointCloud -{ - GENERATED_BODY() - - // Add interface functions to this class. This is the class that will be inherited to implement this interface. -public: - - UFUNCTION(BlueprintNativeEvent) - void SetData(const UPointCloud* SpecklePointCloud, ASpeckleUnrealManager* Manager); - -}; diff --git a/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealPointCloud.h b/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealPointCloud.h deleted file mode 100644 index 3311ae0..0000000 --- a/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealPointCloud.h +++ /dev/null @@ -1,23 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "LidarPointCloudActor.h" -#include "Interfaces/SpecklePointCloud.h" - -#include "SpeckleUnrealPointCloud.generated.h" - -UCLASS() -class SPECKLEUNREAL_API ASpeckleUnrealPointCloud : public ALidarPointCloudActor, public ISpecklePointCloud -{ - GENERATED_BODY() - -public: - - // Sets default values for this actor's properties - ASpeckleUnrealPointCloud(); - - virtual void SetData_Implementation(const UPointCloud* SpecklePointCloud, ASpeckleUnrealManager* Manager) override; - -}; diff --git a/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealProceduralMesh.h b/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealProceduralMesh.h deleted file mode 100644 index e98f5b6..0000000 --- a/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealProceduralMesh.h +++ /dev/null @@ -1,31 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "ProceduralMeshComponent.h" -#include "SpeckleUnrealActor.h" -#include "Interfaces/SpeckleMesh.h" - -#include "SpeckleUnrealProceduralMesh.generated.h" - -/** - * - */ -UCLASS() -class SPECKLEUNREAL_API ASpeckleUnrealProceduralMesh : public ASpeckleUnrealActor, public ISpeckleMesh -{ - GENERATED_BODY() - -public: - UPROPERTY(VisibleAnywhere, BlueprintReadWrite) - UProceduralMeshComponent* MeshComponent; - - // Sets default values for this actor's properties - ASpeckleUnrealProceduralMesh(); - - virtual void SetMesh_Implementation(const UMesh* SpeckleMesh, ASpeckleUnrealManager* Manager) override; - - UFUNCTION(BlueprintCallable) - virtual UMaterialInterface* GetMaterial(const URenderMaterial* SpeckleMaterial, ASpeckleUnrealManager* Manager); -}; diff --git a/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealStaticMesh.h b/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealStaticMesh.h deleted file mode 100644 index fdcc639..0000000 --- a/Source/SpeckleUnreal/Public/NativeActors/SpeckleUnrealStaticMesh.h +++ /dev/null @@ -1,40 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "SpeckleUnrealActor.h" -#include "Interfaces/SpeckleMesh.h" - -#include "SpeckleUnrealStaticMesh.generated.h" - -/** - * - */ -UCLASS() -class SPECKLEUNREAL_API ASpeckleUnrealStaticMesh : public ASpeckleUnrealActor, public ISpeckleMesh -{ - GENERATED_BODY() - -public: - - UPROPERTY(VisibleAnywhere, BlueprintReadWrite) - UStaticMeshComponent* MeshComponent; - - UPROPERTY(VisibleAnywhere, BlueprintReadWrite) - bool UseFullBuild; - - UPROPERTY(VisibleAnywhere, BlueprintReadWrite) - bool BuildSimpleCollision; - - UPROPERTY(VisibleAnywhere, BlueprintReadWrite) - bool Transient; - - // Sets default values for this actor's properties - ASpeckleUnrealStaticMesh(); - - virtual void SetMesh_Implementation(const UMesh* SpeckleMesh, ASpeckleUnrealManager* Manager) override; - - UFUNCTION(BlueprintCallable) - virtual UMaterialInterface* GetMaterial(const URenderMaterial* SpeckleMaterial, ASpeckleUnrealManager* Manager); -}; diff --git a/Source/SpeckleUnreal/Public/Objects/Base.h b/Source/SpeckleUnreal/Public/Objects/Base.h index 74d7709..5ef9b81 100644 --- a/Source/SpeckleUnreal/Public/Objects/Base.h +++ b/Source/SpeckleUnreal/Public/Objects/Base.h @@ -1,4 +1,3 @@ -// Fill out your copyright notice in the Description page of Project Settings. #pragma once @@ -7,33 +6,96 @@ #include "Base.generated.h" +class ITransport; class ASpeckleUnrealManager; /** - * + * Base type that all Object Models inherit from */ -UCLASS(BlueprintType) +UCLASS(BlueprintType, meta=(DisplayName="Speckle Object (Base)")) class SPECKLEUNREAL_API UBase : public UObject { public: + GENERATED_BODY() - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - FString Id; +protected: - //UPROPERTY(BlueprintReadOnly) - //TMap Properties; //TODO figure out how I'm going to do custom properties + explicit UBase(const TCHAR* SpeckleType): SpeckleType(FString(SpeckleType)) {} + explicit UBase(const FString& SpeckleType) : SpeckleType(SpeckleType) {} + +public: - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - FString Units; + UBase() : SpeckleType("Base") {} + + + UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects") + FString Id; - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) + UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects") + int64 TotalChildrenCount = 0; + + UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects") + FString ApplicationId; + + UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects") FString SpeckleType; + + UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects") + FString Units; - virtual void Parse(const TSharedPtr Obj, const ASpeckleUnrealManager* _) + TMap> DynamicProperties; //TODO this won't be serialised! + + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) + { + bool IsValid = false; + DynamicProperties = Obj->Values; + if(Obj->TryGetStringField(TEXT("id"), Id)) + { + IsValid = true; + DynamicProperties.Remove(TEXT("id")); + } + + if(Obj->TryGetStringField(TEXT("units"), Units)) DynamicProperties.Remove(TEXT("units")); + if(Obj->TryGetStringField(TEXT("speckle_type"), SpeckleType)) DynamicProperties.Remove(TEXT("speckle_type")); + if(Obj->TryGetStringField(TEXT("applicationId"), ApplicationId)) DynamicProperties.Remove(TEXT("applicationId")); + if(Obj->TryGetNumberField(TEXT("totalChildrenCount"), TotalChildrenCount)) DynamicProperties.Remove(TEXT("totalChildrenCount")); + + return IsValid; + } + +protected: + + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + int32 RemoveDynamicProperty(UPARAM(ref) const FString& Key) + { + return DynamicProperties.Remove(Key); + } + +public: + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + bool TryGetDynamicString(UPARAM(ref) const FString& Key, FString& OutString) const { - Obj->TryGetStringField("id", Id); - Obj->TryGetStringField("units", Units); - Obj->TryGetStringField("speckle_type", SpeckleType); + const TSharedPtr Value = DynamicProperties.FindRef(Key); + if(Value == nullptr) return false; + return Value->TryGetString(OutString); } -}; \ No newline at end of file + + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + bool TryGetDynamicNumber(UPARAM(ref) const FString& Key, float& OutNumber) const + { + const TSharedPtr Value = DynamicProperties.FindRef(Key); + if(Value == nullptr) return false; + return Value->TryGetNumber(OutNumber); + } + + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + bool TryGetDynamicBool(UPARAM(ref) const FString& Key, bool& OutBool) const + { + const TSharedPtr Value = DynamicProperties.FindRef(Key); + if(Value == nullptr) return false; + return Value->TryGetBool(OutBool); + } +}; + diff --git a/Source/SpeckleUnreal/Public/Objects/Collection.h b/Source/SpeckleUnreal/Public/Objects/Collection.h new file mode 100644 index 0000000..21a26e2 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Collection.h @@ -0,0 +1,28 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" + +#include "Collection.generated.h" + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API UCollection : public UBase +{ + GENERATED_BODY() + +public: + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + FString Name; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + FString CollectionType; + + UCollection() : UBase(TEXT("Speckle.Core.Models.Collection")) {} + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; +}; diff --git a/Source/SpeckleUnreal/Public/Objects/DisplayValueElement.h b/Source/SpeckleUnreal/Public/Objects/DisplayValueElement.h new file mode 100644 index 0000000..f3c4dde --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/DisplayValueElement.h @@ -0,0 +1,32 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Base.h" + +#include "DisplayValueElement.generated.h" + + +class UMesh; + +/** + * This class does not exist in speckle sharp, + * This is a type to represent objects that have displayValues + */ +UCLASS() +class SPECKLEUNREAL_API UDisplayValueElement : public UBase +{ + GENERATED_BODY() +protected: + static TArray DisplayValueAliasStrings; + bool AddDisplayValue(const TSharedPtr Obj, const TScriptInterface ReadTransport); + +public: + + UDisplayValueElement() : UBase(TEXT("Objects.Other.DisplayValueElement")) {} + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray DisplayValue; + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Geometry/Mesh.h b/Source/SpeckleUnreal/Public/Objects/Geometry/Mesh.h new file mode 100644 index 0000000..fbef178 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Geometry/Mesh.h @@ -0,0 +1,50 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" + +#include "Mesh.generated.h" + +class URenderMaterial; + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API UMesh : public UBase +{ + GENERATED_BODY() + +public: + + UMesh() : UBase(TEXT("Objects.Geometry.Mesh")) {} + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray Vertices; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray Faces; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray TextureCoordinates; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray VertexColors; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + FMatrix Transform; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + URenderMaterial* RenderMaterial; + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; + +protected: + + + /// If not already so, this method will align vertices + /// such that a vertex and its corresponding texture coordinates have the same index. + /// See "https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Mesh.cs" + virtual void AlignVerticesWithTexCoordsByIndex(); +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Geometry/PointCloud.h b/Source/SpeckleUnreal/Public/Objects/Geometry/PointCloud.h new file mode 100644 index 0000000..8d93051 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Geometry/PointCloud.h @@ -0,0 +1,31 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" + +#include "PointCloud.generated.h" + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API UPointCloud : public UBase +{ + GENERATED_BODY() + +public: + + UPointCloud() : UBase(TEXT("Objects.Geometry.Pointcloud")) {} + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray Points; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray Colors; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray Sizes; + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Mesh.h b/Source/SpeckleUnreal/Public/Objects/Mesh.h deleted file mode 100644 index 406f6b3..0000000 --- a/Source/SpeckleUnreal/Public/Objects/Mesh.h +++ /dev/null @@ -1,43 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "Base.h" - -#include "Mesh.generated.h" - -class URenderMaterial; -class ASpeckleUnrealManager; -/** - * - */ -UCLASS() -class SPECKLEUNREAL_API UMesh : public UBase -{ - GENERATED_BODY() - -public: - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray Vertices; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray Faces; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray TextureCoordinates; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray VertexColors; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - FMatrix Transform; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - URenderMaterial* RenderMaterial; - - virtual void Parse(const TSharedPtr Obj, const ASpeckleUnrealManager* Manager) override; - -protected: - virtual void AlignVerticesWithTexCoordsByIndex(); -}; diff --git a/Source/SpeckleUnreal/Public/Objects/ObjectModelRegistry.h b/Source/SpeckleUnreal/Public/Objects/ObjectModelRegistry.h new file mode 100644 index 0000000..4b20f08 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/ObjectModelRegistry.h @@ -0,0 +1,62 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintFunctionLibrary.h" +#include "Templates/SubclassOf.h" + +#include "ObjectModelRegistry.generated.h" + +class UBase; + +/** + * Handles the mapping of Speckle type to Object Model + */ +UCLASS() +class SPECKLEUNREAL_API UObjectModelRegistry : public UBlueprintFunctionLibrary +{ + GENERATED_BODY() + +private: + + static TMap> TypeRegistry; + + static void GenerateTypeRegistry(); + +public: + + /** + * @brief Searches for a closest registered speckle type + * by recursively stripping away a the most specific name specifier from the given SpeckleType + * e.g. With an input of `"Objects.BuiltElements.Wall:Objects.BuiltElements.RevitWall"` will first search for + * Will first look for a registered type of `"Objects.BuiltElements.RevitWall"`, then if not found `"Objects.BuiltElements.Wall"`, then simply will use UBase + * @param SpeckleType The full speckle type + * @return The closest registered type + */ + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + static TSubclassOf GetAtomicType(const FString& SpeckleType); + + + // E.g. "Objects.BuiltElements.Wall:Objects.BuiltElements.RevitWall" -> "Objects.BuiltElements.RevitWall" + UFUNCTION(BlueprintCallable, BlueprintPure, Category="Speckle|Objects") + static FString GetTypeName(const FString& SpeckleType); + + // E.g. "Objects.BuiltElements.Wall:Objects.BuiltElements.RevitWall" -> "RevitWall" + UFUNCTION(BlueprintCallable, BlueprintPure, Category="Speckle|Objects") + static FString GetSimplifiedTypeName(const FString& SpeckleType); + + UFUNCTION(BlueprintCallable, BlueprintPure, Category="Speckle|Objects") + static bool SplitSpeckleType(const FString& SpeckleType, FString& OutRemainder, FString& OutTypeName, const FString& Split = ":"); + + /** + * @brief Attempts to find a `TSubclassOf` with a `UBase::SpeckleType` matching the given SpeckleType param + * @param TypeName + * @return the matching type or `nullptr` if none found. + */ + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + static TSubclassOf GetRegisteredType(const FString& TypeName); + + /// Attempts to find a TSubclassOf with a UBase::SpeckleType matching the given SpeckleType param + UFUNCTION(BlueprintCallable, Category="Speckle|Objects") + static bool TryGetRegisteredType(const FString& TypeName, TSubclassOf& OutType); +}; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/Objects/Other/BlockInstance.h b/Source/SpeckleUnreal/Public/Objects/Other/BlockInstance.h new file mode 100644 index 0000000..747e5f0 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Other/BlockInstance.h @@ -0,0 +1,23 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Instance.h" + +#include "BlockInstance.generated.h" + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API UBlockInstance : public UInstance +{ + GENERATED_BODY() + +public: + + UBlockInstance() : UInstance(TEXT("Objects.Other.BlockInstance")) {} + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; + +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Other/Instance.h b/Source/SpeckleUnreal/Public/Objects/Other/Instance.h new file mode 100644 index 0000000..96ac081 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Other/Instance.h @@ -0,0 +1,32 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" + +#include "Instance.generated.h" + +/** + * + */ +UCLASS(Abstract) +class SPECKLEUNREAL_API UInstance : public UBase +{ + GENERATED_BODY() + +public: + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + FString Name; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + TArray Geometry; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects") + FMatrix Transform; + +protected: + UInstance(const FString& SpeckleType) : UBase(SpeckleType) {} + + UInstance() : UBase(TEXT("Objects.Other.BlockInstance")) {} +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Other/RenderMaterial.h b/Source/SpeckleUnreal/Public/Objects/Other/RenderMaterial.h new file mode 100644 index 0000000..c6b8f55 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Other/RenderMaterial.h @@ -0,0 +1,68 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" + +#include "RenderMaterial.generated.h" + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API URenderMaterial : public UBase +{ + GENERATED_BODY() + +public: + + URenderMaterial() : UBase(TEXT("Objects.Other.RenderMaterial")) {} + + UPROPERTY() + FString Name; + + UPROPERTY() + double Opacity = 1; + + UPROPERTY() + double Metalness = 0; + + UPROPERTY() + double Roughness = 1; + + UPROPERTY() + FLinearColor Diffuse = FColor{221,221,221}; + + UPROPERTY() + FLinearColor Emissive = FLinearColor::Black; + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override + { + if(!Super::Parse(Obj, ReadTransport)) return false; + + if(!Obj->TryGetStringField(TEXT("name"), Name)) return false; + if(Obj->TryGetNumberField(TEXT("opacity"), Opacity)) DynamicProperties.Remove(TEXT("opacity")); + if(Obj->TryGetNumberField(TEXT("metalness"), Metalness)) DynamicProperties.Remove(TEXT("metalness")); + if(Obj->TryGetNumberField(TEXT("roughness"), Roughness)) DynamicProperties.Remove(TEXT("roughness")); + + bool IsValid = false; + + int32 ARGB; + if(Obj->TryGetNumberField(TEXT("diffuse"), ARGB)) + { + Diffuse = FColor(ARGB); + DynamicProperties.Remove(TEXT("diffuse")); + IsValid = true; + } + + if(Obj->TryGetNumberField(TEXT("emissive"), ARGB)) + { + Emissive = FColor(ARGB); + DynamicProperties.Remove(TEXT("emissive")); + } + + return IsValid; + } + + +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Other/RevitInstance.h b/Source/SpeckleUnreal/Public/Objects/Other/RevitInstance.h new file mode 100644 index 0000000..a170fb7 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Other/RevitInstance.h @@ -0,0 +1,23 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Instance.h" + +#include "RevitInstance.generated.h" + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API URevitInstance : public UInstance +{ + GENERATED_BODY() + +public: + + URevitInstance() : UInstance(TEXT("Objects.Other.Revit.RevitInstance")) {} + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; + +}; diff --git a/Source/SpeckleUnreal/Public/Objects/Other/View3D.h b/Source/SpeckleUnreal/Public/Objects/Other/View3D.h new file mode 100644 index 0000000..660cc28 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Other/View3D.h @@ -0,0 +1,37 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Objects/Base.h" + +#include "View3D.generated.h" + +/** + * + */ +UCLASS() +class SPECKLEUNREAL_API UView3D : public UBase +{ + GENERATED_BODY() + +public: + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + FString Name; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + FVector Origin; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + FVector UpDirection; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + FVector ForwardDirection; + + UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects") + bool IsOrthogonal; + + UView3D() : UBase(TEXT("Objects.BuiltElements.View")) {} + + virtual bool Parse(const TSharedPtr Obj, const TScriptInterface ReadTransport) override; +}; diff --git a/Source/SpeckleUnreal/Public/Objects/PointCloud.h b/Source/SpeckleUnreal/Public/Objects/PointCloud.h deleted file mode 100644 index f00be49..0000000 --- a/Source/SpeckleUnreal/Public/Objects/PointCloud.h +++ /dev/null @@ -1,29 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "Base.h" -#include "PointCloud.generated.h" - -/** - * - */ -UCLASS() -class SPECKLEUNREAL_API UPointCloud : public UBase -{ - GENERATED_BODY() - -public: - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray Points; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray Colors; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly) - TArray Sizes; - - virtual void Parse(const TSharedPtr Obj, const ASpeckleUnrealManager* Manager) override; -}; diff --git a/Source/SpeckleUnreal/Public/Objects/RenderMaterial.h b/Source/SpeckleUnreal/Public/Objects/RenderMaterial.h deleted file mode 100644 index 3f63bc5..0000000 --- a/Source/SpeckleUnreal/Public/Objects/RenderMaterial.h +++ /dev/null @@ -1,57 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "Objects/Base.h" - -#include "RenderMaterial.generated.h" - -/** - * - */ -UCLASS() -class SPECKLEUNREAL_API URenderMaterial : public UBase -{ - GENERATED_BODY() - -public: - - UPROPERTY() - FString Name; - - UPROPERTY() - double Opacity = 1; - - UPROPERTY() - double Metalness = 0; - - UPROPERTY() - double Roughness = 1; - - UPROPERTY() - FLinearColor Diffuse = FLinearColor{221,221,221}; - - UPROPERTY() - FLinearColor Emissive = FLinearColor::Black; - - virtual void Parse(const TSharedPtr Obj, const ASpeckleUnrealManager* Manager) override - { - Super::Parse(Obj, Manager); - - Obj->TryGetStringField("name", Name); - Obj->TryGetNumberField("opacity", Opacity); - Obj->TryGetNumberField("metalness", Metalness); - Obj->TryGetNumberField("roughness", Roughness); - - int32 ARGB; - if(Obj->TryGetNumberField("diffuse", ARGB)) - Diffuse = FColor(ARGB); - - if(Obj->TryGetNumberField("emissive", ARGB)) - Emissive = FColor(ARGB); - - } - - -}; diff --git a/Source/SpeckleUnreal/Public/Objects/Utils/SpeckleObjectUtils.h b/Source/SpeckleUnreal/Public/Objects/Utils/SpeckleObjectUtils.h new file mode 100644 index 0000000..e330169 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Objects/Utils/SpeckleObjectUtils.h @@ -0,0 +1,57 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintFunctionLibrary.h" +#include "Templates/SubclassOf.h" +#include "SpeckleObjectUtils.generated.h" + +class ITransport; +class UBase; +class FJsonValue; +class FJsonObject; +class UWorld; +class AActor; + +/** + * Several helper functions useful for handling JSON Speckle Objects + */ +UCLASS() +class SPECKLEUNREAL_API USpeckleObjectUtils : public UBlueprintFunctionLibrary +{ + GENERATED_BODY() + +public: + static TArray> CombineChunks(const TArray>& ArrayField, const TScriptInterface Transport); + + static bool ResolveReference(const TSharedPtr Object, const TScriptInterface Transport, TSharedPtr& OutObject); + + static bool TryParseTransform(const TSharedPtr SpeckleObject, FMatrix& OutMatrix); + + + static bool ParseVector(const TSharedPtr Object, const TScriptInterface Transport, FVector& OutObject); + static bool ParseVectorProperty(const TSharedPtr Base, const FString& PropertyName, const TScriptInterface ReadTransport, FVector& OutObject); + + template + static bool ParseSpeckleObject(const TSharedPtr Object, const TScriptInterface Transport, T*& OutObject); + + + UFUNCTION(BlueprintCallable, Category="Speckle/ObjectUtils") + static float ParseScaleFactor(const FString& UnitsString); + + // Given a Right Handed Z-up transformation matrix (Speckle's system), will create an equivalent Left Handed Z-up FTransform (UE's system) + UFUNCTION(BlueprintPure, Category="Speckle/ObjectUtils") + static FTransform CreateTransform(UPARAM(ref) const FMatrix& TransformMatrix); + + UFUNCTION(BlueprintCallable, Category="Speckle/ObjectUtils", meta=(CallableWithoutWorldContext, WorldContext="WorldContextObject", DeterminesOutputType="Class", DynamicOutputParam="ReturnValue")) + static AActor* SpawnActorInWorld(const UObject* WorldContextObject, const TSubclassOf Class, UPARAM(ref) const FTransform& Transform); + + // Helper function to print a json obj to console + static FString DisplayAsString(const FString& msg, const TSharedPtr Obj); + + UFUNCTION(BlueprintCallable, Category="Speckle/ObjectUtils", BlueprintPure) + static FString GetFriendlyObjectName(const UBase* SpeckleObject); + + UFUNCTION(BlueprintCallable, Category="Speckle/ObjectUtils", BlueprintPure) + static FString GetBoringObjectName(const UBase* SpeckleObject); +}; diff --git a/Source/SpeckleUnreal/Public/ReceiveSelectionComponent.h b/Source/SpeckleUnreal/Public/ReceiveSelectionComponent.h new file mode 100644 index 0000000..4c789e3 --- /dev/null +++ b/Source/SpeckleUnreal/Public/ReceiveSelectionComponent.h @@ -0,0 +1,178 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Components/ActorComponent.h" +#include "API/Models/SpeckleStream.h" + +#include "ReceiveSelectionComponent.generated.h" + + +/** + * Actor component for selecting a Speckle Stream + Object + * Either by Stream Id + Object Id (Object selection mode) + * Or by Stream + Branch + Commit (Commit selection mode) + */ +UCLASS(ClassGroup=(Speckle), meta=(BlueprintSpawnableComponent), HideCategories=(Activation, Collision, Cooking, Tags)) +class SPECKLEUNREAL_API UReceiveSelectionComponent : public UActorComponent +{ + GENERATED_BODY() + +public: + + // URL of the speckle server + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle") + FString ServerUrl = "https://app.speckle.systems"; + + // A Personal Access Token can be created from your Speckle Profile page (Treat tokens like passwords, do not share publicly) + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", meta=(PasswordField=true)) + FString AuthToken; + + // Id of the stream to receive from (checkout the stream URL in the Speckle web viewer) + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", meta=(EditCondition="bManualMode", EditConditionHides, DisplayAfter=bManualMode)) + FString StreamId; + + // Id of the Speckle Object to receive (checkout the properties panel in the Speckle web viewer) + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", meta=(EditCondition="bManualMode", EditConditionHides, DisplayAfter=StreamId)) + FString ObjectId; + + /** + * Trys to get the currently selected Commit (Commit selection mode) + * @param OutCommit the selected Commit (if return was true) + * @returns true if a selection was made + */ + UFUNCTION(BlueprintCallable, Category="Speckle") + bool TryGetSelectedCommit(FSpeckleCommit& OutCommit) const; + + /** + * Trys to get the currently selected Branch (Commit selection mode) + * @param OutBranch the selected Branch (if return was true) + * @returns true if a selection was made + */ + UFUNCTION(BlueprintCallable, Category="Speckle") + bool TryGetSelectedBranch(FSpeckleBranch& OutBranch) const; + + /** + * Trys to get the currently selected Stream (Commit selection mode) + * @param OutStream the selected Stream (if return was true) + * @returns true if a selection was made + */ + UFUNCTION(BlueprintCallable, Category="Speckle") + bool TryGetSelectedStream(FSpeckleStream& OutStream) const; + + /** + * @param OutStatusMessage the current status of the object selection as a human readable string + * @returns true if a complete object selection is made. + */ + UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor) + bool IsSelectionComplete(FString& OutStatusMessage) const; + + // Gets the URL of the current selection/partial selection + UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor) + FString GetUrl() const; + + /** + * Launches the URL of the current selection/partial selection using FPlatformProcess + * @returns true if the URL could be launched + */ + UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor) + void OpenURLInBrowser() const; + +#if WITH_EDITOR + virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; +#endif + + virtual void PropertyChangeHandler(const FName& PropertyName); + +protected: //Internal logic for branch/stream/commit fetching and selection + + // When true, user specifies stream id + object id, when false, user specifies stream + branch + commit + UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Specify by Object Id", DisplayAfter=AuthToken)); + bool bManualMode = true; + + // Limit of how many streams/branches/commits to fetch + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay, meta=(DisplayName="Options Limit", ClampMin=0, ClampMax=100, UIMin = 1, UIMax=30)) + int32 Limit = 15; + + // Refreshes the Stream/Branch/Commit options + UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor) + void Refresh(); + +#pragma region Stream + UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Stream", GetOptions=GetStreamsOptions, EditCondition="IsAccountValid && !bManualMode", NoResetToDefault)) + FString SelectedStreamText; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + TMap Streams; + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual TArray GetStreamsOptions() const; + + UFUNCTION(BlueprintCallable, Category="Speckle") + bool SelectStream(const FString& DisplayId); + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual void UpdateStreams(); + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual FSpeckleStream GetSelectedStream() const; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + bool IsStreamValid = false; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + bool IsAccountValid = false; + +#pragma endregion + +#pragma region Branch + UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Branch", GetOptions=GetBranchOptions, EditCondition="IsAccountValid && !bManualMode", NoResetToDefault)) + FString SelectedBranchText; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + TMap Branches; + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual TArray GetBranchOptions(); + + UFUNCTION(BlueprintCallable, Category="Speckle") + bool SelectBranch(const FString& DisplayId); + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual void UpdateBranches(); + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual FSpeckleBranch GetSelectedBranch() const; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + bool IsBranchValid = false; + +#pragma endregion + +#pragma region Commit + UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Commit", GetOptions=GetCommitOptions, EditCondition="IsAccountValid && !bManualMode", NoResetToDefault)) + FString SelectedCommitText; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + TMap Commits; + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual TArray GetCommitOptions(); + + UFUNCTION(BlueprintCallable, Category="Speckle") + bool SelectCommit(const FString& DisplayId); + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual void UpdateCommits(); + + UFUNCTION(BlueprintCallable, Category="Speckle") + virtual FSpeckleCommit GetSelectedCommit() const; + + UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle") + bool IsCommitValid = false; + +#pragma endregion + + static void LogError(const FString& Message, const FString LogName); +}; + diff --git a/Source/SpeckleUnreal/Public/SpeckleUnreal.h b/Source/SpeckleUnreal/Public/SpeckleUnreal.h index 15f34fa..12addf6 100644 --- a/Source/SpeckleUnreal/Public/SpeckleUnreal.h +++ b/Source/SpeckleUnreal/Public/SpeckleUnreal.h @@ -1,4 +1,3 @@ -// Copyright Epic Games, Inc. All Rights Reserved. #pragma once diff --git a/Source/SpeckleUnreal/Public/SpeckleUnrealActor.h b/Source/SpeckleUnreal/Public/SpeckleUnrealActor.h deleted file mode 100644 index f15f80e..0000000 --- a/Source/SpeckleUnreal/Public/SpeckleUnrealActor.h +++ /dev/null @@ -1,23 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "GameFramework/Actor.h" -#include "SpeckleUnrealActor.generated.h" - -class UMeshDescriptionBase; - -UCLASS(BlueprintType) -class SPECKLEUNREAL_API ASpeckleUnrealActor : public AActor -{ - GENERATED_BODY() - -public: - UPROPERTY(VisibleAnywhere) - USceneComponent* Scene; - - // Sets default values for this actor's properties - ASpeckleUnrealActor(); - -}; diff --git a/Source/SpeckleUnreal/Public/SpeckleUnrealLayer.h b/Source/SpeckleUnreal/Public/SpeckleUnrealLayer.h deleted file mode 100644 index 177f745..0000000 --- a/Source/SpeckleUnreal/Public/SpeckleUnrealLayer.h +++ /dev/null @@ -1,33 +0,0 @@ -// Fill out your copyright notice in the Description page of Project Settings. - -#pragma once - -#include "CoreMinimal.h" -#include "UObject/NoExportTypes.h" -#include "SpeckleUnrealLayer.generated.h" - -/** - * - */ -UCLASS(BlueprintType) -class SPECKLEUNREAL_API USpeckleUnrealLayer : public UObject -{ - GENERATED_BODY() - -public: - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle") - FString LayerName; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle") - FLinearColor LayerColor; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle") - int32 StartIndex; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle") - int32 ObjectCount; - - USpeckleUnrealLayer(); - - void Init(FString NewLayerName, int32 NewStartIndex, int32 NewObjectCount); -}; diff --git a/Source/SpeckleUnreal/Public/SpeckleUnrealManager.h b/Source/SpeckleUnreal/Public/SpeckleUnrealManager.h index 0b3a71c..d2dee9b 100644 --- a/Source/SpeckleUnreal/Public/SpeckleUnrealManager.h +++ b/Source/SpeckleUnreal/Public/SpeckleUnrealManager.h @@ -1,133 +1,74 @@ -#pragma once - -// json manipulation -#include "Dom/JsonObject.h" -#include "Dom/JsonValue.h" -// web requests -#include "SpeckleUnrealActor.h" -#include "Runtime/Online/HTTP/Public/Http.h" +#pragma once -#include "SpeckleUnrealLayer.h" #include "GameFramework/Actor.h" -#include "NativeActors/SpeckleUnrealPointCloud.h" -#include "NativeActors/SpeckleUnrealProceduralMesh.h" #include "SpeckleUnrealManager.generated.h" +class UServerTransport; +class ITransport; +class USpeckleConverterComponent; +class UReceiveSelectionComponent; +class FJsonObject; -class URenderMaterial; - -UCLASS(BlueprintType) +/** + * An Actor to handle the receiving of Speckle objects into a level + */ +UCLASS(ClassGroup=(Speckle), AutoCollapseCategories=("Speckle|Conversion"), BlueprintType, HideCategories = (Collision, Rendering, Replication, HLOD, Physics, Networking, Input, Actor)) class SPECKLEUNREAL_API ASpeckleUnrealManager : public AActor { GENERATED_BODY() - + public: - FHttpModule* Http; - /* The actual HTTP call */ - UFUNCTION(CallInEditor, Category = "Speckle") - void ImportSpeckleObject(); - - UFUNCTION(CallInEditor, Category = "Speckle") - void DeleteObjects(); + UPROPERTY(VisibleAnywhere, Category="Speckle", BlueprintReadWrite) + UReceiveSelectionComponent* ReceiveSelection; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle") - FString ServerUrl { - "https://speckle.xyz" - }; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle") - FString StreamID { - "" - }; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle") - FString ObjectID { - "" - }; - - /** A Personal Access Token can be created from your Speckle Profile page (Treat tokens like passwords, do not share publicly) */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle") - FString AuthToken { - "" - }; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle") + // When true, will call `Receive` on BeginPlay + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay) bool ImportAtRuntime; - - /** The type of Actor to use for Mesh conversion, you may create a custom actor implementing ISpeckleMesh */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Conversion", meta = (MustImplement = "SpeckleMesh")) - TSubclassOf MeshActor { - ASpeckleUnrealProceduralMesh::StaticClass() - }; + // When true, will maintain an in-memory (transient) cache of received speckle objects + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay) + bool KeepCache; - /** The type of Actor to use for PointCloud conversion, you may create a custom actor implementing ISpecklePointCloud */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Conversion", meta = (MustImplement = "SpecklePointCloud")) - TSubclassOf PointCloudActor { - ASpeckleUnrealPointCloud::StaticClass() - }; + // The Conversion component to convert received speckle objects into native Actors + UPROPERTY(VisibleAnywhere, Category="Speckle", BlueprintReadWrite) + USpeckleConverterComponent* Converter; + // When true, will display an editor progress bar while receiving objects + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay) + bool DisplayProgressBar; - /** Material to be applied to meshes when no RenderMaterial can be converted */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Materials") - UMaterialInterface* DefaultMeshMaterial; - - /** Material Parent for converted opaque materials*/ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Materials") - UMaterialInterface* BaseMeshOpaqueMaterial; + // Sets default values for this actor's properties + ASpeckleUnrealManager(); - /** Material Parent for converted materials with an opacity less than one */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Materials") - UMaterialInterface* BaseMeshTransparentMaterial; - - /** When generating meshes, materials in this TMap will be used instead of converted ones if the key matches the ID of the Object's RenderMaterial. (Takes priority over name matching)*/ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Materials|Overrides", DisplayName = "By Speckle ID") - TMap MaterialOverridesById; + // Receives specified object from specified Speckle server + UFUNCTION(BlueprintCallable, CallInEditor, Category="Speckle", meta=(DisplayPriority=0)) + virtual void Receive(); - /** When generating meshes, materials in this TSet will be used instead of converted ones if the material name matches the name of the Object's RenderMaterial. */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Speckle|Materials|Overrides", DisplayName = "By Name") - TSet MaterialOverridesByName; + // Deletes the Actors created by the previous receive operation + UFUNCTION(BlueprintCallable, CallInEditor, Category="Speckle" , meta=(DisplayAfter="Receive")) + virtual void DeleteObjects(); - /** Materials converted from stream RenderMaterial objects */ - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Speckle|Materials") - TMap ConvertedMaterials; - - TArray SpeckleUnrealLayers; - - void OnStreamTextResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful); - - // Sets default values for this actor's properties - ASpeckleUnrealManager(); - - // Called when the game starts or when spawned virtual void BeginPlay() override; - TArray> CombineChunks(const TArray>& ArrayField) const; - float ParseScaleFactor(const FString& Units) const; - bool TryGetMaterial(const URenderMaterial* SpeckleMaterial, bool AcceptMaterialOverride, - UMaterialInterface*& OutMaterial); protected: - UWorld* World; - - float WorldToCentimeters; - + // Cache received Speckle objects + UPROPERTY(BlueprintReadWrite, Category="Speckle") + TScriptInterface LocalObjectCache; - TMap> SpeckleObjects; - - TArray CreatedObjectsCache; - TArray InProgressObjectsCache; - - - void ImportObjectFromCache(AActor* AOwner, const TSharedPtr SpeckleObject, const TSharedPtr ParentObject = nullptr); + // Array of Actors created by the previous receive operation + UPROPERTY(BlueprintReadWrite, Category="Speckle") + TArray Actors; + + // Callback when JSON has been received + virtual void HandleReceive(TSharedPtr RootObject, bool DisplayProgress = false); - ASpeckleUnrealActor* CreateMesh(const TSharedPtr Obj, const TSharedPtr Parent = nullptr); - ASpeckleUnrealActor* CreateBlockInstance(const TSharedPtr Obj); - AActor* CreatePointCloud(const TSharedPtr Obj); + // Callback when error + virtual void HandleError(FString& Message); + virtual void PrintMessage(FString& Message, bool IsError = false) const; }; \ No newline at end of file diff --git a/Source/SpeckleUnreal/Public/Transports/MemoryTransport.h b/Source/SpeckleUnreal/Public/Transports/MemoryTransport.h new file mode 100644 index 0000000..24248e8 --- /dev/null +++ b/Source/SpeckleUnreal/Public/Transports/MemoryTransport.h @@ -0,0 +1,38 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Transport.h" + +#include "MemoryTransport.generated.h" + +/** + * An in memory storage of speckle objects. + */ +UCLASS(Transient, BlueprintType) +class SPECKLEUNREAL_API UMemoryTransport : public UObject, public ITransport +{ + GENERATED_BODY() + + TMap> SpeckleObjects; + +public: + + virtual TSharedPtr GetSpeckleObject(const FString& ObjectId) const override; + virtual void SaveObject(const FString& ObjectId, const TSharedPtr SerializedObject) override; + + virtual bool HasObject(const FString& ObjectId) const override; + + virtual void CopyObjectAndChildren(const FString& ObjectId, + TScriptInterface TargetTransport, + const FTransportCopyObjectCompleteDelegate& OnCompleteAction, + const FTransportErrorDelegate& OnErrorAction) override { unimplemented(); } + + + UFUNCTION(BlueprintPure, Category = "Speckle|Transports") + static UMemoryTransport* CreateEmptyMemoryTransport() + { + UMemoryTransport* Transport = NewObject(); + return Transport; + } +}; diff --git a/Source/SpeckleUnreal/Public/Transports/ServerTransport.h b/Source/SpeckleUnreal/Public/Transports/ServerTransport.h new file mode 100644 index 0000000..8b9ff1f --- /dev/null +++ b/Source/SpeckleUnreal/Public/Transports/ServerTransport.h @@ -0,0 +1,100 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Transport.h" +#include "API/Models/SpeckleStream.h" + +#include "ServerTransport.generated.h" + + +class FHttpModule; + +// Data for graphQL request for object ids. +USTRUCT() +struct FObjectIdRequest +{ + GENERATED_BODY() + + UPROPERTY() + TArray Ids; +}; + +/** + * Transport for receiving objects from a Speckle Server + */ +UCLASS(BlueprintType) +class SPECKLEUNREAL_API UServerTransport : public UObject, public ITransport +{ + GENERATED_BODY() + +protected: + + UPROPERTY() + FString ServerUrl; + + UPROPERTY() + FString StreamId; + + UPROPERTY(meta=(PasswordField)) + FString AuthToken; + + UPROPERTY() + int32 MaxNumberOfObjectsPerRequest = 20000; + + FTransportCopyObjectCompleteDelegate OnComplete; + FTransportErrorDelegate OnError; + + +public: + + + + UFUNCTION(BlueprintPure, Category = "Speckle|Transports") + static UServerTransport* CreateServerTransport(const FString& _ServerUrl, + const FString& _StreamId, + const FString& _AuthToken) + { + UServerTransport* Transport = NewObject(); + Transport->ServerUrl = _ServerUrl; + Transport->StreamId = _StreamId; + Transport->AuthToken = _AuthToken; + return Transport; + } + + virtual TSharedPtr GetSpeckleObject(const FString& ObjectId) const override; + virtual void SaveObject(const FString& ObjectId, const TSharedPtr SerializedObject) override; + + virtual bool HasObject(const FString& ObjectId) const override; + + virtual void CopyObjectAndChildren(const FString& ObjectId, + TScriptInterface TargetTransport, + const FTransportCopyObjectCompleteDelegate& OnCompleteAction, + const FTransportErrorDelegate& OnErrorAction) override; + + +protected: + virtual void HandleRootObjectResponse(const FString& RootObjSerialized, + TScriptInterface TargetTransport, + const FString& ObjectId) const; + + /** + * Iteratively fetches chunks of children + * @param TargetTransport the transport to store the fetched objects + * @param RootObjectId the id of the root object + * @param ChildrenIds array of all children to be fetched + * @param CStart the index in ChildrenIds of the start point of the current chunk + */ + virtual void FetchChildren(TScriptInterface TargetTransport, + const FString& RootObjectId, + const TArray& ChildrenIds, + int32 CStart = 0) const; + + virtual void InvokeOnError(FString& Message) const; + + static bool LoadJson(const FString& ObjectJson, TSharedPtr& OutJsonObject); + + static int32 SplitLines(const FString& Content, TArray& OutLines); +}; + + diff --git a/Source/SpeckleUnreal/Public/Transports/Transport.h b/Source/SpeckleUnreal/Public/Transports/Transport.h new file mode 100644 index 0000000..bcf332e --- /dev/null +++ b/Source/SpeckleUnreal/Public/Transports/Transport.h @@ -0,0 +1,44 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "UObject/Interface.h" +#include "Dom/JsonObject.h" + +#include "Transport.generated.h" + +DECLARE_DELEGATE_OneParam(FTransportCopyObjectCompleteDelegate, TSharedPtr); +DECLARE_DELEGATE_OneParam(FTransportErrorDelegate, FString&); +//DECLARE_DELEGATE_OneParam(FTransportTotalChildrenCountKnownDelegate, int32); +//DECLARE_DELEGATE_OneParam(FTransportProgressDelegate, int32); + +// This class does not need to be modified. +UINTERFACE(Blueprintable) +class UTransport : public UInterface +{ + GENERATED_BODY() +}; + +/** + * + */ +class SPECKLEUNREAL_API ITransport +{ + GENERATED_BODY() + +public: + + virtual void SaveObject(const FString& ObjectId, const TSharedPtr SerializedObject) = 0; + + //virtual void SaveObjectFromTransport(FString& ObjectID, TScriptInterface SourceTransport) = 0; + + virtual TSharedPtr GetSpeckleObject(const FString& ObjectId) const = 0; + + virtual bool HasObject(const FString& ObjectId) const = 0; + + virtual void CopyObjectAndChildren(const FString& ObjectId, + TScriptInterface TargetTransport, + const FTransportCopyObjectCompleteDelegate& OnCompleteAction, + const FTransportErrorDelegate& OnErrorAction) = 0; + +}; diff --git a/Source/SpeckleUnreal/SpeckleUnreal.Build.cs b/Source/SpeckleUnreal/SpeckleUnreal.Build.cs index f9cd0d6..d6195e7 100644 --- a/Source/SpeckleUnreal/SpeckleUnreal.Build.cs +++ b/Source/SpeckleUnreal/SpeckleUnreal.Build.cs @@ -1,4 +1,3 @@ -// Copyright Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; @@ -8,25 +7,35 @@ public SpeckleUnreal(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; - PublicIncludePaths.AddRange( + // #if UE_5_2_OR_LATER + // IWYUSupport = IWYUSupport.Full; + // #else + // bEnforceIWYU = true; + // #endif + // + // bUseUnity = false; + + PublicDefinitions.Add("SPECKLE_CONNECTOR_VERSION=\"2.19.0\""); + + 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", + "HTTP", "Json", "JsonUtilities", "ProceduralMeshComponent", @@ -35,7 +44,7 @@ public SpeckleUnreal(ReadOnlyTargetRules Target) : base(Target) "LidarPointCloudRuntime", // ... add other public dependencies that you statically link with here ... } - ); + ); PrivateDependencyModuleNames.AddRange( @@ -47,7 +56,7 @@ public SpeckleUnreal(ReadOnlyTargetRules Target) : base(Target) "SlateCore", // ... add private dependencies that you statically link with here ... } - ); + ); DynamicallyLoadedModuleNames.AddRange( @@ -55,6 +64,6 @@ public SpeckleUnreal(ReadOnlyTargetRules Target) : base(Target) { // ... add any modules that your module loads dynamically here ... } - ); + ); } } diff --git a/Source/SpeckleUnrealEditor/Private/Conversion/ConverterFactory.cpp b/Source/SpeckleUnrealEditor/Private/Conversion/ConverterFactory.cpp new file mode 100644 index 0000000..fe55231 --- /dev/null +++ b/Source/SpeckleUnrealEditor/Private/Conversion/ConverterFactory.cpp @@ -0,0 +1,86 @@ + +#include "Conversion/ConverterFactory.h" + +#include "Conversion/SpeckleConverter.h" +#include "ClassViewerModule.h" +#include "InterfaceClassFilter.h" +#include "SpeckleUnrealEditorModule.h" +#include "Kismet2/SClassPickerDialog.h" + +#define LOCTEXT_NAMESPACE "FSpeckleUnrealEditorModule" + +UConverterFactory::UConverterFactory(UClass* SClass) + : UConverterFactory() +{ + SupportedClass = SClass; + ConverterClass = SClass; +} + +UConverterFactory::UConverterFactory() +{ + bCreateNew = true; + bEditAfterNew = true; + SupportedClass = USpeckleConverter::StaticClass(); //This is not super valid, but it doesn't matter + + ConverterClass = nullptr; +} + +uint32 UConverterFactory::GetMenuCategories() const +{ + static const uint32 SpeckleCategory = FModuleManager::LoadModuleChecked("SpeckleUnrealEditor").GetSpeckleAssetCategory(); + return SpeckleCategory; +} + +bool UConverterFactory::ConfigureProperties() +{ + // Null the CurveClass so we can get a clean class + ConverterClass = nullptr; + + // Load the classviewer module to display a class picker + FClassViewerModule& ClassViewerModule = FModuleManager::LoadModuleChecked("ClassViewer"); + + // Fill in options + FClassViewerInitializationOptions Options; + Options.Mode = EClassViewerMode::ClassPicker; + + TSharedPtr Filter = MakeShareable(new FInterfaceClassFilter); +#if ENGINE_MAJOR_VERSION >= 5 + Options.ClassFilters.Emplace(Filter.ToSharedRef()); +#else + Options.ClassFilter = Filter; +#endif + + Filter->InterfaceThatMustBeImplemented = USpeckleConverter::StaticClass(); + Filter->bAllowAbstract = false; + Filter->ClassPropertyMetaClass = UObject::StaticClass(); + Filter->AllowedClassFilters = {UObject::StaticClass()}; + const FText TitleText = LOCTEXT("CreateConverterOptions", "Pick Converter Class"); + UClass* ChosenClass = nullptr; + const bool bPressedOk = SClassPickerDialog::PickClass(TitleText, Options, ChosenClass, UObject::StaticClass()); + + if ( bPressedOk ) + { + ConverterClass = ChosenClass; + } + + return bPressedOk; +} + + +UObject* UConverterFactory::FactoryCreateNew(UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, + UObject* Context, FFeedbackContext* Warn) +{ + UObject* NewObjectAsset = nullptr; + if(ConverterClass != nullptr) + { + NewObjectAsset = NewObject(InParent, ConverterClass, Name, Flags); + } + return NewObjectAsset; +} + + FText UConverterFactory::GetDisplayName() const + { + return LOCTEXT("ConverterFactoryDisplayName", "Speckle Converter"); + } + +#undef LOCTEXT_NAMESPACE diff --git a/Source/SpeckleUnrealEditor/Private/SpeckleUnrealEditorModule.cpp b/Source/SpeckleUnrealEditor/Private/SpeckleUnrealEditorModule.cpp new file mode 100644 index 0000000..d55f312 --- /dev/null +++ b/Source/SpeckleUnrealEditor/Private/SpeckleUnrealEditorModule.cpp @@ -0,0 +1,58 @@ + +#include "SpeckleUnrealEditorModule.h" + +#include "AssetToolsModule.h" +#include "IAssetTools.h" + +#include "Conversion/ConverterActions.h" +#include "Conversion/SpeckleConverter.h" + +#define LOCTEXT_NAMESPACE "FSpeckleUnrealEditorModule" + +uint32 FSpeckleUnrealEditorModule::GetSpeckleAssetCategory() const +{ + return SpeckleAssetCategoryBit; +} + +void FSpeckleUnrealEditorModule::StartupModule() +{ + // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module +#if WITH_EDITOR + if (GIsEditor) + { + IAssetTools& AssetTools = FModuleManager::LoadModuleChecked("AssetTools").Get(); + + // Register Speckle Category + SpeckleAssetCategoryBit = AssetTools.RegisterAdvancedAssetCategory(FName(TEXT("Speckle")), LOCTEXT("SpeckleCategoryText","Speckle")); + + + // See UAssetToolsImpl::GetNewAssetFactories() for reference + for (TObjectIterator It; It; ++It) + { + UClass* Class = *It; + + // Create FConverterActions for USpeckleConverter types + if ( Class->ImplementsInterface(USpeckleConverter::StaticClass()) + && !Class->HasAnyClassFlags(CLASS_Abstract) + && !Class->GetFName().ToString().Contains(TEXT("REINST"))) //Ignore hot-reloaded BPs + { + AssetTools.RegisterAssetTypeActions(MakeShareable(new FConverterActions(Class, SpeckleAssetCategoryBit))); + } + } + + AssetTools.RegisterAssetTypeActions(MakeShareable(new FConverterActions(USpeckleConverter::StaticClass(), SpeckleAssetCategoryBit))); + + + } +#endif +} + +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. +} + +#undef LOCTEXT_NAMESPACE + +IMPLEMENT_MODULE(FSpeckleUnrealEditorModule, SpeckleUnrealEditor) \ No newline at end of file diff --git a/Source/SpeckleUnrealEditor/Public/Conversion/ConverterActions.h b/Source/SpeckleUnrealEditor/Public/Conversion/ConverterActions.h new file mode 100644 index 0000000..bd362eb --- /dev/null +++ b/Source/SpeckleUnrealEditor/Public/Conversion/ConverterActions.h @@ -0,0 +1,32 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "AssetTypeActions_Base.h" + + +/** + * Asset action for ISpeckleConverter implementors. + */ +class FConverterActions : public FAssetTypeActions_Base +{ +private: + UClass* SupportedClass; + uint32 Category; + +public: + explicit FConverterActions(UClass* SupportedClass, uint32 Category) + { + this->SupportedClass = SupportedClass; + this->Category = Category; + } + + // IAssetTypeActions Implementation + virtual FText GetName() const override { return SupportedClass->GetDisplayNameText(); } + virtual UClass* GetSupportedClass() const override { return SupportedClass; } + virtual FColor GetTypeColor() const override { return FColor(59, 130, 246); } + virtual bool CanLocalize() const override { return false; } + + virtual uint32 GetCategories() override { return Category; } + +}; diff --git a/Source/SpeckleUnrealEditor/Public/Conversion/ConverterFactory.h b/Source/SpeckleUnrealEditor/Public/Conversion/ConverterFactory.h new file mode 100644 index 0000000..53fd685 --- /dev/null +++ b/Source/SpeckleUnrealEditor/Public/Conversion/ConverterFactory.h @@ -0,0 +1,30 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Factories/Factory.h" + +#include "ConverterFactory.generated.h" + +/** + * Factory for ISpeckleConverter classes to appear in the asset creation context menu. + */ +UCLASS() +class SPECKLEUNREALEDITOR_API UConverterFactory : public UFactory +{ + GENERATED_BODY() +protected: + explicit UConverterFactory(UClass* SupportedClass); +public: + UPROPERTY(EditAnywhere, Category="Speckle|Factories", meta = (MustImplement = USpeckleConverter)) + UClass* ConverterClass; + + UConverterFactory(); + + virtual uint32 GetMenuCategories() const override; + + virtual bool ConfigureProperties() override; + virtual UObject* FactoryCreateNew(UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn) override; + virtual FText GetDisplayName() const override; + +}; \ No newline at end of file diff --git a/Source/SpeckleUnrealEditor/Public/InterfaceClassFilter.h b/Source/SpeckleUnrealEditor/Public/InterfaceClassFilter.h new file mode 100644 index 0000000..9d9e517 --- /dev/null +++ b/Source/SpeckleUnrealEditor/Public/InterfaceClassFilter.h @@ -0,0 +1,66 @@ + +#pragma once + +#include "ClassViewerModule.h" +#include "ClassViewerFilter.h" + + +/** + * Class filter for classes that implement a given interface + * based on FPropertyEditorClassFilter + */ +class FInterfaceClassFilter : public IClassViewerFilter +{ +public: + /** The meta class for the property that classes must be a child-of. */ + const UClass* ClassPropertyMetaClass; + + /** The interface that must be implemented. */ + const UClass* InterfaceThatMustBeImplemented; + + /** Whether or not abstract classes are allowed. */ + bool bAllowAbstract; + + /** Classes that can be picked */ + TArray AllowedClassFilters; + + /** Classes that can't be picked */ + TArray DisallowedClassFilters; + + virtual bool IsClassAllowed(const FClassViewerInitializationOptions& InInitOptions, const UClass* InClass, TSharedRef< FClassViewerFilterFuncs > InFilterFuncs ) override + { + return IsClassAllowedHelper(InClass); + } + + virtual bool IsUnloadedClassAllowed(const FClassViewerInitializationOptions& InInitOptions, const TSharedRef< const IUnloadedBlueprintData > InBlueprint, TSharedRef< FClassViewerFilterFuncs > InFilterFuncs) override + { + return IsClassAllowedHelper(InBlueprint); + } + +private: + + template + bool IsClassAllowedHelper(TClass InClass) + { + bool bMatchesFlags = !InClass->HasAnyClassFlags(CLASS_Hidden | CLASS_HideDropDown | CLASS_Deprecated) && + (bAllowAbstract || !InClass->HasAnyClassFlags(CLASS_Abstract)); + + if (bMatchesFlags && InClass->IsChildOf(ClassPropertyMetaClass) + && (!InterfaceThatMustBeImplemented || InClass->ImplementsInterface(InterfaceThatMustBeImplemented))) + { + auto PredicateFn = [InClass](const UClass* Class) + { + return InClass->IsChildOf(Class); + }; + + if (DisallowedClassFilters.FindByPredicate(PredicateFn) == nullptr && + (AllowedClassFilters.Num() == 0 || AllowedClassFilters.FindByPredicate(PredicateFn) != nullptr)) + { + return true; + } + } + + return false; + } + +}; \ No newline at end of file diff --git a/Source/SpeckleUnrealEditor/Public/SpeckleUnrealEditorModule.h b/Source/SpeckleUnrealEditor/Public/SpeckleUnrealEditorModule.h new file mode 100644 index 0000000..359da31 --- /dev/null +++ b/Source/SpeckleUnrealEditor/Public/SpeckleUnrealEditorModule.h @@ -0,0 +1,24 @@ + +#pragma once + +#include "CoreMinimal.h" +#include "Modules/ModuleManager.h" + +class FSpeckleUnrealEditorModule : public IModuleInterface +{ + +#if WITH_EDITORONLY_DATA +protected: + uint32 SpeckleAssetCategoryBit = 0; +#endif + +#if WITH_EDITOR +public: + virtual uint32 GetSpeckleAssetCategory() const; +#endif + +public: + /** IModuleInterface implementation */ + virtual void StartupModule() override; + virtual void ShutdownModule() override; +}; diff --git a/Source/SpeckleUnrealEditor/SpeckleUnrealEditor.Build.cs b/Source/SpeckleUnrealEditor/SpeckleUnrealEditor.Build.cs new file mode 100644 index 0000000..0a8b59e --- /dev/null +++ b/Source/SpeckleUnrealEditor/SpeckleUnrealEditor.Build.cs @@ -0,0 +1,57 @@ + +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", + "UnrealEd", + "SpeckleUnreal", + // ... add other public dependencies that you statically link with here ... + } + ); + + + PrivateDependencyModuleNames.AddRange( + new string[] + { + "CoreUObject", + "Engine", + "Slate", + "SlateCore", + // ... add private dependencies that you statically link with here ... + } + ); + + + DynamicallyLoadedModuleNames.AddRange( + new string[] + { + // ... add any modules that your module loads dynamically here ... + } + ); + } +} diff --git a/SpeckleUnreal.uplugin b/SpeckleUnreal.uplugin index fab1e3a..eef49c1 100644 --- a/SpeckleUnreal.uplugin +++ b/SpeckleUnreal.uplugin @@ -1,15 +1,15 @@ { "FileVersion": 3, "Version": 1, - "VersionName": "0.0.1", - "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.", + "VersionName": "2.19.0", + "FriendlyName": "Speckle Unreal", + "Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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", - "MarketplaceURL": "", - "SupportURL": "", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81", + "SupportURL": "https://speckle.community/", "CanContainContent": true, "IsBetaVersion": true, "IsExperimentalVersion": false, @@ -18,7 +18,14 @@ { "Name": "SpeckleUnreal", "Type": "Runtime", - "LoadingPhase": "Default" + "LoadingPhase": "Default", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] + }, + { + "Name": "SpeckleUnrealEditor", + "Type": "Editor", + "LoadingPhase": "PostEngineInit", + "WhitelistPlatforms": [ "Win64", "Linux", "Mac" ] } ], "Plugins": [