From bad4cc5c177d65868a8cdc9468a69fd49555244e Mon Sep 17 00:00:00 2001 From: Stephen Hodgson Date: Thu, 27 Jul 2023 13:04:45 -0400 Subject: [PATCH] refactor project convert init on load method to wait until editor is done updating before attempting to reconnect loose nodes --- .editorconfig | 8 - .github/workflows/build.yml | 38 + .github/workflows/upm-subtree-split.yml | 35 + .gitignore | 102 +- CONTRIBUTING.md | 40 - Scripts/Editor/NodeEditorAssetModProcessor.cs | 66 - Scripts/Editor/NodeGraphImporter.cs | 45 - package.json | 7 - Scripts.meta => xNode/Assets/Scenes.meta | 5 +- xNode/Assets/Scenes/SampleScene.unity | 267 ++++ .../Assets/Scenes/SampleScene.unity.meta | 4 +- xNode/Packages/com.pillow.xnode/.editorconfig | 75 + .../.github/workflows/publish.yml | 31 + xNode/Packages/com.pillow.xnode/.npmignore | 2 + xNode/Packages/com.pillow.xnode/.npmrc | 1 + .../Packages/com.pillow.xnode/LICENSE.md | 0 .../Packages/com.pillow.xnode/LICENSE.md.meta | 0 .../Packages/com.pillow.xnode/Runtime.meta | 5 +- .../com.pillow.xnode/Runtime}/Attributes.meta | 0 .../Runtime}/Attributes/NodeEnum.cs | 0 .../Runtime}/Attributes/NodeEnum.cs.meta | 0 .../Attributes/PortTypeOverrideAttribute.cs | 24 +- .../PortTypeOverrideAttribute.cs.meta | 0 .../com.pillow.xnode/Runtime}/Editor.meta | 0 .../Runtime}/Editor/AdvancedGenericMenu.cs | 28 +- .../Editor/AdvancedGenericMenu.cs.meta | 0 .../Runtime}/Editor/Drawers.meta | 0 .../Runtime}/Editor/Drawers/NodeEnumDrawer.cs | 17 +- .../Editor/Drawers/NodeEnumDrawer.cs.meta | 0 .../Runtime}/Editor/Drawers/Odin.meta | 0 .../Odin/InNodeEditorAttributeProcessor.cs | 0 .../InNodeEditorAttributeProcessor.cs.meta | 0 .../Drawers/Odin/InputAttributeDrawer.cs | 0 .../Drawers/Odin/InputAttributeDrawer.cs.meta | 0 .../Drawers/Odin/OutputAttributeDrawer.cs | 0 .../Odin/OutputAttributeDrawer.cs.meta | 0 .../Runtime}/Editor/GraphAndNodeEditor.cs | 6 +- .../Editor/GraphAndNodeEditor.cs.meta | 0 .../Editor/GraphRenameFixAssetProcessor.cs | 6 +- .../GraphRenameFixAssetProcessor.cs.meta | 0 .../Runtime}/Editor/Internal.meta | 0 .../Editor/Internal/RerouteReference.cs | 0 .../Editor/Internal/RerouteReference.cs.meta | 0 .../Runtime}/Editor/NodeEditor.cs | 404 ++--- .../Runtime}/Editor/NodeEditor.cs.meta | 0 .../Runtime}/Editor/NodeEditorAction.cs | 1266 +++++++++------- .../Runtime}/Editor/NodeEditorAction.cs.meta | 0 .../Editor/NodeEditorAssetModProcessor.cs | 103 ++ .../NodeEditorAssetModProcessor.cs.meta | 0 .../Runtime}/Editor/NodeEditorBase.cs | 82 +- .../Runtime}/Editor/NodeEditorBase.cs.meta | 0 .../Runtime}/Editor/NodeEditorGUI.cs | 1344 +++++++++-------- .../Runtime}/Editor/NodeEditorGUI.cs.meta | 0 .../Runtime}/Editor/NodeEditorGUILayout.cs | 325 ++-- .../Editor/NodeEditorGUILayout.cs.meta | 0 .../Runtime}/Editor/NodeEditorPreferences.cs | 111 +- .../Editor/NodeEditorPreferences.cs.meta | 0 .../Runtime}/Editor/NodeEditorReflection.cs | 381 ++--- .../Editor/NodeEditorReflection.cs.meta | 0 .../Runtime}/Editor/NodeEditorResources.cs | 202 +-- .../Editor/NodeEditorResources.cs.meta | 0 .../Runtime}/Editor/NodeEditorUtilities.cs | 689 +++++---- .../Editor/NodeEditorUtilities.cs.meta | 0 .../Runtime}/Editor/NodeEditorWindow.cs | 469 +++--- .../Runtime}/Editor/NodeEditorWindow.cs.meta | 0 .../Runtime}/Editor/NodeGraphEditor.cs | 140 +- .../Runtime}/Editor/NodeGraphEditor.cs.meta | 0 .../Runtime/Editor/NodeGraphImporter.cs | 69 + .../Runtime}/Editor/NodeGraphImporter.cs.meta | 0 .../Runtime}/Editor/RenamePopup.cs | 20 +- .../Runtime}/Editor/RenamePopup.cs.meta | 0 .../Runtime}/Editor/Resources.meta | 0 .../Editor/Resources/ScriptTemplates.meta | 0 .../xNode_NodeGraphTemplate.cs.txt | 0 .../xNode_NodeGraphTemplate.cs.txt.meta | 0 .../ScriptTemplates/xNode_NodeTemplate.cs.txt | 0 .../xNode_NodeTemplate.cs.txt.meta | 0 .../Runtime}/Editor/Resources/xnode_dot.png | Bin .../Editor/Resources/xnode_dot.png.meta | 0 .../Editor/Resources/xnode_dot_outer.png | Bin .../Editor/Resources/xnode_dot_outer.png.meta | 0 .../Runtime}/Editor/Resources/xnode_node.png | Bin .../Editor/Resources/xnode_node.png.meta | 0 .../Editor/Resources/xnode_node_highlight.png | Bin .../Resources/xnode_node_highlight.png.meta | 0 .../Editor/Resources/xnode_node_workfile.psd | Bin .../Resources/xnode_node_workfile.psd.meta | 0 .../Runtime}/Editor/SceneGraphEditor.cs | 14 +- .../Runtime}/Editor/SceneGraphEditor.cs.meta | 0 .../Runtime}/Editor/XNodeEditor.asmdef | 0 .../Runtime}/Editor/XNodeEditor.asmdef.meta | 0 .../com.pillow.xnode/Runtime}/Node.cs | 924 ++++++------ .../com.pillow.xnode/Runtime}/Node.cs.meta | 0 .../Runtime}/NodeDataCache.cs | 119 +- .../Runtime}/NodeDataCache.cs.meta | 0 .../com.pillow.xnode/Runtime}/NodeGraph.cs | 276 ++-- .../Runtime}/NodeGraph.cs.meta | 0 .../com.pillow.xnode/Runtime}/NodePort.cs | 974 ++++++------ .../Runtime}/NodePort.cs.meta | 0 .../com.pillow.xnode/Runtime}/SceneGraph.cs | 0 .../Runtime}/SceneGraph.cs.meta | 0 .../com.pillow.xnode/Runtime}/XNode.asmdef | 0 .../Runtime}/XNode.asmdef.meta | 0 xNode/Packages/com.pillow.xnode/package.json | 20 + .../com.pillow.xnode/package.json.meta | 0 .../~Documentation~/README.md | 0 xNode/Packages/manifest.json | 38 + xNode/ProjectSettings/AudioManager.asset | 19 + .../ProjectSettings/ClusterInputManager.asset | 6 + xNode/ProjectSettings/DynamicsManager.asset | 34 + .../ProjectSettings/EditorBuildSettings.asset | 8 + xNode/ProjectSettings/EditorSettings.asset | 30 + xNode/ProjectSettings/GraphicsSettings.asset | 63 + xNode/ProjectSettings/InputManager.asset | 295 ++++ xNode/ProjectSettings/MemorySettings.asset | 35 + xNode/ProjectSettings/NavMeshAreas.asset | 91 ++ .../PackageManagerSettings.asset | 35 + .../Settings.json | 5 + xNode/ProjectSettings/Physics2DSettings.asset | 56 + xNode/ProjectSettings/PresetManager.asset | 7 + xNode/ProjectSettings/ProjectSettings.asset | 759 ++++++++++ xNode/ProjectSettings/ProjectVersion.txt | 2 + xNode/ProjectSettings/QualitySettings.asset | 232 +++ xNode/ProjectSettings/TagManager.asset | 43 + xNode/ProjectSettings/TimeManager.asset | 9 + .../UnityConnectSettings.asset | 36 + xNode/ProjectSettings/VFXManager.asset | 12 + .../VersionControlSettings.asset | 8 + xNode/ProjectSettings/XRSettings.asset | 10 + 129 files changed, 6996 insertions(+), 3581 deletions(-) delete mode 100644 .editorconfig create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/upm-subtree-split.yml delete mode 100644 CONTRIBUTING.md delete mode 100644 Scripts/Editor/NodeEditorAssetModProcessor.cs delete mode 100644 Scripts/Editor/NodeGraphImporter.cs delete mode 100644 package.json rename Scripts.meta => xNode/Assets/Scenes.meta (57%) create mode 100644 xNode/Assets/Scenes/SampleScene.unity rename CONTRIBUTING.md.meta => xNode/Assets/Scenes/SampleScene.unity.meta (62%) create mode 100644 xNode/Packages/com.pillow.xnode/.editorconfig create mode 100644 xNode/Packages/com.pillow.xnode/.github/workflows/publish.yml create mode 100644 xNode/Packages/com.pillow.xnode/.npmignore create mode 100644 xNode/Packages/com.pillow.xnode/.npmrc rename LICENSE.md => xNode/Packages/com.pillow.xnode/LICENSE.md (100%) rename LICENSE.md.meta => xNode/Packages/com.pillow.xnode/LICENSE.md.meta (100%) rename README.md.meta => xNode/Packages/com.pillow.xnode/Runtime.meta (57%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Attributes.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Attributes/NodeEnum.cs (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Attributes/NodeEnum.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Attributes/PortTypeOverrideAttribute.cs (97%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Attributes/PortTypeOverrideAttribute.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/AdvancedGenericMenu.cs (93%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/AdvancedGenericMenu.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/NodeEnumDrawer.cs (86%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/NodeEnumDrawer.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin/InputAttributeDrawer.cs (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin/InputAttributeDrawer.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin/OutputAttributeDrawer.cs (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Drawers/Odin/OutputAttributeDrawer.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/GraphAndNodeEditor.cs (92%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/GraphAndNodeEditor.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/GraphRenameFixAssetProcessor.cs (92%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/GraphRenameFixAssetProcessor.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Internal.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Internal/RerouteReference.cs (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Internal/RerouteReference.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditor.cs (81%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditor.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorAction.cs (68%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorAction.cs.meta (100%) create mode 100644 xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAssetModProcessor.cs rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorAssetModProcessor.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorBase.cs (65%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorBase.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorGUI.cs (56%) mode change 100755 => 100644 rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorGUI.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorGUILayout.cs (68%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorGUILayout.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorPreferences.cs (79%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorPreferences.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorReflection.cs (78%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorReflection.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorResources.cs (79%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorResources.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorUtilities.cs (74%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorUtilities.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorWindow.cs (72%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeEditorWindow.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeGraphEditor.cs (78%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeGraphEditor.cs.meta (100%) create mode 100644 xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphImporter.cs rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/NodeGraphImporter.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/RenamePopup.cs (90%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/RenamePopup.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/ScriptTemplates.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_dot.png (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_dot.png.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_dot_outer.png (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_dot_outer.png.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_node.png (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_node.png.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_node_highlight.png (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_node_highlight.png.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_node_workfile.psd (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/Resources/xnode_node_workfile.psd.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/SceneGraphEditor.cs (86%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/SceneGraphEditor.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/XNodeEditor.asmdef (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Editor/XNodeEditor.asmdef.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Node.cs (89%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/Node.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/NodeDataCache.cs (75%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/NodeDataCache.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/NodeGraph.cs (79%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/NodeGraph.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/NodePort.cs (74%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/NodePort.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/SceneGraph.cs (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/SceneGraph.cs.meta (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/XNode.asmdef (100%) rename {Scripts => xNode/Packages/com.pillow.xnode/Runtime}/XNode.asmdef.meta (100%) create mode 100644 xNode/Packages/com.pillow.xnode/package.json rename package.json.meta => xNode/Packages/com.pillow.xnode/package.json.meta (100%) rename README.md => xNode/Packages/com.pillow.xnode/~Documentation~/README.md (100%) create mode 100644 xNode/Packages/manifest.json create mode 100644 xNode/ProjectSettings/AudioManager.asset create mode 100644 xNode/ProjectSettings/ClusterInputManager.asset create mode 100644 xNode/ProjectSettings/DynamicsManager.asset create mode 100644 xNode/ProjectSettings/EditorBuildSettings.asset create mode 100644 xNode/ProjectSettings/EditorSettings.asset create mode 100644 xNode/ProjectSettings/GraphicsSettings.asset create mode 100644 xNode/ProjectSettings/InputManager.asset create mode 100644 xNode/ProjectSettings/MemorySettings.asset create mode 100644 xNode/ProjectSettings/NavMeshAreas.asset create mode 100644 xNode/ProjectSettings/PackageManagerSettings.asset create mode 100644 xNode/ProjectSettings/Packages/com.unity.testtools.codecoverage/Settings.json create mode 100644 xNode/ProjectSettings/Physics2DSettings.asset create mode 100644 xNode/ProjectSettings/PresetManager.asset create mode 100644 xNode/ProjectSettings/ProjectSettings.asset create mode 100644 xNode/ProjectSettings/ProjectVersion.txt create mode 100644 xNode/ProjectSettings/QualitySettings.asset create mode 100644 xNode/ProjectSettings/TagManager.asset create mode 100644 xNode/ProjectSettings/TimeManager.asset create mode 100644 xNode/ProjectSettings/UnityConnectSettings.asset create mode 100644 xNode/ProjectSettings/VFXManager.asset create mode 100644 xNode/ProjectSettings/VersionControlSettings.asset create mode 100644 xNode/ProjectSettings/XRSettings.asset diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 03c2cb5..0000000 --- a/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -root = true - -[*.cs] -indent_style = space -indent_size = 4 -end_of_line = crlf -insert_final_newline = false -trim_trailing_whitespace = true diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..aec9b6d --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,38 @@ +name: build + +on: + pull_request: + branches: + - '*' + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + include: + - os: windows + build-target: Android + + steps: + - uses: actions/checkout@v3 + with: + clean: false + lfs: true + + # Installs the Unity Editor based on your project version text file + # sets -> env.UNITY_EDITOR_PATH + # sets -> env.UNITY_PROJECT_PATH + # https://github.com/XRTK/unity-setup + - uses: xrtk/unity-setup@v7.2 + with: + build-targets: ${{ matrix.build-target }} + + - name: Unity Build (${{ matrix.build-target }}) + uses: RageAgainstThePixel/unity-build@v5 + with: + build-target: ${{ matrix.build-target }} + publish-artifacts: false diff --git a/.github/workflows/upm-subtree-split.yml b/.github/workflows/upm-subtree-split.yml new file mode 100644 index 0000000..af28306 --- /dev/null +++ b/.github/workflows/upm-subtree-split.yml @@ -0,0 +1,35 @@ +name: upm-subtree-split + +on: + push: + branches: + - main + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + upm-subtree-split: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + token: ${{ secrets.CI_TOKEN }} + fetch-depth: 0 + + - name: upm subtree split + run: | + # upm subtree split + git config user.name github-actions + git config user.email github-actions@github.com + git fetch --all --tags + $packageDir = Get-Item -Path "**/Packages/com.*" | Select-Object -ExpandProperty FullName + $packageDir = $packageDir.replace('${{ github.workspace }}/','') + Write-Host $packageDir + git subtree split --prefix="$packageDir" -b upm + git checkout upm + git fetch origin upm + git rebase origin/upm --reapply-cherry-picks + git push origin upm --force-with-lease --tags --set-upstream --verbose + working-directory: ${{ github.workspace }} + shell: pwsh diff --git a/.gitignore b/.gitignore index c75a01e..d7bb963 100644 --- a/.gitignore +++ b/.gitignore @@ -1,30 +1,84 @@ -/[Ll]ibrary/ -/[Tt]emp/ -/[Oo]bj/ -/[Bb]uild/ +# ============ # +# System Files # +# ============ # +.DS_Store +._* -# Autogenerated VS/MD solution and project files -*.csproj -*.unityproj -*.sln -*.suo -*.tmp -*.user +# =============== # +# Unity generated # +# =============== # +[Aa]pp/ +[Aa]pp.meta +[Bb]in/ +[Bb]uilds/ +[Bb]uild/ +[Ll]ibrary/ +[Ll]ogs/ +[Oo]bj/ +[Tt]emp/ +UserSettings/ +UWP/ +WindowsStoreApp/ +UnityGenerated/ +UnityPackageManager/ +.out/ +.gradle/ +project.json +project.lock.json +*.package +TextMesh Pro.meta +TextMesh Pro/ +UIElementsSchema/ +*packages-lock.json + +# ============ # +# Certificates # +# ============ # +*.cert +*.privkey +*.pfx +*.pfx.meta + +# ===================================== # +# Visual Studio / MonoDevelop generated # +# ===================================== # +.vs/ +ExportedObj/ +obj/ +*.svd *.userprefs +/*.csproj +*.csproj *.pidb -*.booproj +*.suo +/*.sln +*.sln +*.user +*.unityproj +*.ipch +*.opensdf +*.sdf +*.tlog +*.log +*.idb +*.opendb +*.vsconfig -# Unity3D generated meta files -*.pidb.meta +# ============================ # +# Visual Studio Code Generated # +# ============================ # +.vscode/ -# Unity3D Generated File On Crash Reports -sysinfo.txt +# ========================= # +# Jetbrains Rider Generated # +# ========================= # +.idea/ +_ReSharper.Caches -/Examples/ - -.git.meta -.gitignore.meta -.gitattributes.meta - -# OS X only: -.DS_Store \ No newline at end of file +# ===================== # +# Project Specific List # +# ===================== # +--Version/ +artifacts/ +StreamingAssets/ +StreamingAssets.meta diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 10d780a..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,40 +0,0 @@ -## Contributing to xNode -💙Thank you for taking the time to contribute💙 - -If you haven't already, join our [Discord channel](https://discord.gg/qgPrHv4)! - -## Pull Requests -Try to keep your pull requests relevant, neat, and manageable. If you are adding multiple features, split them into separate PRs. -These are the main points to follow: - -1) Use formatting which is consistent with the rest of xNode base (see below) -2) Keep _one feature_ per PR (see below) -3) xNode aims to be compatible with C# 4.x, do not use new language features -4) Avoid including irellevant whitespace or formatting changes -5) Comment your code -6) Spell check your code / comments -7) Use concrete types, not *var* -8) Use english language - -## New features -xNode aims to be simple and extendible, not trying to fix all of Unity's shortcomings. - -Approved changes might be rejected if bundled with rejected changes, so keep PRs as separate as possible. - -If your feature aims to cover something not related to editing nodes, it generally won't be accepted. If in doubt, ask on the Discord channel. - -## Coding conventions -Using consistent formatting is key to having a clean git history. Skim through the code and you'll get the hang of it quickly. -* Methods, Types and properties PascalCase -* Variables camelCase -* Public methods XML commented. Params described if not obvious -* Explicit usage of brackets when doing multiple math operations on the same line - -## Formatting -I use VSCode with the C# FixFormat extension and the following setting overrides: -```json -"csharpfixformat.style.spaces.beforeParenthesis": false, -"csharpfixformat.style.indent.regionIgnored": true -``` -* Open braces on same line as condition -* 4 spaces for indentation. diff --git a/Scripts/Editor/NodeEditorAssetModProcessor.cs b/Scripts/Editor/NodeEditorAssetModProcessor.cs deleted file mode 100644 index f4b14a2..0000000 --- a/Scripts/Editor/NodeEditorAssetModProcessor.cs +++ /dev/null @@ -1,66 +0,0 @@ -using UnityEditor; -using UnityEngine; -using System.IO; - -namespace XNodeEditor { - /// Deals with modified assets - class NodeEditorAssetModProcessor : UnityEditor.AssetModificationProcessor { - - /// Automatically delete Node sub-assets before deleting their script. - /// This is important to do, because you can't delete null sub assets. - /// For another workaround, see: https://gitlab.com/RotaryHeart-UnityShare/subassetmissingscriptdelete - private static AssetDeleteResult OnWillDeleteAsset (string path, RemoveAssetOptions options) { - // Skip processing anything without the .cs extension - if (Path.GetExtension(path) != ".cs") return AssetDeleteResult.DidNotDelete; - - // Get the object that is requested for deletion - UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath (path); - - // If we aren't deleting a script, return - if (!(obj is UnityEditor.MonoScript)) return AssetDeleteResult.DidNotDelete; - - // Check script type. Return if deleting a non-node script - UnityEditor.MonoScript script = obj as UnityEditor.MonoScript; - System.Type scriptType = script.GetClass (); - if (scriptType == null || (scriptType != typeof (XNode.Node) && !scriptType.IsSubclassOf (typeof (XNode.Node)))) return AssetDeleteResult.DidNotDelete; - - // Find all ScriptableObjects using this script - string[] guids = AssetDatabase.FindAssets ("t:" + scriptType); - for (int i = 0; i < guids.Length; i++) { - string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]); - Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath); - for (int k = 0; k < objs.Length; k++) { - XNode.Node node = objs[k] as XNode.Node; - if (node.GetType () == scriptType) { - if (node != null && node.graph != null) { - // Delete the node and notify the user - Debug.LogWarning (node.name + " of " + node.graph + " depended on deleted script and has been removed automatically.", node.graph); - node.graph.RemoveNode (node); - } - } - } - } - // We didn't actually delete the script. Tell the internal system to carry on with normal deletion procedure - return AssetDeleteResult.DidNotDelete; - } - - /// Automatically re-add loose node assets to the Graph node list - [InitializeOnLoadMethod] - private static void OnReloadEditor () { - // Find all NodeGraph assets - string[] guids = AssetDatabase.FindAssets ("t:" + typeof (XNode.NodeGraph)); - for (int i = 0; i < guids.Length; i++) { - string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]); - XNode.NodeGraph graph = AssetDatabase.LoadAssetAtPath (assetpath, typeof (XNode.NodeGraph)) as XNode.NodeGraph; - graph.nodes.RemoveAll(x => x == null); //Remove null items - Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath); - // Ensure that all sub node assets are present in the graph node list - for (int u = 0; u < objs.Length; u++) { - // Ignore null sub assets - if (objs[u] == null) continue; - if (!graph.nodes.Contains (objs[u] as XNode.Node)) graph.nodes.Add(objs[u] as XNode.Node); - } - } - } - } -} \ No newline at end of file diff --git a/Scripts/Editor/NodeGraphImporter.cs b/Scripts/Editor/NodeGraphImporter.cs deleted file mode 100644 index 3faf54f..0000000 --- a/Scripts/Editor/NodeGraphImporter.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEditor.Experimental.AssetImporters; -using UnityEngine; -using XNode; - -namespace XNodeEditor { - /// Deals with modified assets - class NodeGraphImporter : AssetPostprocessor { - private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { - foreach (string path in importedAssets) { - // Skip processing anything without the .asset extension - if (Path.GetExtension(path) != ".asset") continue; - - // Get the object that is requested for deletion - NodeGraph graph = AssetDatabase.LoadAssetAtPath(path); - if (graph == null) continue; - - // Get attributes - Type graphType = graph.GetType(); - NodeGraph.RequireNodeAttribute[] attribs = Array.ConvertAll( - graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true), x => x as NodeGraph.RequireNodeAttribute); - - Vector2 position = Vector2.zero; - foreach (NodeGraph.RequireNodeAttribute attrib in attribs) { - if (attrib.type0 != null) AddRequired(graph, attrib.type0, ref position); - if (attrib.type1 != null) AddRequired(graph, attrib.type1, ref position); - if (attrib.type2 != null) AddRequired(graph, attrib.type2, ref position); - } - } - } - - private static void AddRequired(NodeGraph graph, Type type, ref Vector2 position) { - if (!graph.nodes.Any(x => x.GetType() == type)) { - XNode.Node node = graph.AddNode(type); - node.position = position; - position.x += 200; - if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type); - if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(graph))) AssetDatabase.AddObjectToAsset(node, graph); - } - } - } -} \ No newline at end of file diff --git a/package.json b/package.json deleted file mode 100644 index 9c1ec7d..0000000 --- a/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "com.github.siccity.xnode", - "description": "xNode provides a set of APIs and an editor interface for creating and editing custom node graphs.", - "version": "1.8.0", - "unity": "2018.1", - "displayName": "xNode" -} diff --git a/Scripts.meta b/xNode/Assets/Scenes.meta similarity index 57% rename from Scripts.meta rename to xNode/Assets/Scenes.meta index ab712b6..cdcb446 100644 --- a/Scripts.meta +++ b/xNode/Assets/Scenes.meta @@ -1,9 +1,8 @@ fileFormatVersion: 2 -guid: 657b15cb3ec32a24ca80faebf094d0f4 +guid: 999581c3922a8f942959bcb0a0fc7d18 folderAsset: yes -timeCreated: 1505418321 -licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/xNode/Assets/Scenes/SampleScene.unity b/xNode/Assets/Scenes/SampleScene.unity new file mode 100644 index 0000000..2221b04 --- /dev/null +++ b/xNode/Assets/Scenes/SampleScene.unity @@ -0,0 +1,267 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 705507994} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 12 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 500 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 2 + m_PVRDenoiserTypeDirect: 0 + m_PVRDenoiserTypeIndirect: 0 + m_PVRDenoiserTypeAO: 0 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 0 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 + m_LightingDataAsset: {fileID: 0} + m_LightingSettings: {fileID: 0} +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &705507993 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 705507995} + - component: {fileID: 705507994} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &705507994 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 705507993} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 1 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &705507995 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 705507993} + m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0} +--- !u!1 &963194225 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 963194228} + - component: {fileID: 963194227} + - component: {fileID: 963194226} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &963194226 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 963194225} + m_Enabled: 1 +--- !u!20 &963194227 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 963194225} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_projectionMatrixMode: 1 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_GateFitMode: 2 + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &963194228 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 963194225} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/CONTRIBUTING.md.meta b/xNode/Assets/Scenes/SampleScene.unity.meta similarity index 62% rename from CONTRIBUTING.md.meta rename to xNode/Assets/Scenes/SampleScene.unity.meta index 5d7c128..952bd1e 100644 --- a/CONTRIBUTING.md.meta +++ b/xNode/Assets/Scenes/SampleScene.unity.meta @@ -1,6 +1,6 @@ fileFormatVersion: 2 -guid: bc1db8b29c76d44648c9c86c2dfade6d -TextScriptImporter: +guid: 9fc0d4010bbf28b4594072e72b8655ab +DefaultImporter: externalObjects: {} userData: assetBundleName: diff --git a/xNode/Packages/com.pillow.xnode/.editorconfig b/xNode/Packages/com.pillow.xnode/.editorconfig new file mode 100644 index 0000000..c485248 --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/.editorconfig @@ -0,0 +1,75 @@ +# https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/code-style-rule-options + +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = true +trim_trailing_whitespace = true +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_open_brace = all + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:error + +# Code-block preferences +csharp_prefer_braces = true:error + +# Use language keywords for types +dotnet_style_predefined_type_for_member_access = true +dotnet_style_predefined_type_for_locals_parameters_members = true + +# Code Style +csharp_style_var_when_type_is_apparent = true + +#### Resharper/Rider Rules #### +# https://www.jetbrains.com/help/resharper/EditorConfig_Properties.html + +resharper_csharp_force_attribute_style=separate +csharp_place_field_attribute_on_same_line=false +csharp_place_accessorholder_attribute_on_same_line=false +csharp_trailing_comma_in_multiline_lists=false +csharp_trailing_comma_in_singleline_lists=false +csharp_keep_existing_attribute_arrangement=false +csharp_blank_lines_around_region=1 +csharp_blank_lines_inside_region=1 +csharp_keep_blank_lines_in_code=false +csharp_remove_blank_lines_near_braces_in_code=true +csharp_blank_lines_before_control_transfer_statements=1 +csharp_blank_lines_after_control_transfer_statements=1 +csharp_blank_lines_before_block_statements=1 +csharp_blank_lines_after_block_statements=1 +csharp_blank_lines_before_multiline_statements=1 +csharp_blank_lines_after_multiline_statements=1 +csharp_blank_lines_around_block_case_section=0 +csharp_blank_lines_around_multiline_case_section=0 +csharp_blank_lines_before_case=0 +csharp_blank_lines_after_case=0 +resharper_unity_duplicate_event_function_highlighting=error +resharper_unity_duplicate_shortcut_highlighting=error +resharper_unity_expected_component_highlighting=error +resharper_unity_explicit_tag_comparison_highlighting=error +resharper_unity_incorrect_mono_behaviour_instantiation_highlighting=error +resharper_unity_incorrect_scriptable_object_instantiation_highlighting=error +resharper_unity_no_null_coalescing_highlighting=error +resharper_unity_performance_critical_code_camera_main_highlighting=error +resharper_unity_performance_critical_code_invocation_highlighting=warning +resharper_unity_performance_critical_code_null_comparison_highlighting=warning +resharper_unity_possible_misapplication_of_attribute_to_multiple_fields_highlighting=error +resharper_unity_redundant_attribute_on_target_highlighting=error +resharper_unity_redundant_formerly_serialized_as_attribute_highlighting=error +resharper_unity_unresolved_component_or_scriptable_object_highlighting=error +resharper_use_name_of_instead_of_type_of_highlighting=error +resharper_wrong_public_modifier_specification_highlighting=error diff --git a/xNode/Packages/com.pillow.xnode/.github/workflows/publish.yml b/xNode/Packages/com.pillow.xnode/.github/workflows/publish.yml new file mode 100644 index 0000000..ae4a4a2 --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/.github/workflows/publish.yml @@ -0,0 +1,31 @@ +name: publish + +on: + push: + branches: + - upm + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + token: ${{ secrets.CI_TOKEN }} + ref: upm + clean: true + lfs: true + + - uses: xrtk/upm-release@development + with: + upm-username: 'pillow-build-bot' + upm-email: 'hello@pillow.social' + upm-server-address: 'http://upm.pillow.social:4873' + upm-auth-token: '${{ secrets.UPM_AUTH_TOKEN }}' + github-username: 'TogetherXR' + github-pat: '${{ secrets.CI_TOKEN }}' + github-token: '${{ secrets.GITHUB_TOKEN }}' + package-root: '${{ github.workspace }}' diff --git a/xNode/Packages/com.pillow.xnode/.npmignore b/xNode/Packages/com.pillow.xnode/.npmignore new file mode 100644 index 0000000..f231e53 --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/.npmignore @@ -0,0 +1,2 @@ +.npmrc +.github/ \ No newline at end of file diff --git a/xNode/Packages/com.pillow.xnode/.npmrc b/xNode/Packages/com.pillow.xnode/.npmrc new file mode 100644 index 0000000..a49e127 --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/.npmrc @@ -0,0 +1 @@ +strict-ssl=false diff --git a/LICENSE.md b/xNode/Packages/com.pillow.xnode/LICENSE.md similarity index 100% rename from LICENSE.md rename to xNode/Packages/com.pillow.xnode/LICENSE.md diff --git a/LICENSE.md.meta b/xNode/Packages/com.pillow.xnode/LICENSE.md.meta similarity index 100% rename from LICENSE.md.meta rename to xNode/Packages/com.pillow.xnode/LICENSE.md.meta diff --git a/README.md.meta b/xNode/Packages/com.pillow.xnode/Runtime.meta similarity index 57% rename from README.md.meta rename to xNode/Packages/com.pillow.xnode/Runtime.meta index dd3ed6f..8f44005 100644 --- a/README.md.meta +++ b/xNode/Packages/com.pillow.xnode/Runtime.meta @@ -1,6 +1,7 @@ fileFormatVersion: 2 -guid: 243efae3a6b7941ad8f8e54dcf38ce8c -TextScriptImporter: +guid: 809e2193de010ae4b9fa476efbe41cd4 +folderAsset: yes +DefaultImporter: externalObjects: {} userData: assetBundleName: diff --git a/Scripts/Attributes.meta b/xNode/Packages/com.pillow.xnode/Runtime/Attributes.meta similarity index 100% rename from Scripts/Attributes.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Attributes.meta diff --git a/Scripts/Attributes/NodeEnum.cs b/xNode/Packages/com.pillow.xnode/Runtime/Attributes/NodeEnum.cs similarity index 100% rename from Scripts/Attributes/NodeEnum.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Attributes/NodeEnum.cs diff --git a/Scripts/Attributes/NodeEnum.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Attributes/NodeEnum.cs.meta similarity index 100% rename from Scripts/Attributes/NodeEnum.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Attributes/NodeEnum.cs.meta diff --git a/Scripts/Attributes/PortTypeOverrideAttribute.cs b/xNode/Packages/com.pillow.xnode/Runtime/Attributes/PortTypeOverrideAttribute.cs similarity index 97% rename from Scripts/Attributes/PortTypeOverrideAttribute.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Attributes/PortTypeOverrideAttribute.cs index 316ca2d..9f890f0 100644 --- a/Scripts/Attributes/PortTypeOverrideAttribute.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Attributes/PortTypeOverrideAttribute.cs @@ -1,12 +1,12 @@ -using System; -/// Overrides the ValueType of the Port, to have a ValueType different from the type of its serializable field -/// Especially useful in Dynamic Port Lists to create Value-Port Pairs with different type. -[AttributeUsage(AttributeTargets.Field)] -public class PortTypeOverrideAttribute : Attribute { - public Type type; - /// Overrides the ValueType of the Port - /// ValueType of the Port - public PortTypeOverrideAttribute(Type type) { - this.type = type; - } -} +using System; +/// Overrides the ValueType of the Port, to have a ValueType different from the type of its serializable field +/// Especially useful in Dynamic Port Lists to create Value-Port Pairs with different type. +[AttributeUsage(AttributeTargets.Field)] +public class PortTypeOverrideAttribute : Attribute { + public Type type; + /// Overrides the ValueType of the Port + /// ValueType of the Port + public PortTypeOverrideAttribute(Type type) { + this.type = type; + } +} diff --git a/Scripts/Attributes/PortTypeOverrideAttribute.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Attributes/PortTypeOverrideAttribute.cs.meta similarity index 100% rename from Scripts/Attributes/PortTypeOverrideAttribute.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Attributes/PortTypeOverrideAttribute.cs.meta diff --git a/Scripts/Editor.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor.meta similarity index 100% rename from Scripts/Editor.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor.meta diff --git a/Scripts/Editor/AdvancedGenericMenu.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/AdvancedGenericMenu.cs similarity index 93% rename from Scripts/Editor/AdvancedGenericMenu.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/AdvancedGenericMenu.cs index a22fa83..c6e674b 100644 --- a/Scripts/Editor/AdvancedGenericMenu.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/AdvancedGenericMenu.cs @@ -51,9 +51,13 @@ namespace XNodeEditor public void Run() { if ( func2 != null ) + { func2( userData ); + } else if ( func != null ) + { func(); + } } } @@ -62,33 +66,41 @@ namespace XNodeEditor private AdvancedGenericMenuItem FindOrCreateItem( string name, AdvancedGenericMenuItem currentRoot = null ) { if ( string.IsNullOrWhiteSpace( name ) ) + { return null; + } AdvancedGenericMenuItem item = null; - string[] paths = name.Split( '/' ); + var paths = name.Split( '/' ); if ( currentRoot == null ) { item = items.FirstOrDefault( x => x != null && x.name == paths[0] ); if ( item == null ) + { items.Add( item = new AdvancedGenericMenuItem( paths[0] ) ); + } } else { item = currentRoot.children.OfType().FirstOrDefault( x => x.name == paths[0] ); if ( item == null ) + { currentRoot.AddChild( item = new AdvancedGenericMenuItem( paths[0] ) ); + } } if ( paths.Length > 1 ) + { return FindOrCreateItem( string.Join( "/", paths, 1, paths.Length - 1 ), item ); + } return item; } private AdvancedGenericMenuItem FindParent( string name ) { - string[] paths = name.Split( '/' ); + var paths = name.Split( '/' ); return FindOrCreateItem( string.Join( "/", paths, 0, paths.Length - 1 ) ); } @@ -169,9 +181,13 @@ namespace XNodeEditor { var parent = string.IsNullOrWhiteSpace( path ) ? null : FindParent( path ); if ( parent == null ) + { items.Add( null ); + } else + { parent.AddSeparator(); + } } // @@ -195,9 +211,13 @@ namespace XNodeEditor foreach ( var m in items ) { if ( m == null ) + { root.AddSeparator(); + } else + { root.AddChild( m ); + } } return root; @@ -206,8 +226,10 @@ namespace XNodeEditor protected override void ItemSelected( AdvancedDropdownItem item ) { if ( item is AdvancedGenericMenuItem gmItem ) + { gmItem.Run(); + } } } } -#endif \ No newline at end of file +#endif diff --git a/Scripts/Editor/AdvancedGenericMenu.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/AdvancedGenericMenu.cs.meta similarity index 100% rename from Scripts/Editor/AdvancedGenericMenu.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/AdvancedGenericMenu.cs.meta diff --git a/Scripts/Editor/Drawers.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers.meta similarity index 100% rename from Scripts/Editor/Drawers.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers.meta diff --git a/Scripts/Editor/Drawers/NodeEnumDrawer.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/NodeEnumDrawer.cs similarity index 86% rename from Scripts/Editor/Drawers/NodeEnumDrawer.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/NodeEnumDrawer.cs index 8aa748c..cdb9a9e 100644 --- a/Scripts/Editor/Drawers/NodeEnumDrawer.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/NodeEnumDrawer.cs @@ -27,8 +27,11 @@ namespace XNodeEditor { position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); // Get current enum name - string enumName = ""; - if (property.enumValueIndex >= 0 && property.enumValueIndex < property.enumDisplayNames.Length) enumName = property.enumDisplayNames[property.enumValueIndex]; + var enumName = ""; + if (property.enumValueIndex >= 0 && property.enumValueIndex < property.enumDisplayNames.Length) + { + enumName = property.enumDisplayNames[property.enumValueIndex]; + } #if UNITY_2017_1_OR_NEWER // Display dropdown @@ -49,16 +52,16 @@ namespace XNodeEditor { public static void ShowContextMenuAtMouse(SerializedProperty property) { // Initialize menu - GenericMenu menu = new GenericMenu(); + var menu = new GenericMenu(); // Add all enum display names to menu - for (int i = 0; i < property.enumDisplayNames.Length; i++) { - int index = i; + for (var i = 0; i < property.enumDisplayNames.Length; i++) { + var index = i; menu.AddItem(new GUIContent(property.enumDisplayNames[i]), false, () => SetEnum(property, index)); } // Display at cursor position - Rect r = new Rect(Event.current.mousePosition, new Vector2(0, 0)); + var r = new Rect(Event.current.mousePosition, new Vector2(0, 0)); menu.DropDown(r); } @@ -68,4 +71,4 @@ namespace XNodeEditor { property.serializedObject.Update(); } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/NodeEnumDrawer.cs.meta similarity index 100% rename from Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/NodeEnumDrawer.cs.meta diff --git a/Scripts/Editor/Drawers/Odin.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin.meta similarity index 100% rename from Scripts/Editor/Drawers/Odin.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin.meta diff --git a/Scripts/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs similarity index 100% rename from Scripts/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs diff --git a/Scripts/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs.meta similarity index 100% rename from Scripts/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InNodeEditorAttributeProcessor.cs.meta diff --git a/Scripts/Editor/Drawers/Odin/InputAttributeDrawer.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InputAttributeDrawer.cs similarity index 100% rename from Scripts/Editor/Drawers/Odin/InputAttributeDrawer.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InputAttributeDrawer.cs diff --git a/Scripts/Editor/Drawers/Odin/InputAttributeDrawer.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InputAttributeDrawer.cs.meta similarity index 100% rename from Scripts/Editor/Drawers/Odin/InputAttributeDrawer.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/InputAttributeDrawer.cs.meta diff --git a/Scripts/Editor/Drawers/Odin/OutputAttributeDrawer.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/OutputAttributeDrawer.cs similarity index 100% rename from Scripts/Editor/Drawers/Odin/OutputAttributeDrawer.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/OutputAttributeDrawer.cs diff --git a/Scripts/Editor/Drawers/Odin/OutputAttributeDrawer.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/OutputAttributeDrawer.cs.meta similarity index 100% rename from Scripts/Editor/Drawers/Odin/OutputAttributeDrawer.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Drawers/Odin/OutputAttributeDrawer.cs.meta diff --git a/Scripts/Editor/GraphAndNodeEditor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphAndNodeEditor.cs similarity index 92% rename from Scripts/Editor/GraphAndNodeEditor.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphAndNodeEditor.cs index 6859855..28154cb 100644 --- a/Scripts/Editor/GraphAndNodeEditor.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphAndNodeEditor.cs @@ -57,8 +57,8 @@ namespace XNodeEditor { serializedObject.Update(); if (GUILayout.Button("Edit graph", GUILayout.Height(40))) { - SerializedProperty graphProp = serializedObject.FindProperty("graph"); - NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as XNode.NodeGraph); + var graphProp = serializedObject.FindProperty("graph"); + var w = NodeEditorWindow.Open(graphProp.objectReferenceValue as XNode.NodeGraph); w.Home(); // Focus selected node } @@ -72,4 +72,4 @@ namespace XNodeEditor { } } #endif -} \ No newline at end of file +} diff --git a/Scripts/Editor/GraphAndNodeEditor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphAndNodeEditor.cs.meta similarity index 100% rename from Scripts/Editor/GraphAndNodeEditor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphAndNodeEditor.cs.meta diff --git a/Scripts/Editor/GraphRenameFixAssetProcessor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphRenameFixAssetProcessor.cs similarity index 92% rename from Scripts/Editor/GraphRenameFixAssetProcessor.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphRenameFixAssetProcessor.cs index 264e8b1..dc65f77 100644 --- a/Scripts/Editor/GraphRenameFixAssetProcessor.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphRenameFixAssetProcessor.cs @@ -16,8 +16,8 @@ namespace XNodeEditor { string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { - for (int i = 0; i < movedAssets.Length; i++) { - Node nodeAsset = AssetDatabase.LoadMainAssetAtPath(movedAssets[i]) as Node; + for (var i = 0; i < movedAssets.Length; i++) { + var nodeAsset = AssetDatabase.LoadMainAssetAtPath(movedAssets[i]) as Node; // If the renamed asset is a node graph, but the v2 AssetDatabase has swapped a sub-asset node to be its // main asset, reset the node graph to be the main asset and rename the node asset back to its default @@ -32,4 +32,4 @@ namespace XNodeEditor { } } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/GraphRenameFixAssetProcessor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphRenameFixAssetProcessor.cs.meta similarity index 100% rename from Scripts/Editor/GraphRenameFixAssetProcessor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/GraphRenameFixAssetProcessor.cs.meta diff --git a/Scripts/Editor/Internal.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Internal.meta similarity index 100% rename from Scripts/Editor/Internal.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Internal.meta diff --git a/Scripts/Editor/Internal/RerouteReference.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Internal/RerouteReference.cs similarity index 100% rename from Scripts/Editor/Internal/RerouteReference.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Internal/RerouteReference.cs diff --git a/Scripts/Editor/Internal/RerouteReference.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Internal/RerouteReference.cs.meta similarity index 100% rename from Scripts/Editor/Internal/RerouteReference.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Internal/RerouteReference.cs.meta diff --git a/Scripts/Editor/NodeEditor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditor.cs similarity index 81% rename from Scripts/Editor/NodeEditor.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditor.cs index 8522fc0..aeeb286 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditor.cs @@ -1,187 +1,217 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEditor; -using UnityEngine; -#if ODIN_INSPECTOR -using Sirenix.OdinInspector.Editor; -using Sirenix.Utilities; -using Sirenix.Utilities.Editor; -#endif -#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU -using GenericMenu = XNodeEditor.AdvancedGenericMenu; -#endif - -namespace XNodeEditor { - /// Base class to derive custom Node editors from. Use this to create your own custom inspectors and editors for your nodes. - [CustomNodeEditor(typeof(XNode.Node))] - public class NodeEditor : XNodeEditor.Internal.NodeEditorBase { - - /// Fires every whenever a node was modified through the editor - public static Action onUpdateNode; - public readonly static Dictionary portPositions = new Dictionary(); - -#if ODIN_INSPECTOR - protected internal static bool inNodeEditor = false; -#endif - - public virtual void OnHeaderGUI() { - GUILayout.Label(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); - } - - /// Draws standard field editors for all public fields - public virtual void OnBodyGUI() { -#if ODIN_INSPECTOR - inNodeEditor = true; -#endif - - // Unity specifically requires this to save/update any serial object. - // serializedObject.Update(); must go at the start of an inspector gui, and - // serializedObject.ApplyModifiedProperties(); goes at the end. - serializedObject.Update(); - string[] excludes = { "m_Script", "graph", "position", "ports" }; - -#if ODIN_INSPECTOR - try - { -#if ODIN_INSPECTOR_3 - objectTree.BeginDraw( true ); -#else - InspectorUtilities.BeginDrawPropertyTree(objectTree, true); -#endif - } - catch ( ArgumentNullException ) - { -#if ODIN_INSPECTOR_3 - objectTree.EndDraw(); -#else - InspectorUtilities.EndDrawPropertyTree(objectTree); -#endif - NodeEditor.DestroyEditor(this.target); - return; - } - - GUIHelper.PushLabelWidth( 84 ); - objectTree.Draw( true ); -#if ODIN_INSPECTOR_3 - objectTree.EndDraw(); -#else - InspectorUtilities.EndDrawPropertyTree(objectTree); -#endif - GUIHelper.PopLabelWidth(); -#else - - // Iterate through serialized properties and draw them like the Inspector (But with ports) - SerializedProperty iterator = serializedObject.GetIterator(); - bool enterChildren = true; - while (iterator.NextVisible(enterChildren)) { - enterChildren = false; - if (excludes.Contains(iterator.name)) continue; - NodeEditorGUILayout.PropertyField(iterator, true); - } -#endif - - // Iterate through dynamic ports and draw them in the order in which they are serialized - foreach (XNode.NodePort dynamicPort in target.DynamicPorts) { - if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort)) continue; - NodeEditorGUILayout.PortField(dynamicPort); - } - - serializedObject.ApplyModifiedProperties(); - -#if ODIN_INSPECTOR - // Call repaint so that the graph window elements respond properly to layout changes coming from Odin - if (GUIHelper.RepaintRequested) { - GUIHelper.ClearRepaintRequest(); - window.Repaint(); - } -#endif - -#if ODIN_INSPECTOR - inNodeEditor = false; -#endif - } - - public virtual int GetWidth() { - Type type = target.GetType(); - int width; - if (type.TryGetAttributeWidth(out width)) return width; - else return 208; - } - - /// Returns color for target node - public virtual Color GetTint() { - // Try get color from [NodeTint] attribute - Type type = target.GetType(); - Color color; - if (type.TryGetAttributeTint(out color)) return color; - // Return default color (grey) - else return NodeEditorPreferences.GetSettings().tintColor; - } - - public virtual GUIStyle GetBodyStyle() { - return NodeEditorResources.styles.nodeBody; - } - - public virtual GUIStyle GetBodyHighlightStyle() { - return NodeEditorResources.styles.nodeHighlight; - } - - /// Override to display custom node header tooltips - public virtual string GetHeaderTooltip() { - return null; - } - - /// Add items for the context menu when right-clicking this node. Override to add custom menu items. - public virtual void AddContextMenuItems(GenericMenu menu) { - bool canRemove = true; - // Actions if only one node is selected - if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { - XNode.Node node = Selection.activeObject as XNode.Node; - menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node)); - menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode); - - canRemove = NodeGraphEditor.GetEditor(node.graph, NodeEditorWindow.current).CanRemove(node); - } - - // Add actions to any number of selected nodes - menu.AddItem(new GUIContent("Copy"), false, NodeEditorWindow.current.CopySelectedNodes); - menu.AddItem(new GUIContent("Duplicate"), false, NodeEditorWindow.current.DuplicateSelectedNodes); - - if (canRemove) menu.AddItem(new GUIContent("Remove"), false, NodeEditorWindow.current.RemoveSelectedNodes); - else menu.AddItem(new GUIContent("Remove"), false, null); - - // Custom sctions if only one node is selected - if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { - XNode.Node node = Selection.activeObject as XNode.Node; - menu.AddCustomContextMenuItems(node); - } - } - - /// Rename the node asset. This will trigger a reimport of the node. - public void Rename(string newName) { - if (newName == null || newName.Trim() == "") newName = NodeEditorUtilities.NodeDefaultName(target.GetType()); - target.name = newName; - OnRename(); - AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); - } - - /// Called after this node's name has changed. - public virtual void OnRename() { } - - [AttributeUsage(AttributeTargets.Class)] - public class CustomNodeEditorAttribute : Attribute, - XNodeEditor.Internal.NodeEditorBase.INodeEditorAttrib { - private Type inspectedType; - /// Tells a NodeEditor which Node type it is an editor for - /// Type that this editor can edit - public CustomNodeEditorAttribute(Type inspectedType) { - this.inspectedType = inspectedType; - } - - public Type GetInspectedType() { - return inspectedType; - } - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +#if ODIN_INSPECTOR +using Sirenix.OdinInspector.Editor; +using Sirenix.Utilities; +using Sirenix.Utilities.Editor; +#endif +#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU +using GenericMenu = XNodeEditor.AdvancedGenericMenu; +#endif + +namespace XNodeEditor { + /// Base class to derive custom Node editors from. Use this to create your own custom inspectors and editors for your nodes. + [CustomNodeEditor(typeof(XNode.Node))] + public class NodeEditor : XNodeEditor.Internal.NodeEditorBase { + + /// Fires every whenever a node was modified through the editor + public static Action onUpdateNode; + public readonly static Dictionary portPositions = new Dictionary(); + +#if ODIN_INSPECTOR + protected internal static bool inNodeEditor = false; +#endif + + public virtual void OnHeaderGUI() { + GUILayout.Label(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); + } + + /// Draws standard field editors for all public fields + public virtual void OnBodyGUI() { +#if ODIN_INSPECTOR + inNodeEditor = true; +#endif + + // Unity specifically requires this to save/update any serial object. + // serializedObject.Update(); must go at the start of an inspector gui, and + // serializedObject.ApplyModifiedProperties(); goes at the end. + serializedObject.Update(); + string[] excludes = { "m_Script", "graph", "position", "ports" }; + +#if ODIN_INSPECTOR + try + { +#if ODIN_INSPECTOR_3 + objectTree.BeginDraw( true ); +#else + InspectorUtilities.BeginDrawPropertyTree(objectTree, true); +#endif + } + catch ( ArgumentNullException ) + { +#if ODIN_INSPECTOR_3 + objectTree.EndDraw(); +#else + InspectorUtilities.EndDrawPropertyTree(objectTree); +#endif + NodeEditor.DestroyEditor(this.target); + return; + } + + GUIHelper.PushLabelWidth( 84 ); + objectTree.Draw( true ); +#if ODIN_INSPECTOR_3 + objectTree.EndDraw(); +#else + InspectorUtilities.EndDrawPropertyTree(objectTree); +#endif + GUIHelper.PopLabelWidth(); +#else + + // Iterate through serialized properties and draw them like the Inspector (But with ports) + var iterator = serializedObject.GetIterator(); + var enterChildren = true; + while (iterator.NextVisible(enterChildren)) { + enterChildren = false; + if (excludes.Contains(iterator.name)) + { + continue; + } + + NodeEditorGUILayout.PropertyField(iterator, true); + } +#endif + + // Iterate through dynamic ports and draw them in the order in which they are serialized + foreach (var dynamicPort in target.DynamicPorts) { + if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort)) + { + continue; + } + + NodeEditorGUILayout.PortField(dynamicPort); + } + + serializedObject.ApplyModifiedProperties(); + +#if ODIN_INSPECTOR + // Call repaint so that the graph window elements respond properly to layout changes coming from Odin + if (GUIHelper.RepaintRequested) { + GUIHelper.ClearRepaintRequest(); + window.Repaint(); + } +#endif + +#if ODIN_INSPECTOR + inNodeEditor = false; +#endif + } + + public virtual int GetWidth() { + var type = target.GetType(); + int width; + if (type.TryGetAttributeWidth(out width)) + { + return width; + } + else + { + return 208; + } + } + + /// Returns color for target node + public virtual Color GetTint() { + // Try get color from [NodeTint] attribute + var type = target.GetType(); + Color color; + if (type.TryGetAttributeTint(out color)) + { + return color; + } + // Return default color (grey) + else + { + return NodeEditorPreferences.GetSettings().tintColor; + } + } + + public virtual GUIStyle GetBodyStyle() { + return NodeEditorResources.styles.nodeBody; + } + + public virtual GUIStyle GetBodyHighlightStyle() { + return NodeEditorResources.styles.nodeHighlight; + } + + /// Override to display custom node header tooltips + public virtual string GetHeaderTooltip() { + return null; + } + + /// Add items for the context menu when right-clicking this node. Override to add custom menu items. + public virtual void AddContextMenuItems(GenericMenu menu) { + var canRemove = true; + // Actions if only one node is selected + if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { + var node = Selection.activeObject as XNode.Node; + menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node)); + menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode); + + canRemove = NodeGraphEditor.GetEditor(node.graph, NodeEditorWindow.current).CanRemove(node); + } + + // Add actions to any number of selected nodes + menu.AddItem(new GUIContent("Copy"), false, NodeEditorWindow.current.CopySelectedNodes); + menu.AddItem(new GUIContent("Duplicate"), false, NodeEditorWindow.current.DuplicateSelectedNodes); + + if (canRemove) + { + menu.AddItem(new GUIContent("Remove"), false, NodeEditorWindow.current.RemoveSelectedNodes); + } + else + { + menu.AddItem(new GUIContent("Remove"), false, null); + } + + // Custom sctions if only one node is selected + if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { + var node = Selection.activeObject as XNode.Node; + menu.AddCustomContextMenuItems(node); + } + } + + /// Rename the node asset. This will trigger a reimport of the node. + public void Rename(string newName) { + if (newName == null || newName.Trim() == "") + { + newName = NodeEditorUtilities.NodeDefaultName(target.GetType()); + } + + target.name = newName; + OnRename(); + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); + } + + /// Called after this node's name has changed. + public virtual void OnRename() { } + + [AttributeUsage(AttributeTargets.Class)] + public class CustomNodeEditorAttribute : Attribute, + XNodeEditor.Internal.NodeEditorBase.INodeEditorAttrib { + private Type inspectedType; + /// Tells a NodeEditor which Node type it is an editor for + /// Type that this editor can edit + public CustomNodeEditorAttribute(Type inspectedType) { + this.inspectedType = inspectedType; + } + + public Type GetInspectedType() { + return inspectedType; + } + } + } +} diff --git a/Scripts/Editor/NodeEditor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditor.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditor.cs.meta diff --git a/Scripts/Editor/NodeEditorAction.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAction.cs similarity index 68% rename from Scripts/Editor/NodeEditorAction.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAction.cs index a9147f2..fb80486 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAction.cs @@ -1,566 +1,700 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEditor; -using UnityEngine; -using XNodeEditor.Internal; -#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU -using GenericMenu = XNodeEditor.AdvancedGenericMenu; -#endif - -namespace XNodeEditor { - public partial class NodeEditorWindow { - public enum NodeActivity { Idle, HoldNode, DragNode, HoldGrid, DragGrid } - public static NodeActivity currentActivity = NodeActivity.Idle; - public static bool isPanning { get; private set; } - public static Vector2[] dragOffset; - - public static XNode.Node[] copyBuffer = null; - - public bool IsDraggingPort { get { return draggedOutput != null; } } - public bool IsHoveringPort { get { return hoveredPort != null; } } - public bool IsHoveringNode { get { return hoveredNode != null; } } - public bool IsHoveringReroute { get { return hoveredReroute.port != null; } } - - /// Return the dragged port or null if not exist - public XNode.NodePort DraggedOutputPort { get { XNode.NodePort result = draggedOutput; return result; } } - /// Return the Hovered port or null if not exist - public XNode.NodePort HoveredPort { get { XNode.NodePort result = hoveredPort; return result; } } - /// Return the Hovered node or null if not exist - public XNode.Node HoveredNode { get { XNode.Node result = hoveredNode; return result; } } - - private XNode.Node hoveredNode = null; - [NonSerialized] public XNode.NodePort hoveredPort = null; - [NonSerialized] private XNode.NodePort draggedOutput = null; - [NonSerialized] private XNode.NodePort draggedOutputTarget = null; - [NonSerialized] private XNode.NodePort autoConnectOutput = null; - [NonSerialized] private List draggedOutputReroutes = new List(); - - private RerouteReference hoveredReroute = new RerouteReference(); - public List selectedReroutes = new List(); - private Vector2 dragBoxStart; - private UnityEngine.Object[] preBoxSelection; - private RerouteReference[] preBoxSelectionReroute; - private Rect selectionBox; - private bool isDoubleClick = false; - private Vector2 lastMousePosition; - private float dragThreshold = 1f; - - public void Controls() { - wantsMouseMove = true; - Event e = Event.current; - switch (e.type) { - case EventType.DragUpdated: - case EventType.DragPerform: - DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - if (e.type == EventType.DragPerform) { - DragAndDrop.AcceptDrag(); - graphEditor.OnDropObjects(DragAndDrop.objectReferences); - } - break; - case EventType.MouseMove: - //Keyboard commands will not get correct mouse position from Event - lastMousePosition = e.mousePosition; - break; - case EventType.ScrollWheel: - float oldZoom = zoom; - if (e.delta.y > 0) zoom += 0.1f * zoom; - else zoom -= 0.1f * zoom; - if (NodeEditorPreferences.GetSettings().zoomToMouse) panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset); - break; - case EventType.MouseDrag: - if (e.button == 0) { - if (IsDraggingPort) { - // Set target even if we can't connect, so as to prevent auto-conn menu from opening erroneously - if (IsHoveringPort && hoveredPort.IsInput && !draggedOutput.IsConnectedTo(hoveredPort)) { - draggedOutputTarget = hoveredPort; - } else { - draggedOutputTarget = null; - } - Repaint(); - } else if (currentActivity == NodeActivity.HoldNode) { - RecalculateDragOffsets(e); - currentActivity = NodeActivity.DragNode; - Repaint(); - } - if (currentActivity == NodeActivity.DragNode) { - // Holding ctrl inverts grid snap - bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap; - if (e.control) gridSnap = !gridSnap; - - Vector2 mousePos = WindowToGridPosition(e.mousePosition); - // Move selected nodes with offset - for (int i = 0; i < Selection.objects.Length; i++) { - if (Selection.objects[i] is XNode.Node) { - XNode.Node node = Selection.objects[i] as XNode.Node; - Undo.RecordObject(node, "Moved Node"); - Vector2 initial = node.position; - node.position = mousePos + dragOffset[i]; - if (gridSnap) { - node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8; - node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8; - } - - // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame. - Vector2 offset = node.position - initial; - if (offset.sqrMagnitude > 0) { - foreach (XNode.NodePort output in node.Outputs) { - Rect rect; - if (portConnectionPoints.TryGetValue(output, out rect)) { - rect.position += offset; - portConnectionPoints[output] = rect; - } - } - - foreach (XNode.NodePort input in node.Inputs) { - Rect rect; - if (portConnectionPoints.TryGetValue(input, out rect)) { - rect.position += offset; - portConnectionPoints[input] = rect; - } - } - } - } - } - // Move selected reroutes with offset - for (int i = 0; i < selectedReroutes.Count; i++) { - Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i]; - if (gridSnap) { - pos.x = (Mathf.Round(pos.x / 16) * 16); - pos.y = (Mathf.Round(pos.y / 16) * 16); - } - selectedReroutes[i].SetPoint(pos); - } - Repaint(); - } else if (currentActivity == NodeActivity.HoldGrid) { - currentActivity = NodeActivity.DragGrid; - preBoxSelection = Selection.objects; - preBoxSelectionReroute = selectedReroutes.ToArray(); - dragBoxStart = WindowToGridPosition(e.mousePosition); - Repaint(); - } else if (currentActivity == NodeActivity.DragGrid) { - Vector2 boxStartPos = GridToWindowPosition(dragBoxStart); - Vector2 boxSize = e.mousePosition - boxStartPos; - if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); } - if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); } - selectionBox = new Rect(boxStartPos, boxSize); - Repaint(); - } - } else if (e.button == 1 || e.button == 2) { - //check drag threshold for larger screens - if (e.delta.magnitude > dragThreshold) { - panOffset += e.delta * zoom; - isPanning = true; - } - } - break; - case EventType.MouseDown: - Repaint(); - if (e.button == 0) { - draggedOutputReroutes.Clear(); - - if (IsHoveringPort) { - if (hoveredPort.IsOutput) { - draggedOutput = hoveredPort; - autoConnectOutput = hoveredPort; - } else { - hoveredPort.VerifyConnections(); - autoConnectOutput = null; - if (hoveredPort.IsConnected) { - XNode.Node node = hoveredPort.node; - XNode.NodePort output = hoveredPort.Connection; - int outputConnectionIndex = output.GetConnectionIndex(hoveredPort); - draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex); - hoveredPort.Disconnect(output); - draggedOutput = output; - draggedOutputTarget = hoveredPort; - if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node); - } - } - } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { - // If mousedown on node header, select or deselect - if (!Selection.Contains(hoveredNode)) { - SelectNode(hoveredNode, e.control || e.shift); - if (!e.control && !e.shift) selectedReroutes.Clear(); - } else if (e.control || e.shift) DeselectNode(hoveredNode); - - // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown. - isDoubleClick = (e.clickCount == 2); - - e.Use(); - currentActivity = NodeActivity.HoldNode; - } else if (IsHoveringReroute) { - // If reroute isn't selected - if (!selectedReroutes.Contains(hoveredReroute)) { - // Add it - if (e.control || e.shift) selectedReroutes.Add(hoveredReroute); - // Select it - else { - selectedReroutes = new List() { hoveredReroute }; - Selection.activeObject = null; - } - - } - // Deselect - else if (e.control || e.shift) selectedReroutes.Remove(hoveredReroute); - e.Use(); - currentActivity = NodeActivity.HoldNode; - } - // If mousedown on grid background, deselect all - else if (!IsHoveringNode) { - currentActivity = NodeActivity.HoldGrid; - if (!e.control && !e.shift) { - selectedReroutes.Clear(); - Selection.activeObject = null; - } - } - } - break; - case EventType.MouseUp: - if (e.button == 0) { - //Port drag release - if (IsDraggingPort) { - // If connection is valid, save it - if (draggedOutputTarget != null && graphEditor.CanConnect(draggedOutput, draggedOutputTarget)) { - XNode.Node node = draggedOutputTarget.node; - if (graph.nodes.Count != 0) draggedOutput.Connect(draggedOutputTarget); - - // ConnectionIndex can be -1 if the connection is removed instantly after creation - int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget); - if (connectionIndex != -1) { - draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes); - if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node); - EditorUtility.SetDirty(graph); - } - } - // Open context menu for auto-connection if there is no target node - else if (draggedOutputTarget == null && NodeEditorPreferences.GetSettings().dragToCreate && autoConnectOutput != null) { - GenericMenu menu = new GenericMenu(); - graphEditor.AddContextMenuItems(menu, draggedOutput.ValueType); - menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - } - //Release dragged connection - draggedOutput = null; - draggedOutputTarget = null; - EditorUtility.SetDirty(graph); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } else if (currentActivity == NodeActivity.DragNode) { - IEnumerable nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node); - foreach (XNode.Node node in nodes) EditorUtility.SetDirty(node); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } else if (!IsHoveringNode) { - // If click outside node, release field focus - if (!isPanning) { - EditorGUI.FocusTextInControl(null); - EditorGUIUtility.editingTextField = false; - } - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } - - // If click node header, select it. - if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift)) { - selectedReroutes.Clear(); - SelectNode(hoveredNode, false); - - // Double click to center node - if (isDoubleClick) { - Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero; - panOffset = -hoveredNode.position - nodeDimension; - } - } - - // If click reroute, select it. - if (IsHoveringReroute && !(e.control || e.shift)) { - selectedReroutes = new List() { hoveredReroute }; - Selection.activeObject = null; - } - - Repaint(); - currentActivity = NodeActivity.Idle; - } else if (e.button == 1 || e.button == 2) { - if (!isPanning) { - if (IsDraggingPort) { - draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition)); - } else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1) { - selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint()); - selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1); - } else if (IsHoveringReroute) { - ShowRerouteContextMenu(hoveredReroute); - } else if (IsHoveringPort) { - ShowPortContextMenu(hoveredPort); - } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { - if (!Selection.Contains(hoveredNode)) SelectNode(hoveredNode, false); - autoConnectOutput = null; - GenericMenu menu = new GenericMenu(); - NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu); - menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places. - } else if (!IsHoveringNode) { - autoConnectOutput = null; - GenericMenu menu = new GenericMenu(); - graphEditor.AddContextMenuItems(menu); - menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - } - } - isPanning = false; - } - // Reset DoubleClick - isDoubleClick = false; - break; - case EventType.KeyDown: - if (EditorGUIUtility.editingTextField || GUIUtility.keyboardControl != 0) break; - else if (e.keyCode == KeyCode.F) Home(); - if (NodeEditorUtilities.IsMac()) { - if (e.keyCode == KeyCode.Return) RenameSelectedNode(); - } else { - if (e.keyCode == KeyCode.F2) RenameSelectedNode(); - } - if (e.keyCode == KeyCode.A) { - if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node))) { - foreach (XNode.Node node in graph.nodes) { - DeselectNode(node); - } - } else { - foreach (XNode.Node node in graph.nodes) { - SelectNode(node, true); - } - } - Repaint(); - } - break; - case EventType.ValidateCommand: - case EventType.ExecuteCommand: - if (e.commandName == "SoftDelete") { - if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); - e.Use(); - } else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete") { - if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); - e.Use(); - } else if (e.commandName == "Duplicate") { - if (e.type == EventType.ExecuteCommand) DuplicateSelectedNodes(); - e.Use(); - } else if (e.commandName == "Copy") { - if (!EditorGUIUtility.editingTextField) { - if (e.type == EventType.ExecuteCommand) CopySelectedNodes(); - e.Use(); - } - } else if (e.commandName == "Paste") { - if (!EditorGUIUtility.editingTextField) { - if (e.type == EventType.ExecuteCommand) PasteNodes(WindowToGridPosition(lastMousePosition)); - e.Use(); - } - } - Repaint(); - break; - case EventType.Ignore: - // If release mouse outside window - if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid) { - Repaint(); - currentActivity = NodeActivity.Idle; - } - break; - } - } - - private void RecalculateDragOffsets(Event current) { - dragOffset = new Vector2[Selection.objects.Length + selectedReroutes.Count]; - // Selected nodes - for (int i = 0; i < Selection.objects.Length; i++) { - if (Selection.objects[i] is XNode.Node) { - XNode.Node node = Selection.objects[i] as XNode.Node; - dragOffset[i] = node.position - WindowToGridPosition(current.mousePosition); - } - } - - // Selected reroutes - for (int i = 0; i < selectedReroutes.Count; i++) { - dragOffset[Selection.objects.Length + i] = selectedReroutes[i].GetPoint() - WindowToGridPosition(current.mousePosition); - } - } - - /// Puts all selected nodes in focus. If no nodes are present, resets view and zoom to to origin - public void Home() { - var nodes = Selection.objects.Where(o => o is XNode.Node).Cast().ToList(); - if (nodes.Count > 0) { - Vector2 minPos = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); - Vector2 maxPos = nodes.Select(x => x.position + (nodeSizes.ContainsKey(x) ? nodeSizes[x] : Vector2.zero)).Aggregate((x, y) => new Vector2(Mathf.Max(x.x, y.x), Mathf.Max(x.y, y.y))); - panOffset = -(minPos + (maxPos - minPos) / 2f); - } else { - zoom = 2; - panOffset = Vector2.zero; - } - } - - /// Remove nodes in the graph in Selection.objects - public void RemoveSelectedNodes() { - // We need to delete reroutes starting at the highest point index to avoid shifting indices - selectedReroutes = selectedReroutes.OrderByDescending(x => x.pointIndex).ToList(); - for (int i = 0; i < selectedReroutes.Count; i++) { - selectedReroutes[i].RemovePoint(); - } - selectedReroutes.Clear(); - foreach (UnityEngine.Object item in Selection.objects) { - if (item is XNode.Node) { - XNode.Node node = item as XNode.Node; - graphEditor.RemoveNode(node); - } - } - } - - /// Initiate a rename on the currently selected node - public void RenameSelectedNode() { - if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { - XNode.Node node = Selection.activeObject as XNode.Node; - Vector2 size; - if (nodeSizes.TryGetValue(node, out size)) { - RenamePopup.Show(Selection.activeObject, size.x); - } else { - RenamePopup.Show(Selection.activeObject); - } - } - } - - /// Draw this node on top of other nodes by placing it last in the graph.nodes list - public void MoveNodeToTop(XNode.Node node) { - int index; - while ((index = graph.nodes.IndexOf(node)) != graph.nodes.Count - 1) { - graph.nodes[index] = graph.nodes[index + 1]; - graph.nodes[index + 1] = node; - } - } - - /// Duplicate selected nodes and select the duplicates - public void DuplicateSelectedNodes() { - // Get selected nodes which are part of this graph - XNode.Node[] selectedNodes = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray(); - if (selectedNodes == null || selectedNodes.Length == 0) return; - // Get top left node position - Vector2 topLeftNode = selectedNodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); - InsertDuplicateNodes(selectedNodes, topLeftNode + new Vector2(30, 30)); - } - - public void CopySelectedNodes() { - copyBuffer = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray(); - } - - public void PasteNodes(Vector2 pos) { - InsertDuplicateNodes(copyBuffer, pos); - } - - private void InsertDuplicateNodes(XNode.Node[] nodes, Vector2 topLeft) { - if (nodes == null || nodes.Length == 0) return; - - // Get top-left node - Vector2 topLeftNode = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); - Vector2 offset = topLeft - topLeftNode; - - UnityEngine.Object[] newNodes = new UnityEngine.Object[nodes.Length]; - Dictionary substitutes = new Dictionary(); - for (int i = 0; i < nodes.Length; i++) { - XNode.Node srcNode = nodes[i]; - if (srcNode == null) continue; - - // Check if user is allowed to add more of given node type - XNode.Node.DisallowMultipleNodesAttribute disallowAttrib; - Type nodeType = srcNode.GetType(); - if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib)) { - int typeCount = graph.nodes.Count(x => x.GetType() == nodeType); - if (typeCount >= disallowAttrib.max) continue; - } - - XNode.Node newNode = graphEditor.CopyNode(srcNode); - substitutes.Add(srcNode, newNode); - newNode.position = srcNode.position + offset; - newNodes[i] = newNode; - } - - // Walk through the selected nodes again, recreate connections, using the new nodes - for (int i = 0; i < nodes.Length; i++) { - XNode.Node srcNode = nodes[i]; - if (srcNode == null) continue; - foreach (XNode.NodePort port in srcNode.Ports) { - for (int c = 0; c < port.ConnectionCount; c++) { - XNode.NodePort inputPort = port.direction == XNode.NodePort.IO.Input ? port : port.GetConnection(c); - XNode.NodePort outputPort = port.direction == XNode.NodePort.IO.Output ? port : port.GetConnection(c); - - XNode.Node newNodeIn, newNodeOut; - if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut)) { - newNodeIn.UpdatePorts(); - newNodeOut.UpdatePorts(); - inputPort = newNodeIn.GetInputPort(inputPort.fieldName); - outputPort = newNodeOut.GetOutputPort(outputPort.fieldName); - } - if (!inputPort.IsConnectedTo(outputPort)) inputPort.Connect(outputPort); - } - } - } - EditorUtility.SetDirty(graph); - // Select the new nodes - Selection.objects = newNodes; - } - - /// Draw a connection as we are dragging it - public void DrawDraggedConnection() { - if (IsDraggingPort) { - Gradient gradient = graphEditor.GetNoodleGradient(draggedOutput, null); - float thickness = graphEditor.GetNoodleThickness(draggedOutput, null); - NoodlePath path = graphEditor.GetNoodlePath(draggedOutput, null); - NoodleStroke stroke = graphEditor.GetNoodleStroke(draggedOutput, null); - - Rect fromRect; - if (!_portConnectionPoints.TryGetValue(draggedOutput, out fromRect)) return; - List gridPoints = new List(); - gridPoints.Add(fromRect.center); - for (int i = 0; i < draggedOutputReroutes.Count; i++) { - gridPoints.Add(draggedOutputReroutes[i]); - } - if (draggedOutputTarget != null) gridPoints.Add(portConnectionPoints[draggedOutputTarget].center); - else gridPoints.Add(WindowToGridPosition(Event.current.mousePosition)); - - DrawNoodle(gradient, path, stroke, thickness, gridPoints); - - GUIStyle portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(draggedOutput); - Color bgcol = Color.black; - Color frcol = gradient.colorKeys[0].color; - bgcol.a = 0.6f; - frcol.a = 0.6f; - - // Loop through reroute points again and draw the points - for (int i = 0; i < draggedOutputReroutes.Count; i++) { - // Draw reroute point at position - Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16)); - rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8); - rect = GridToWindowRect(rect); - - NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol, portStyle.normal.background, portStyle.active.background); - } - } - } - - bool IsHoveringTitle(XNode.Node node) { - Vector2 mousePos = Event.current.mousePosition; - //Get node position - Vector2 nodePos = GridToWindowPosition(node.position); - float width; - Vector2 size; - if (nodeSizes.TryGetValue(node, out size)) width = size.x; - else width = 200; - Rect windowRect = new Rect(nodePos, new Vector2(width / zoom, 30 / zoom)); - return windowRect.Contains(mousePos); - } - - /// Attempt to connect dragged output to target node - public void AutoConnect(XNode.Node node) { - if (autoConnectOutput == null) return; - - // Find compatible input port - XNode.NodePort inputPort = node.Ports.FirstOrDefault(x => x.IsInput && graphEditor.CanConnect(autoConnectOutput, x)); - if (inputPort != null) autoConnectOutput.Connect(inputPort); - - // Save changes - EditorUtility.SetDirty(graph); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - autoConnectOutput = null; - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +using XNodeEditor.Internal; +#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU +using GenericMenu = XNodeEditor.AdvancedGenericMenu; +#endif + +namespace XNodeEditor { + public partial class NodeEditorWindow { + public enum NodeActivity { Idle, HoldNode, DragNode, HoldGrid, DragGrid } + public static NodeActivity currentActivity = NodeActivity.Idle; + public static bool isPanning { get; private set; } + public static Vector2[] dragOffset; + + public static XNode.Node[] copyBuffer = null; + + public bool IsDraggingPort { get { return draggedOutput != null; } } + public bool IsHoveringPort { get { return hoveredPort != null; } } + public bool IsHoveringNode { get { return hoveredNode != null; } } + public bool IsHoveringReroute { get { return hoveredReroute.port != null; } } + + /// Return the dragged port or null if not exist + public XNode.NodePort DraggedOutputPort { get { var result = draggedOutput; return result; } } + /// Return the Hovered port or null if not exist + public XNode.NodePort HoveredPort { get { var result = hoveredPort; return result; } } + /// Return the Hovered node or null if not exist + public XNode.Node HoveredNode { get { var result = hoveredNode; return result; } } + + private XNode.Node hoveredNode = null; + [NonSerialized] public XNode.NodePort hoveredPort = null; + [NonSerialized] private XNode.NodePort draggedOutput = null; + [NonSerialized] private XNode.NodePort draggedOutputTarget = null; + [NonSerialized] private XNode.NodePort autoConnectOutput = null; + [NonSerialized] private List draggedOutputReroutes = new List(); + + private RerouteReference hoveredReroute = new RerouteReference(); + public List selectedReroutes = new List(); + private Vector2 dragBoxStart; + private UnityEngine.Object[] preBoxSelection; + private RerouteReference[] preBoxSelectionReroute; + private Rect selectionBox; + private bool isDoubleClick = false; + private Vector2 lastMousePosition; + private float dragThreshold = 1f; + + public void Controls() { + wantsMouseMove = true; + var e = Event.current; + switch (e.type) { + case EventType.DragUpdated: + case EventType.DragPerform: + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + if (e.type == EventType.DragPerform) { + DragAndDrop.AcceptDrag(); + graphEditor.OnDropObjects(DragAndDrop.objectReferences); + } + break; + case EventType.MouseMove: + //Keyboard commands will not get correct mouse position from Event + lastMousePosition = e.mousePosition; + break; + case EventType.ScrollWheel: + var oldZoom = zoom; + if (e.delta.y > 0) + { + zoom += 0.1f * zoom; + } + else + { + zoom -= 0.1f * zoom; + } + + if (NodeEditorPreferences.GetSettings().zoomToMouse) + { + panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset); + } + + break; + case EventType.MouseDrag: + if (e.button == 0) { + if (IsDraggingPort) { + // Set target even if we can't connect, so as to prevent auto-conn menu from opening erroneously + if (IsHoveringPort && hoveredPort.IsInput && !draggedOutput.IsConnectedTo(hoveredPort)) { + draggedOutputTarget = hoveredPort; + } else { + draggedOutputTarget = null; + } + Repaint(); + } else if (currentActivity == NodeActivity.HoldNode) { + RecalculateDragOffsets(e); + currentActivity = NodeActivity.DragNode; + Repaint(); + } + if (currentActivity == NodeActivity.DragNode) { + // Holding ctrl inverts grid snap + var gridSnap = NodeEditorPreferences.GetSettings().gridSnap; + if (e.control) + { + gridSnap = !gridSnap; + } + + var mousePos = WindowToGridPosition(e.mousePosition); + // Move selected nodes with offset + for (var i = 0; i < Selection.objects.Length; i++) { + if (Selection.objects[i] is XNode.Node) { + var node = Selection.objects[i] as XNode.Node; + Undo.RecordObject(node, "Moved Node"); + var initial = node.position; + node.position = mousePos + dragOffset[i]; + if (gridSnap) { + node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8; + node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8; + } + + // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame. + var offset = node.position - initial; + if (offset.sqrMagnitude > 0) { + foreach (var output in node.Outputs) { + Rect rect; + if (portConnectionPoints.TryGetValue(output, out rect)) { + rect.position += offset; + portConnectionPoints[output] = rect; + } + } + + foreach (var input in node.Inputs) { + Rect rect; + if (portConnectionPoints.TryGetValue(input, out rect)) { + rect.position += offset; + portConnectionPoints[input] = rect; + } + } + } + } + } + // Move selected reroutes with offset + for (var i = 0; i < selectedReroutes.Count; i++) { + var pos = mousePos + dragOffset[Selection.objects.Length + i]; + if (gridSnap) { + pos.x = (Mathf.Round(pos.x / 16) * 16); + pos.y = (Mathf.Round(pos.y / 16) * 16); + } + selectedReroutes[i].SetPoint(pos); + } + Repaint(); + } else if (currentActivity == NodeActivity.HoldGrid) { + currentActivity = NodeActivity.DragGrid; + preBoxSelection = Selection.objects; + preBoxSelectionReroute = selectedReroutes.ToArray(); + dragBoxStart = WindowToGridPosition(e.mousePosition); + Repaint(); + } else if (currentActivity == NodeActivity.DragGrid) { + var boxStartPos = GridToWindowPosition(dragBoxStart); + var boxSize = e.mousePosition - boxStartPos; + if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); } + if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); } + selectionBox = new Rect(boxStartPos, boxSize); + Repaint(); + } + } else if (e.button == 1 || e.button == 2) { + //check drag threshold for larger screens + if (e.delta.magnitude > dragThreshold) { + panOffset += e.delta * zoom; + isPanning = true; + } + } + break; + case EventType.MouseDown: + Repaint(); + if (e.button == 0) { + draggedOutputReroutes.Clear(); + + if (IsHoveringPort) { + if (hoveredPort.IsOutput) { + draggedOutput = hoveredPort; + autoConnectOutput = hoveredPort; + } else { + hoveredPort.VerifyConnections(); + autoConnectOutput = null; + if (hoveredPort.IsConnected) { + var node = hoveredPort.node; + var output = hoveredPort.Connection; + var outputConnectionIndex = output.GetConnectionIndex(hoveredPort); + draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex); + hoveredPort.Disconnect(output); + draggedOutput = output; + draggedOutputTarget = hoveredPort; + if (NodeEditor.onUpdateNode != null) + { + NodeEditor.onUpdateNode(node); + } + } + } + } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { + // If mousedown on node header, select or deselect + if (!Selection.Contains(hoveredNode)) { + SelectNode(hoveredNode, e.control || e.shift); + if (!e.control && !e.shift) + { + selectedReroutes.Clear(); + } + } else if (e.control || e.shift) + { + DeselectNode(hoveredNode); + } + + // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown. + isDoubleClick = (e.clickCount == 2); + + e.Use(); + currentActivity = NodeActivity.HoldNode; + } else if (IsHoveringReroute) { + // If reroute isn't selected + if (!selectedReroutes.Contains(hoveredReroute)) { + // Add it + if (e.control || e.shift) + { + selectedReroutes.Add(hoveredReroute); + } + // Select it + else { + selectedReroutes = new List() { hoveredReroute }; + Selection.activeObject = null; + } + + } + // Deselect + else if (e.control || e.shift) + { + selectedReroutes.Remove(hoveredReroute); + } + + e.Use(); + currentActivity = NodeActivity.HoldNode; + } + // If mousedown on grid background, deselect all + else if (!IsHoveringNode) { + currentActivity = NodeActivity.HoldGrid; + if (!e.control && !e.shift) { + selectedReroutes.Clear(); + Selection.activeObject = null; + } + } + } + break; + case EventType.MouseUp: + if (e.button == 0) { + //Port drag release + if (IsDraggingPort) { + // If connection is valid, save it + if (draggedOutputTarget != null && graphEditor.CanConnect(draggedOutput, draggedOutputTarget)) { + var node = draggedOutputTarget.node; + if (graph.nodes.Count != 0) + { + draggedOutput.Connect(draggedOutputTarget); + } + + // ConnectionIndex can be -1 if the connection is removed instantly after creation + var connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget); + if (connectionIndex != -1) { + draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes); + if (NodeEditor.onUpdateNode != null) + { + NodeEditor.onUpdateNode(node); + } + + EditorUtility.SetDirty(graph); + } + } + // Open context menu for auto-connection if there is no target node + else if (draggedOutputTarget == null && NodeEditorPreferences.GetSettings().dragToCreate && autoConnectOutput != null) { + var menu = new GenericMenu(); + graphEditor.AddContextMenuItems(menu, draggedOutput.ValueType); + menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); + } + //Release dragged connection + draggedOutput = null; + draggedOutputTarget = null; + EditorUtility.SetDirty(graph); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } else if (currentActivity == NodeActivity.DragNode) { + var nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node); + foreach (var node in nodes) + { + EditorUtility.SetDirty(node); + } + + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } else if (!IsHoveringNode) { + // If click outside node, release field focus + if (!isPanning) { + EditorGUI.FocusTextInControl(null); + EditorGUIUtility.editingTextField = false; + } + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } + + // If click node header, select it. + if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift)) { + selectedReroutes.Clear(); + SelectNode(hoveredNode, false); + + // Double click to center node + if (isDoubleClick) { + var nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero; + panOffset = -hoveredNode.position - nodeDimension; + } + } + + // If click reroute, select it. + if (IsHoveringReroute && !(e.control || e.shift)) { + selectedReroutes = new List() { hoveredReroute }; + Selection.activeObject = null; + } + + Repaint(); + currentActivity = NodeActivity.Idle; + } else if (e.button == 1 || e.button == 2) { + if (!isPanning) { + if (IsDraggingPort) { + draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition)); + } else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1) { + selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint()); + selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1); + } else if (IsHoveringReroute) { + ShowRerouteContextMenu(hoveredReroute); + } else if (IsHoveringPort) { + ShowPortContextMenu(hoveredPort); + } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { + if (!Selection.Contains(hoveredNode)) + { + SelectNode(hoveredNode, false); + } + + autoConnectOutput = null; + var menu = new GenericMenu(); + NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu); + menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); + e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places. + } else if (!IsHoveringNode) { + autoConnectOutput = null; + var menu = new GenericMenu(); + graphEditor.AddContextMenuItems(menu); + menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); + } + } + isPanning = false; + } + // Reset DoubleClick + isDoubleClick = false; + break; + case EventType.KeyDown: + if (EditorGUIUtility.editingTextField || GUIUtility.keyboardControl != 0) + { + break; + } + else if (e.keyCode == KeyCode.F) + { + Home(); + } + + if (NodeEditorUtilities.IsMac()) { + if (e.keyCode == KeyCode.Return) + { + RenameSelectedNode(); + } + } else { + if (e.keyCode == KeyCode.F2) + { + RenameSelectedNode(); + } + } + if (e.keyCode == KeyCode.A) { + if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node))) { + foreach (var node in graph.nodes) { + DeselectNode(node); + } + } else { + foreach (var node in graph.nodes) { + SelectNode(node, true); + } + } + Repaint(); + } + break; + case EventType.ValidateCommand: + case EventType.ExecuteCommand: + if (e.commandName == "SoftDelete") { + if (e.type == EventType.ExecuteCommand) + { + RemoveSelectedNodes(); + } + + e.Use(); + } else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete") { + if (e.type == EventType.ExecuteCommand) + { + RemoveSelectedNodes(); + } + + e.Use(); + } else if (e.commandName == "Duplicate") { + if (e.type == EventType.ExecuteCommand) + { + DuplicateSelectedNodes(); + } + + e.Use(); + } else if (e.commandName == "Copy") { + if (!EditorGUIUtility.editingTextField) { + if (e.type == EventType.ExecuteCommand) + { + CopySelectedNodes(); + } + + e.Use(); + } + } else if (e.commandName == "Paste") { + if (!EditorGUIUtility.editingTextField) { + if (e.type == EventType.ExecuteCommand) + { + PasteNodes(WindowToGridPosition(lastMousePosition)); + } + + e.Use(); + } + } + Repaint(); + break; + case EventType.Ignore: + // If release mouse outside window + if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid) { + Repaint(); + currentActivity = NodeActivity.Idle; + } + break; + } + } + + private void RecalculateDragOffsets(Event current) { + dragOffset = new Vector2[Selection.objects.Length + selectedReroutes.Count]; + // Selected nodes + for (var i = 0; i < Selection.objects.Length; i++) { + if (Selection.objects[i] is XNode.Node) { + var node = Selection.objects[i] as XNode.Node; + dragOffset[i] = node.position - WindowToGridPosition(current.mousePosition); + } + } + + // Selected reroutes + for (var i = 0; i < selectedReroutes.Count; i++) { + dragOffset[Selection.objects.Length + i] = selectedReroutes[i].GetPoint() - WindowToGridPosition(current.mousePosition); + } + } + + /// Puts all selected nodes in focus. If no nodes are present, resets view and zoom to to origin + public void Home() { + var nodes = Selection.objects.Where(o => o is XNode.Node).Cast().ToList(); + if (nodes.Count > 0) { + var minPos = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); + var maxPos = nodes.Select(x => x.position + (nodeSizes.ContainsKey(x) ? nodeSizes[x] : Vector2.zero)).Aggregate((x, y) => new Vector2(Mathf.Max(x.x, y.x), Mathf.Max(x.y, y.y))); + panOffset = -(minPos + (maxPos - minPos) / 2f); + } else { + zoom = 2; + panOffset = Vector2.zero; + } + } + + /// Remove nodes in the graph in Selection.objects + public void RemoveSelectedNodes() { + // We need to delete reroutes starting at the highest point index to avoid shifting indices + selectedReroutes = selectedReroutes.OrderByDescending(x => x.pointIndex).ToList(); + for (var i = 0; i < selectedReroutes.Count; i++) { + selectedReroutes[i].RemovePoint(); + } + selectedReroutes.Clear(); + foreach (var item in Selection.objects) { + if (item is XNode.Node) { + var node = item as XNode.Node; + graphEditor.RemoveNode(node); + } + } + } + + /// Initiate a rename on the currently selected node + public void RenameSelectedNode() { + if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { + var node = Selection.activeObject as XNode.Node; + Vector2 size; + if (nodeSizes.TryGetValue(node, out size)) { + RenamePopup.Show(Selection.activeObject, size.x); + } else { + RenamePopup.Show(Selection.activeObject); + } + } + } + + /// Draw this node on top of other nodes by placing it last in the graph.nodes list + public void MoveNodeToTop(XNode.Node node) { + int index; + while ((index = graph.nodes.IndexOf(node)) != graph.nodes.Count - 1) { + graph.nodes[index] = graph.nodes[index + 1]; + graph.nodes[index + 1] = node; + } + } + + /// Duplicate selected nodes and select the duplicates + public void DuplicateSelectedNodes() { + // Get selected nodes which are part of this graph + var selectedNodes = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray(); + if (selectedNodes == null || selectedNodes.Length == 0) + { + return; + } + + // Get top left node position + var topLeftNode = selectedNodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); + InsertDuplicateNodes(selectedNodes, topLeftNode + new Vector2(30, 30)); + } + + public void CopySelectedNodes() { + copyBuffer = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray(); + } + + public void PasteNodes(Vector2 pos) { + InsertDuplicateNodes(copyBuffer, pos); + } + + private void InsertDuplicateNodes(XNode.Node[] nodes, Vector2 topLeft) { + if (nodes == null || nodes.Length == 0) + { + return; + } + + // Get top-left node + var topLeftNode = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y))); + var offset = topLeft - topLeftNode; + + var newNodes = new UnityEngine.Object[nodes.Length]; + var substitutes = new Dictionary(); + for (var i = 0; i < nodes.Length; i++) { + var srcNode = nodes[i]; + if (srcNode == null) + { + continue; + } + + // Check if user is allowed to add more of given node type + XNode.Node.DisallowMultipleNodesAttribute disallowAttrib; + var nodeType = srcNode.GetType(); + if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib)) { + var typeCount = graph.nodes.Count(x => x.GetType() == nodeType); + if (typeCount >= disallowAttrib.max) + { + continue; + } + } + + var newNode = graphEditor.CopyNode(srcNode); + substitutes.Add(srcNode, newNode); + newNode.position = srcNode.position + offset; + newNodes[i] = newNode; + } + + // Walk through the selected nodes again, recreate connections, using the new nodes + for (var i = 0; i < nodes.Length; i++) { + var srcNode = nodes[i]; + if (srcNode == null) + { + continue; + } + + foreach (var port in srcNode.Ports) { + for (var c = 0; c < port.ConnectionCount; c++) { + var inputPort = port.direction == XNode.NodePort.IO.Input ? port : port.GetConnection(c); + var outputPort = port.direction == XNode.NodePort.IO.Output ? port : port.GetConnection(c); + + XNode.Node newNodeIn, newNodeOut; + if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut)) { + newNodeIn.UpdatePorts(); + newNodeOut.UpdatePorts(); + inputPort = newNodeIn.GetInputPort(inputPort.fieldName); + outputPort = newNodeOut.GetOutputPort(outputPort.fieldName); + } + if (!inputPort.IsConnectedTo(outputPort)) + { + inputPort.Connect(outputPort); + } + } + } + } + EditorUtility.SetDirty(graph); + // Select the new nodes + Selection.objects = newNodes; + } + + /// Draw a connection as we are dragging it + public void DrawDraggedConnection() { + if (IsDraggingPort) { + var gradient = graphEditor.GetNoodleGradient(draggedOutput, null); + var thickness = graphEditor.GetNoodleThickness(draggedOutput, null); + var path = graphEditor.GetNoodlePath(draggedOutput, null); + var stroke = graphEditor.GetNoodleStroke(draggedOutput, null); + + Rect fromRect; + if (!_portConnectionPoints.TryGetValue(draggedOutput, out fromRect)) + { + return; + } + + var gridPoints = new List(); + gridPoints.Add(fromRect.center); + for (var i = 0; i < draggedOutputReroutes.Count; i++) { + gridPoints.Add(draggedOutputReroutes[i]); + } + if (draggedOutputTarget != null) + { + gridPoints.Add(portConnectionPoints[draggedOutputTarget].center); + } + else + { + gridPoints.Add(WindowToGridPosition(Event.current.mousePosition)); + } + + DrawNoodle(gradient, path, stroke, thickness, gridPoints); + + var portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(draggedOutput); + var bgcol = Color.black; + var frcol = gradient.colorKeys[0].color; + bgcol.a = 0.6f; + frcol.a = 0.6f; + + // Loop through reroute points again and draw the points + for (var i = 0; i < draggedOutputReroutes.Count; i++) { + // Draw reroute point at position + var rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16)); + rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8); + rect = GridToWindowRect(rect); + + NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol, portStyle.normal.background, portStyle.active.background); + } + } + } + + private bool IsHoveringTitle(XNode.Node node) { + var mousePos = Event.current.mousePosition; + //Get node position + var nodePos = GridToWindowPosition(node.position); + float width; + Vector2 size; + if (nodeSizes.TryGetValue(node, out size)) + { + width = size.x; + } + else + { + width = 200; + } + + var windowRect = new Rect(nodePos, new Vector2(width / zoom, 30 / zoom)); + return windowRect.Contains(mousePos); + } + + /// Attempt to connect dragged output to target node + public void AutoConnect(XNode.Node node) { + if (autoConnectOutput == null) + { + return; + } + + // Find compatible input port + var inputPort = node.Ports.FirstOrDefault(x => x.IsInput && graphEditor.CanConnect(autoConnectOutput, x)); + if (inputPort != null) + { + autoConnectOutput.Connect(inputPort); + } + + // Save changes + EditorUtility.SetDirty(graph); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + + autoConnectOutput = null; + } + } +} diff --git a/Scripts/Editor/NodeEditorAction.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAction.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorAction.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAction.cs.meta diff --git a/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAssetModProcessor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAssetModProcessor.cs new file mode 100644 index 0000000..873b5d2 --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAssetModProcessor.cs @@ -0,0 +1,103 @@ +using UnityEditor; +using UnityEngine; +using System.IO; + +namespace XNodeEditor +{ + /// Deals with modified assets + internal class NodeEditorAssetModProcessor : AssetModificationProcessor + { + /// Automatically delete Node sub-assets before deleting their script. + /// This is important to do, because you can't delete null sub assets. + /// For another workaround, see: https://gitlab.com/RotaryHeart-UnityShare/subassetmissingscriptdelete + private static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options) + { + // Skip processing anything without the .cs extension + if (Path.GetExtension(path) != ".cs") + { + return AssetDeleteResult.DidNotDelete; + } + + // Get the object that is requested for deletion + var obj = AssetDatabase.LoadAssetAtPath(path); + + // If we aren't deleting a script, return + if (obj is MonoScript script) + { + var scriptType = script.GetClass(); + + if (scriptType == null || + (scriptType != typeof(XNode.Node) && !scriptType.IsSubclassOf(typeof(XNode.Node)))) + { + return AssetDeleteResult.DidNotDelete; + } + + // Find all ScriptableObjects using this script + var guids = AssetDatabase.FindAssets($"t:{scriptType}"); + + for (var i = 0; i < guids.Length; i++) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); + var objects = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath); + + for (var k = 0; k < objects.Length; k++) + { + if (objects[k] is XNode.Node node && + node.GetType() == scriptType && + node != null && node.graph != null) + { + // Delete the node and notify the user + Debug.LogWarning($"{node.name} of {node.graph} depended on deleted script and has been removed automatically.", node.graph); + node.graph.RemoveNode(node); + } + } + } + + // We didn't actually delete the script. Tell the internal system to carry on with normal deletion procedure + return AssetDeleteResult.DidNotDelete; + } + + // Check script type. Return if deleting a non-node script + return AssetDeleteResult.DidNotDelete; + } + + [InitializeOnLoadMethod] + private static void Init() => OnReloadEditor(); + + /// Automatically re-add loose node assets to the Graph node list + private static void OnReloadEditor() => EditorApplication.delayCall += () => + { + if (EditorApplication.isUpdating) + { + OnReloadEditor(); + return; + } + + // Find all NodeGraph assets + var guids = AssetDatabase.FindAssets($"t:{typeof(XNode.NodeGraph)}"); + + for (var i = 0; i < guids.Length; i++) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); + + if (AssetDatabase.LoadAssetAtPath(assetPath, typeof(XNode.NodeGraph)) is XNode.NodeGraph graph) + { + graph.nodes.RemoveAll(x => x == null); //Remove null items + var objects = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath); + + // Ensure that all sub node assets are present in the graph node list + for (var u = 0; u < objects.Length; u++) + { + // Ignore null sub assets + if (objects[u] == null) { continue; } + + if (!graph.nodes.Contains(objects[u] as XNode.Node)) + { + graph.nodes.Add(objects[u] as XNode.Node); + } + } + } + } + }; + } +} diff --git a/Scripts/Editor/NodeEditorAssetModProcessor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAssetModProcessor.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorAssetModProcessor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorAssetModProcessor.cs.meta diff --git a/Scripts/Editor/NodeEditorBase.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorBase.cs similarity index 65% rename from Scripts/Editor/NodeEditorBase.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorBase.cs index e556a10..c34e2a6 100644 --- a/Scripts/Editor/NodeEditorBase.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorBase.cs @@ -40,11 +40,15 @@ namespace XNodeEditor.Internal { #endif public static T GetEditor(K target, NodeEditorWindow window) { - if (target == null) return null; - T editor; + if (target == null) + { + return null; + } + + T editor; if (!editors.TryGetValue(target, out editor)) { - Type type = target.GetType(); - Type editorType = GetEditorType(type); + var type = target.GetType(); + var editorType = GetEditorType(type); editor = Activator.CreateInstance(editorType) as T; editor.target = target; editor.serializedObject = new SerializedObject(target); @@ -52,15 +56,31 @@ namespace XNodeEditor.Internal { editor.OnCreate(); editors.Add(target, editor); } - if (editor.target == null) editor.target = target; - if (editor.window != window) editor.window = window; - if (editor.serializedObject == null) editor.serializedObject = new SerializedObject(target); - return editor; + if (editor.target == null) + { + editor.target = target; + } + + if (editor.window != window) + { + editor.window = window; + } + + if (editor.serializedObject == null) + { + editor.serializedObject = new SerializedObject(target); + } + + return editor; } public static void DestroyEditor( K target ) { - if ( target == null ) return; + if ( target == null ) + { + return; + } + T editor; if ( editors.TryGetValue( target, out editor ) ) { @@ -69,11 +89,23 @@ namespace XNodeEditor.Internal { } private static Type GetEditorType(Type type) { - if (type == null) return null; - if (editorTypes == null) CacheCustomEditors(); - Type result; - if (editorTypes.TryGetValue(type, out result)) return result; - //If type isn't found, try base type + if (type == null) + { + return null; + } + + if (editorTypes == null) + { + CacheCustomEditors(); + } + + Type result; + if (editorTypes.TryGetValue(type, out result)) + { + return result; + } + + //If type isn't found, try base type return GetEditorType(type.BaseType); } @@ -81,12 +113,20 @@ namespace XNodeEditor.Internal { editorTypes = new Dictionary(); //Get all classes deriving from NodeEditor via reflection - Type[] nodeEditors = typeof(T).GetDerivedTypes(); - for (int i = 0; i < nodeEditors.Length; i++) { - if (nodeEditors[i].IsAbstract) continue; - var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false); - if (attribs == null || attribs.Length == 0) continue; - A attrib = attribs[0] as A; + var nodeEditors = typeof(T).GetDerivedTypes(); + for (var i = 0; i < nodeEditors.Length; i++) { + if (nodeEditors[i].IsAbstract) + { + continue; + } + + var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false); + if (attribs == null || attribs.Length == 0) + { + continue; + } + + var attrib = attribs[0] as A; editorTypes.Add(attrib.GetInspectedType(), nodeEditors[i]); } } @@ -98,4 +138,4 @@ namespace XNodeEditor.Internal { Type GetInspectedType(); } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/NodeEditorBase.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorBase.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorBase.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorBase.cs.meta diff --git a/Scripts/Editor/NodeEditorGUI.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUI.cs old mode 100755 new mode 100644 similarity index 56% rename from Scripts/Editor/NodeEditorGUI.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUI.cs index 35b2e2a..ebf7e8b --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUI.cs @@ -1,590 +1,754 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEditor; -using UnityEngine; -using XNodeEditor.Internal; -#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU -using GenericMenu = XNodeEditor.AdvancedGenericMenu; -#endif - -namespace XNodeEditor { - /// Contains GUI methods - public partial class NodeEditorWindow { - public NodeGraphEditor graphEditor; - private List selectionCache; - private List culledNodes; - /// 19 if docked, 22 if not - private int topPadding { get { return isDocked() ? 19 : 22; } } - /// Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run. - public event Action onLateGUI; - private static readonly Vector3[] polyLineTempArray = new Vector3[2]; - - protected virtual void OnGUI() { - Event e = Event.current; - Matrix4x4 m = GUI.matrix; - if (graph == null) return; - ValidateGraphEditor(); - Controls(); - - DrawGrid(position, zoom, panOffset); - DrawConnections(); - DrawDraggedConnection(); - DrawNodes(); - DrawSelectionBox(); - DrawTooltip(); - graphEditor.OnGUI(); - - // Run and reset onLateGUI - if (onLateGUI != null) { - onLateGUI(); - onLateGUI = null; - } - - GUI.matrix = m; - } - - public static void BeginZoomed(Rect rect, float zoom, float topPadding) { - GUI.EndClip(); - - GUIUtility.ScaleAroundPivot(Vector2.one / zoom, rect.size * 0.5f); - Vector4 padding = new Vector4(0, topPadding, 0, 0); - padding *= zoom; - GUI.BeginClip(new Rect(-((rect.width * zoom) - rect.width) * 0.5f, -(((rect.height * zoom) - rect.height) * 0.5f) + (topPadding * zoom), - rect.width * zoom, - rect.height * zoom)); - } - - public static void EndZoomed(Rect rect, float zoom, float topPadding) { - GUIUtility.ScaleAroundPivot(Vector2.one * zoom, rect.size * 0.5f); - Vector3 offset = new Vector3( - (((rect.width * zoom) - rect.width) * 0.5f), - (((rect.height * zoom) - rect.height) * 0.5f) + (-topPadding * zoom) + topPadding, - 0); - GUI.matrix = Matrix4x4.TRS(offset, Quaternion.identity, Vector3.one); - } - - public void DrawGrid(Rect rect, float zoom, Vector2 panOffset) { - - rect.position = Vector2.zero; - - Vector2 center = rect.size / 2f; - Texture2D gridTex = graphEditor.GetGridTexture(); - Texture2D crossTex = graphEditor.GetSecondaryGridTexture(); - - // Offset from origin in tile units - float xOffset = -(center.x * zoom + panOffset.x) / gridTex.width; - float yOffset = ((center.y - rect.size.y) * zoom + panOffset.y) / gridTex.height; - - Vector2 tileOffset = new Vector2(xOffset, yOffset); - - // Amount of tiles - float tileAmountX = Mathf.Round(rect.size.x * zoom) / gridTex.width; - float tileAmountY = Mathf.Round(rect.size.y * zoom) / gridTex.height; - - Vector2 tileAmount = new Vector2(tileAmountX, tileAmountY); - - // Draw tiled background - GUI.DrawTextureWithTexCoords(rect, gridTex, new Rect(tileOffset, tileAmount)); - GUI.DrawTextureWithTexCoords(rect, crossTex, new Rect(tileOffset + new Vector2(0.5f, 0.5f), tileAmount)); - } - - public void DrawSelectionBox() { - if (currentActivity == NodeActivity.DragGrid) { - Vector2 curPos = WindowToGridPosition(Event.current.mousePosition); - Vector2 size = curPos - dragBoxStart; - Rect r = new Rect(dragBoxStart, size); - r.position = GridToWindowPosition(r.position); - r.size /= zoom; - Handles.DrawSolidRectangleWithOutline(r, new Color(0, 0, 0, 0.1f), new Color(1, 1, 1, 0.6f)); - } - } - - public static bool DropdownButton(string name, float width) { - return GUILayout.Button(name, EditorStyles.toolbarDropDown, GUILayout.Width(width)); - } - - /// Show right-click context menu for hovered reroute - void ShowRerouteContextMenu(RerouteReference reroute) { - GenericMenu contextMenu = new GenericMenu(); - contextMenu.AddItem(new GUIContent("Remove"), false, () => reroute.RemovePoint()); - contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } - - /// Show right-click context menu for hovered port - void ShowPortContextMenu(XNode.NodePort hoveredPort) { - GenericMenu contextMenu = new GenericMenu(); - foreach (var port in hoveredPort.GetConnections()) { - var name = port.node.name; - var index = hoveredPort.GetConnectionIndex(port); - contextMenu.AddItem(new GUIContent(string.Format("Disconnect({0})", name)), false, () => hoveredPort.Disconnect(index)); - } - contextMenu.AddItem(new GUIContent("Clear Connections"), false, () => hoveredPort.ClearConnections()); - //Get compatible nodes with this port - if (NodeEditorPreferences.GetSettings().createFilter) { - contextMenu.AddSeparator(""); - - if (hoveredPort.direction == XNode.NodePort.IO.Input) - graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, XNode.NodePort.IO.Output); - else - graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, XNode.NodePort.IO.Input); - } - contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } - - static Vector2 CalculateBezierPoint(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t) { - float u = 1 - t; - float tt = t * t, uu = u * u; - float uuu = uu * u, ttt = tt * t; - return new Vector2( - (uuu * p0.x) + (3 * uu * t * p1.x) + (3 * u * tt * p2.x) + (ttt * p3.x), - (uuu * p0.y) + (3 * uu * t * p1.y) + (3 * u * tt * p2.y) + (ttt * p3.y) - ); - } - - /// Draws a line segment without allocating temporary arrays - static void DrawAAPolyLineNonAlloc(float thickness, Vector2 p0, Vector2 p1) { - polyLineTempArray[0].x = p0.x; - polyLineTempArray[0].y = p0.y; - polyLineTempArray[1].x = p1.x; - polyLineTempArray[1].y = p1.y; - Handles.DrawAAPolyLine(thickness, polyLineTempArray); - } - - /// Draw a bezier from output to input in grid coordinates - public void DrawNoodle(Gradient gradient, NoodlePath path, NoodleStroke stroke, float thickness, List gridPoints) { - // convert grid points to window points - for (int i = 0; i < gridPoints.Count; ++i) - gridPoints[i] = GridToWindowPosition(gridPoints[i]); - - Color originalHandlesColor = Handles.color; - Handles.color = gradient.Evaluate(0f); - int length = gridPoints.Count; - switch (path) { - case NoodlePath.Curvy: - Vector2 outputTangent = Vector2.right; - for (int i = 0; i < length - 1; i++) { - Vector2 inputTangent; - // Cached most variables that repeat themselves here to avoid so many indexer calls :p - Vector2 point_a = gridPoints[i]; - Vector2 point_b = gridPoints[i + 1]; - float dist_ab = Vector2.Distance(point_a, point_b); - if (i == 0) outputTangent = zoom * dist_ab * 0.01f * Vector2.right; - if (i < length - 2) { - Vector2 point_c = gridPoints[i + 2]; - Vector2 ab = (point_b - point_a).normalized; - Vector2 cb = (point_b - point_c).normalized; - Vector2 ac = (point_c - point_a).normalized; - Vector2 p = (ab + cb) * 0.5f; - float tangentLength = (dist_ab + Vector2.Distance(point_b, point_c)) * 0.005f * zoom; - float side = ((ac.x * (point_b.y - point_a.y)) - (ac.y * (point_b.x - point_a.x))); - - p = tangentLength * Mathf.Sign(side) * new Vector2(-p.y, p.x); - inputTangent = p; - } else { - inputTangent = zoom * dist_ab * 0.01f * Vector2.left; - } - - // Calculates the tangents for the bezier's curves. - float zoomCoef = 50 / zoom; - Vector2 tangent_a = point_a + outputTangent * zoomCoef; - Vector2 tangent_b = point_b + inputTangent * zoomCoef; - // Hover effect. - int division = Mathf.RoundToInt(.2f * dist_ab) + 3; - // Coloring and bezier drawing. - int draw = 0; - Vector2 bezierPrevious = point_a; - for (int j = 1; j <= division; ++j) { - if (stroke == NoodleStroke.Dashed) { - draw++; - if (draw >= 2) draw = -2; - if (draw < 0) continue; - if (draw == 0) bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, (j - 1f) / (float) division); - } - if (i == length - 2) - Handles.color = gradient.Evaluate((j + 1f) / division); - Vector2 bezierNext = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, j / (float) division); - DrawAAPolyLineNonAlloc(thickness, bezierPrevious, bezierNext); - bezierPrevious = bezierNext; - } - outputTangent = -inputTangent; - } - break; - case NoodlePath.Straight: - for (int i = 0; i < length - 1; i++) { - Vector2 point_a = gridPoints[i]; - Vector2 point_b = gridPoints[i + 1]; - // Draws the line with the coloring. - Vector2 prev_point = point_a; - // Approximately one segment per 5 pixels - int segments = (int) Vector2.Distance(point_a, point_b) / 5; - segments = Math.Max(segments, 1); - - int draw = 0; - for (int j = 0; j <= segments; j++) { - draw++; - float t = j / (float) segments; - Vector2 lerp = Vector2.Lerp(point_a, point_b, t); - if (draw > 0) { - if (i == length - 2) Handles.color = gradient.Evaluate(t); - DrawAAPolyLineNonAlloc(thickness, prev_point, lerp); - } - prev_point = lerp; - if (stroke == NoodleStroke.Dashed && draw >= 2) draw = -2; - } - } - break; - case NoodlePath.Angled: - for (int i = 0; i < length - 1; i++) { - if (i == length - 1) continue; // Skip last index - if (gridPoints[i].x <= gridPoints[i + 1].x - (50 / zoom)) { - float midpoint = (gridPoints[i].x + gridPoints[i + 1].x) * 0.5f; - Vector2 start_1 = gridPoints[i]; - Vector2 end_1 = gridPoints[i + 1]; - start_1.x = midpoint; - end_1.x = midpoint; - if (i == length - 2) { - DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); - Handles.color = gradient.Evaluate(0.5f); - DrawAAPolyLineNonAlloc(thickness, start_1, end_1); - Handles.color = gradient.Evaluate(1f); - DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); - } else { - DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); - DrawAAPolyLineNonAlloc(thickness, start_1, end_1); - DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); - } - } else { - float midpoint = (gridPoints[i].y + gridPoints[i + 1].y) * 0.5f; - Vector2 start_1 = gridPoints[i]; - Vector2 end_1 = gridPoints[i + 1]; - start_1.x += 25 / zoom; - end_1.x -= 25 / zoom; - Vector2 start_2 = start_1; - Vector2 end_2 = end_1; - start_2.y = midpoint; - end_2.y = midpoint; - if (i == length - 2) { - DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); - Handles.color = gradient.Evaluate(0.25f); - DrawAAPolyLineNonAlloc(thickness, start_1, start_2); - Handles.color = gradient.Evaluate(0.5f); - DrawAAPolyLineNonAlloc(thickness, start_2, end_2); - Handles.color = gradient.Evaluate(0.75f); - DrawAAPolyLineNonAlloc(thickness, end_2, end_1); - Handles.color = gradient.Evaluate(1f); - DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); - } else { - DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); - DrawAAPolyLineNonAlloc(thickness, start_1, start_2); - DrawAAPolyLineNonAlloc(thickness, start_2, end_2); - DrawAAPolyLineNonAlloc(thickness, end_2, end_1); - DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); - } - } - } - break; - case NoodlePath.ShaderLab: - Vector2 start = gridPoints[0]; - Vector2 end = gridPoints[length - 1]; - //Modify first and last point in array so we can loop trough them nicely. - gridPoints[0] = gridPoints[0] + Vector2.right * (20 / zoom); - gridPoints[length - 1] = gridPoints[length - 1] + Vector2.left * (20 / zoom); - //Draw first vertical lines going out from nodes - Handles.color = gradient.Evaluate(0f); - DrawAAPolyLineNonAlloc(thickness, start, gridPoints[0]); - Handles.color = gradient.Evaluate(1f); - DrawAAPolyLineNonAlloc(thickness, end, gridPoints[length - 1]); - for (int i = 0; i < length - 1; i++) { - Vector2 point_a = gridPoints[i]; - Vector2 point_b = gridPoints[i + 1]; - // Draws the line with the coloring. - Vector2 prev_point = point_a; - // Approximately one segment per 5 pixels - int segments = (int) Vector2.Distance(point_a, point_b) / 5; - segments = Math.Max(segments, 1); - - int draw = 0; - for (int j = 0; j <= segments; j++) { - draw++; - float t = j / (float) segments; - Vector2 lerp = Vector2.Lerp(point_a, point_b, t); - if (draw > 0) { - if (i == length - 2) Handles.color = gradient.Evaluate(t); - DrawAAPolyLineNonAlloc(thickness, prev_point, lerp); - } - prev_point = lerp; - if (stroke == NoodleStroke.Dashed && draw >= 2) draw = -2; - } - } - gridPoints[0] = start; - gridPoints[length - 1] = end; - break; - } - Handles.color = originalHandlesColor; - } - - /// Draws all connections - public void DrawConnections() { - Vector2 mousePos = Event.current.mousePosition; - List selection = preBoxSelectionReroute != null ? new List(preBoxSelectionReroute) : new List(); - hoveredReroute = new RerouteReference(); - - List gridPoints = new List(2); - - Color col = GUI.color; - foreach (XNode.Node node in graph.nodes) { - //If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset. - if (node == null) continue; - - // Draw full connections and output > reroute - foreach (XNode.NodePort output in node.Outputs) { - //Needs cleanup. Null checks are ugly - Rect fromRect; - if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue; - - Color portColor = graphEditor.GetPortColor(output); - GUIStyle portStyle = graphEditor.GetPortStyle(output); - - for (int k = 0; k < output.ConnectionCount; k++) { - XNode.NodePort input = output.GetConnection(k); - - Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input); - float noodleThickness = graphEditor.GetNoodleThickness(output, input); - NoodlePath noodlePath = graphEditor.GetNoodlePath(output, input); - NoodleStroke noodleStroke = graphEditor.GetNoodleStroke(output, input); - - // Error handling - if (input == null) continue; //If a script has been updated and the port doesn't exist, it is removed and null is returned. If this happens, return. - if (!input.IsConnectedTo(output)) input.Connect(output); - Rect toRect; - if (!_portConnectionPoints.TryGetValue(input, out toRect)) continue; - - List reroutePoints = output.GetReroutePoints(k); - - gridPoints.Clear(); - gridPoints.Add(fromRect.center); - gridPoints.AddRange(reroutePoints); - gridPoints.Add(toRect.center); - DrawNoodle(noodleGradient, noodlePath, noodleStroke, noodleThickness, gridPoints); - - // Loop through reroute points again and draw the points - for (int i = 0; i < reroutePoints.Count; i++) { - RerouteReference rerouteRef = new RerouteReference(output, k, i); - // Draw reroute point at position - Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12)); - rect.position = new Vector2(rect.position.x - 6, rect.position.y - 6); - rect = GridToWindowRect(rect); - - // Draw selected reroute points with an outline - if (selectedReroutes.Contains(rerouteRef)) { - GUI.color = NodeEditorPreferences.GetSettings().highlightColor; - GUI.DrawTexture(rect, portStyle.normal.background); - } - - GUI.color = portColor; - GUI.DrawTexture(rect, portStyle.active.background); - if (rect.Overlaps(selectionBox)) selection.Add(rerouteRef); - if (rect.Contains(mousePos)) hoveredReroute = rerouteRef; - - } - } - } - } - GUI.color = col; - if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) selectedReroutes = selection; - } - - private void DrawNodes() { - Event e = Event.current; - if (e.type == EventType.Layout) { - selectionCache = new List(Selection.objects); - } - - System.Reflection.MethodInfo onValidate = null; - if (Selection.activeObject != null && Selection.activeObject is XNode.Node) { - onValidate = Selection.activeObject.GetType().GetMethod("OnValidate"); - if (onValidate != null) EditorGUI.BeginChangeCheck(); - } - - BeginZoomed(position, zoom, topPadding); - - Vector2 mousePos = Event.current.mousePosition; - - if (e.type != EventType.Layout) { - hoveredNode = null; - hoveredPort = null; - } - - List preSelection = preBoxSelection != null ? new List(preBoxSelection) : new List(); - - // Selection box stuff - Vector2 boxStartPos = GridToWindowPositionNoClipped(dragBoxStart); - Vector2 boxSize = mousePos - boxStartPos; - if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); } - if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); } - Rect selectionBox = new Rect(boxStartPos, boxSize); - - //Save guiColor so we can revert it - Color guiColor = GUI.color; - - List removeEntries = new List(); - - if (e.type == EventType.Layout) culledNodes = new List(); - for (int n = 0; n < graph.nodes.Count; n++) { - // Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable. - if (graph.nodes[n] == null) continue; - if (n >= graph.nodes.Count) return; - XNode.Node node = graph.nodes[n]; - - // Culling - if (e.type == EventType.Layout) { - // Cull unselected nodes outside view - if (!Selection.Contains(node) && ShouldBeCulled(node)) { - culledNodes.Add(node); - continue; - } - } else if (culledNodes.Contains(node)) continue; - - if (e.type == EventType.Repaint) { - removeEntries.Clear(); - foreach (var kvp in _portConnectionPoints) - if (kvp.Key.node == node) removeEntries.Add(kvp.Key); - foreach (var k in removeEntries) _portConnectionPoints.Remove(k); - } - - NodeEditor nodeEditor = NodeEditor.GetEditor(node, this); - - NodeEditor.portPositions.Clear(); - - // Set default label width. This is potentially overridden in OnBodyGUI - EditorGUIUtility.labelWidth = 84; - - //Get node position - Vector2 nodePos = GridToWindowPositionNoClipped(node.position); - - GUILayout.BeginArea(new Rect(nodePos, new Vector2(nodeEditor.GetWidth(), 4000))); - - bool selected = selectionCache.Contains(graph.nodes[n]); - - if (selected) { - GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle()); - GUIStyle highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle()); - highlightStyle.padding = style.padding; - style.padding = new RectOffset(); - GUI.color = nodeEditor.GetTint(); - GUILayout.BeginVertical(style); - GUI.color = NodeEditorPreferences.GetSettings().highlightColor; - GUILayout.BeginVertical(new GUIStyle(highlightStyle)); - } else { - GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle()); - GUI.color = nodeEditor.GetTint(); - GUILayout.BeginVertical(style); - } - - GUI.color = guiColor; - EditorGUI.BeginChangeCheck(); - - //Draw node contents - nodeEditor.OnHeaderGUI(); - nodeEditor.OnBodyGUI(); - - //If user changed a value, notify other scripts through onUpdateNode - if (EditorGUI.EndChangeCheck()) { - if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node); - EditorUtility.SetDirty(node); - nodeEditor.serializedObject.ApplyModifiedProperties(); - } - - GUILayout.EndVertical(); - - //Cache data about the node for next frame - if (e.type == EventType.Repaint) { - Vector2 size = GUILayoutUtility.GetLastRect().size; - if (nodeSizes.ContainsKey(node)) nodeSizes[node] = size; - else nodeSizes.Add(node, size); - - foreach (var kvp in NodeEditor.portPositions) { - Vector2 portHandlePos = kvp.Value; - portHandlePos += node.position; - Rect rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16); - portConnectionPoints[kvp.Key] = rect; - } - } - - if (selected) GUILayout.EndVertical(); - - if (e.type != EventType.Layout) { - //Check if we are hovering this node - Vector2 nodeSize = GUILayoutUtility.GetLastRect().size; - Rect windowRect = new Rect(nodePos, nodeSize); - if (windowRect.Contains(mousePos)) hoveredNode = node; - - //If dragging a selection box, add nodes inside to selection - if (currentActivity == NodeActivity.DragGrid) { - if (windowRect.Overlaps(selectionBox)) preSelection.Add(node); - } - - //Check if we are hovering any of this nodes ports - //Check input ports - foreach (XNode.NodePort input in node.Inputs) { - //Check if port rect is available - if (!portConnectionPoints.ContainsKey(input)) continue; - Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]); - if (r.Contains(mousePos)) hoveredPort = input; - } - //Check all output ports - foreach (XNode.NodePort output in node.Outputs) { - //Check if port rect is available - if (!portConnectionPoints.ContainsKey(output)) continue; - Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]); - if (r.Contains(mousePos)) hoveredPort = output; - } - } - - GUILayout.EndArea(); - } - - if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) Selection.objects = preSelection.ToArray(); - EndZoomed(position, zoom, topPadding); - - //If a change in is detected in the selected node, call OnValidate method. - //This is done through reflection because OnValidate is only relevant in editor, - //and thus, the code should not be included in build. - if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null); - } - - private bool ShouldBeCulled(XNode.Node node) { - - Vector2 nodePos = GridToWindowPositionNoClipped(node.position); - if (nodePos.x / _zoom > position.width) return true; // Right - else if (nodePos.y / _zoom > position.height) return true; // Bottom - else if (nodeSizes.ContainsKey(node)) { - Vector2 size = nodeSizes[node]; - if (nodePos.x + size.x < 0) return true; // Left - else if (nodePos.y + size.y < 0) return true; // Top - } - return false; - } - - private void DrawTooltip() { - if (!NodeEditorPreferences.GetSettings().portTooltips || graphEditor == null) - return; - string tooltip = null; - if (hoveredPort != null) { - tooltip = graphEditor.GetPortTooltip(hoveredPort); - } else if (hoveredNode != null && IsHoveringNode && IsHoveringTitle(hoveredNode)) { - tooltip = NodeEditor.GetEditor(hoveredNode, this).GetHeaderTooltip(); - } - if (string.IsNullOrEmpty(tooltip)) return; - GUIContent content = new GUIContent(tooltip); - Vector2 size = NodeEditorResources.styles.tooltip.CalcSize(content); - size.x += 8; - Rect rect = new Rect(Event.current.mousePosition - (size), size); - EditorGUI.LabelField(rect, content, NodeEditorResources.styles.tooltip); - Repaint(); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +using XNodeEditor.Internal; +#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU +using GenericMenu = XNodeEditor.AdvancedGenericMenu; +#endif + +namespace XNodeEditor { + /// Contains GUI methods + public partial class NodeEditorWindow { + public NodeGraphEditor graphEditor; + private List selectionCache; + private List culledNodes; + /// 19 if docked, 22 if not + private int topPadding { get { return isDocked() ? 19 : 22; } } + /// Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run. + public event Action onLateGUI; + private static readonly Vector3[] polyLineTempArray = new Vector3[2]; + + protected virtual void OnGUI() { + var e = Event.current; + var m = GUI.matrix; + if (graph == null) + { + return; + } + + ValidateGraphEditor(); + Controls(); + + DrawGrid(position, zoom, panOffset); + DrawConnections(); + DrawDraggedConnection(); + DrawNodes(); + DrawSelectionBox(); + DrawTooltip(); + graphEditor.OnGUI(); + + // Run and reset onLateGUI + if (onLateGUI != null) { + onLateGUI(); + onLateGUI = null; + } + + GUI.matrix = m; + } + + public static void BeginZoomed(Rect rect, float zoom, float topPadding) { + GUI.EndClip(); + + GUIUtility.ScaleAroundPivot(Vector2.one / zoom, rect.size * 0.5f); + var padding = new Vector4(0, topPadding, 0, 0); + padding *= zoom; + GUI.BeginClip(new Rect(-((rect.width * zoom) - rect.width) * 0.5f, -(((rect.height * zoom) - rect.height) * 0.5f) + (topPadding * zoom), + rect.width * zoom, + rect.height * zoom)); + } + + public static void EndZoomed(Rect rect, float zoom, float topPadding) { + GUIUtility.ScaleAroundPivot(Vector2.one * zoom, rect.size * 0.5f); + var offset = new Vector3( + (((rect.width * zoom) - rect.width) * 0.5f), + (((rect.height * zoom) - rect.height) * 0.5f) + (-topPadding * zoom) + topPadding, + 0); + GUI.matrix = Matrix4x4.TRS(offset, Quaternion.identity, Vector3.one); + } + + public void DrawGrid(Rect rect, float zoom, Vector2 panOffset) { + + rect.position = Vector2.zero; + + var center = rect.size / 2f; + var gridTex = graphEditor.GetGridTexture(); + var crossTex = graphEditor.GetSecondaryGridTexture(); + + // Offset from origin in tile units + var xOffset = -(center.x * zoom + panOffset.x) / gridTex.width; + var yOffset = ((center.y - rect.size.y) * zoom + panOffset.y) / gridTex.height; + + var tileOffset = new Vector2(xOffset, yOffset); + + // Amount of tiles + var tileAmountX = Mathf.Round(rect.size.x * zoom) / gridTex.width; + var tileAmountY = Mathf.Round(rect.size.y * zoom) / gridTex.height; + + var tileAmount = new Vector2(tileAmountX, tileAmountY); + + // Draw tiled background + GUI.DrawTextureWithTexCoords(rect, gridTex, new Rect(tileOffset, tileAmount)); + GUI.DrawTextureWithTexCoords(rect, crossTex, new Rect(tileOffset + new Vector2(0.5f, 0.5f), tileAmount)); + } + + public void DrawSelectionBox() { + if (currentActivity == NodeActivity.DragGrid) { + var curPos = WindowToGridPosition(Event.current.mousePosition); + var size = curPos - dragBoxStart; + var r = new Rect(dragBoxStart, size); + r.position = GridToWindowPosition(r.position); + r.size /= zoom; + Handles.DrawSolidRectangleWithOutline(r, new Color(0, 0, 0, 0.1f), new Color(1, 1, 1, 0.6f)); + } + } + + public static bool DropdownButton(string name, float width) { + return GUILayout.Button(name, EditorStyles.toolbarDropDown, GUILayout.Width(width)); + } + + /// Show right-click context menu for hovered reroute + private void ShowRerouteContextMenu(RerouteReference reroute) { + var contextMenu = new GenericMenu(); + contextMenu.AddItem(new GUIContent("Remove"), false, () => reroute.RemovePoint()); + contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } + + /// Show right-click context menu for hovered port + private void ShowPortContextMenu(XNode.NodePort hoveredPort) { + var contextMenu = new GenericMenu(); + foreach (var port in hoveredPort.GetConnections()) { + var name = port.node.name; + var index = hoveredPort.GetConnectionIndex(port); + contextMenu.AddItem(new GUIContent(string.Format("Disconnect({0})", name)), false, () => hoveredPort.Disconnect(index)); + } + contextMenu.AddItem(new GUIContent("Clear Connections"), false, () => hoveredPort.ClearConnections()); + //Get compatible nodes with this port + if (NodeEditorPreferences.GetSettings().createFilter) { + contextMenu.AddSeparator(""); + + if (hoveredPort.direction == XNode.NodePort.IO.Input) + { + graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, XNode.NodePort.IO.Output); + } + else + { + graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, XNode.NodePort.IO.Input); + } + } + contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } + + private static Vector2 CalculateBezierPoint(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t) { + var u = 1 - t; + float tt = t * t, uu = u * u; + float uuu = uu * u, ttt = tt * t; + return new Vector2( + (uuu * p0.x) + (3 * uu * t * p1.x) + (3 * u * tt * p2.x) + (ttt * p3.x), + (uuu * p0.y) + (3 * uu * t * p1.y) + (3 * u * tt * p2.y) + (ttt * p3.y) + ); + } + + /// Draws a line segment without allocating temporary arrays + private static void DrawAAPolyLineNonAlloc(float thickness, Vector2 p0, Vector2 p1) { + polyLineTempArray[0].x = p0.x; + polyLineTempArray[0].y = p0.y; + polyLineTempArray[1].x = p1.x; + polyLineTempArray[1].y = p1.y; + Handles.DrawAAPolyLine(thickness, polyLineTempArray); + } + + /// Draw a bezier from output to input in grid coordinates + public void DrawNoodle(Gradient gradient, NoodlePath path, NoodleStroke stroke, float thickness, List gridPoints) { + // convert grid points to window points + for (var i = 0; i < gridPoints.Count; ++i) + { + gridPoints[i] = GridToWindowPosition(gridPoints[i]); + } + + var originalHandlesColor = Handles.color; + Handles.color = gradient.Evaluate(0f); + var length = gridPoints.Count; + switch (path) { + case NoodlePath.Curvy: + var outputTangent = Vector2.right; + for (var i = 0; i < length - 1; i++) { + Vector2 inputTangent; + // Cached most variables that repeat themselves here to avoid so many indexer calls :p + var point_a = gridPoints[i]; + var point_b = gridPoints[i + 1]; + var dist_ab = Vector2.Distance(point_a, point_b); + if (i == 0) + { + outputTangent = zoom * dist_ab * 0.01f * Vector2.right; + } + + if (i < length - 2) { + var point_c = gridPoints[i + 2]; + var ab = (point_b - point_a).normalized; + var cb = (point_b - point_c).normalized; + var ac = (point_c - point_a).normalized; + var p = (ab + cb) * 0.5f; + var tangentLength = (dist_ab + Vector2.Distance(point_b, point_c)) * 0.005f * zoom; + var side = ((ac.x * (point_b.y - point_a.y)) - (ac.y * (point_b.x - point_a.x))); + + p = tangentLength * Mathf.Sign(side) * new Vector2(-p.y, p.x); + inputTangent = p; + } else { + inputTangent = zoom * dist_ab * 0.01f * Vector2.left; + } + + // Calculates the tangents for the bezier's curves. + var zoomCoef = 50 / zoom; + var tangent_a = point_a + outputTangent * zoomCoef; + var tangent_b = point_b + inputTangent * zoomCoef; + // Hover effect. + var division = Mathf.RoundToInt(.2f * dist_ab) + 3; + // Coloring and bezier drawing. + var draw = 0; + var bezierPrevious = point_a; + for (var j = 1; j <= division; ++j) { + if (stroke == NoodleStroke.Dashed) { + draw++; + if (draw >= 2) + { + draw = -2; + } + + if (draw < 0) + { + continue; + } + + if (draw == 0) + { + bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, (j - 1f) / (float) division); + } + } + if (i == length - 2) + { + Handles.color = gradient.Evaluate((j + 1f) / division); + } + + var bezierNext = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, j / (float) division); + DrawAAPolyLineNonAlloc(thickness, bezierPrevious, bezierNext); + bezierPrevious = bezierNext; + } + outputTangent = -inputTangent; + } + break; + case NoodlePath.Straight: + for (var i = 0; i < length - 1; i++) { + var point_a = gridPoints[i]; + var point_b = gridPoints[i + 1]; + // Draws the line with the coloring. + var prev_point = point_a; + // Approximately one segment per 5 pixels + var segments = (int) Vector2.Distance(point_a, point_b) / 5; + segments = Math.Max(segments, 1); + + var draw = 0; + for (var j = 0; j <= segments; j++) { + draw++; + var t = j / (float) segments; + var lerp = Vector2.Lerp(point_a, point_b, t); + if (draw > 0) { + if (i == length - 2) + { + Handles.color = gradient.Evaluate(t); + } + + DrawAAPolyLineNonAlloc(thickness, prev_point, lerp); + } + prev_point = lerp; + if (stroke == NoodleStroke.Dashed && draw >= 2) + { + draw = -2; + } + } + } + break; + case NoodlePath.Angled: + for (var i = 0; i < length - 1; i++) { + if (i == length - 1) + { + continue; // Skip last index + } + + if (gridPoints[i].x <= gridPoints[i + 1].x - (50 / zoom)) { + var midpoint = (gridPoints[i].x + gridPoints[i + 1].x) * 0.5f; + var start_1 = gridPoints[i]; + var end_1 = gridPoints[i + 1]; + start_1.x = midpoint; + end_1.x = midpoint; + if (i == length - 2) { + DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); + Handles.color = gradient.Evaluate(0.5f); + DrawAAPolyLineNonAlloc(thickness, start_1, end_1); + Handles.color = gradient.Evaluate(1f); + DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); + } else { + DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); + DrawAAPolyLineNonAlloc(thickness, start_1, end_1); + DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); + } + } else { + var midpoint = (gridPoints[i].y + gridPoints[i + 1].y) * 0.5f; + var start_1 = gridPoints[i]; + var end_1 = gridPoints[i + 1]; + start_1.x += 25 / zoom; + end_1.x -= 25 / zoom; + var start_2 = start_1; + var end_2 = end_1; + start_2.y = midpoint; + end_2.y = midpoint; + if (i == length - 2) { + DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); + Handles.color = gradient.Evaluate(0.25f); + DrawAAPolyLineNonAlloc(thickness, start_1, start_2); + Handles.color = gradient.Evaluate(0.5f); + DrawAAPolyLineNonAlloc(thickness, start_2, end_2); + Handles.color = gradient.Evaluate(0.75f); + DrawAAPolyLineNonAlloc(thickness, end_2, end_1); + Handles.color = gradient.Evaluate(1f); + DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); + } else { + DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1); + DrawAAPolyLineNonAlloc(thickness, start_1, start_2); + DrawAAPolyLineNonAlloc(thickness, start_2, end_2); + DrawAAPolyLineNonAlloc(thickness, end_2, end_1); + DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]); + } + } + } + break; + case NoodlePath.ShaderLab: + var start = gridPoints[0]; + var end = gridPoints[length - 1]; + //Modify first and last point in array so we can loop trough them nicely. + gridPoints[0] = gridPoints[0] + Vector2.right * (20 / zoom); + gridPoints[length - 1] = gridPoints[length - 1] + Vector2.left * (20 / zoom); + //Draw first vertical lines going out from nodes + Handles.color = gradient.Evaluate(0f); + DrawAAPolyLineNonAlloc(thickness, start, gridPoints[0]); + Handles.color = gradient.Evaluate(1f); + DrawAAPolyLineNonAlloc(thickness, end, gridPoints[length - 1]); + for (var i = 0; i < length - 1; i++) { + var point_a = gridPoints[i]; + var point_b = gridPoints[i + 1]; + // Draws the line with the coloring. + var prev_point = point_a; + // Approximately one segment per 5 pixels + var segments = (int) Vector2.Distance(point_a, point_b) / 5; + segments = Math.Max(segments, 1); + + var draw = 0; + for (var j = 0; j <= segments; j++) { + draw++; + var t = j / (float) segments; + var lerp = Vector2.Lerp(point_a, point_b, t); + if (draw > 0) { + if (i == length - 2) + { + Handles.color = gradient.Evaluate(t); + } + + DrawAAPolyLineNonAlloc(thickness, prev_point, lerp); + } + prev_point = lerp; + if (stroke == NoodleStroke.Dashed && draw >= 2) + { + draw = -2; + } + } + } + gridPoints[0] = start; + gridPoints[length - 1] = end; + break; + } + Handles.color = originalHandlesColor; + } + + /// Draws all connections + public void DrawConnections() { + var mousePos = Event.current.mousePosition; + var selection = preBoxSelectionReroute != null ? new List(preBoxSelectionReroute) : new List(); + hoveredReroute = new RerouteReference(); + + var gridPoints = new List(2); + + var col = GUI.color; + foreach (var node in graph.nodes) { + //If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset. + if (node == null) + { + continue; + } + + // Draw full connections and output > reroute + foreach (var output in node.Outputs) { + //Needs cleanup. Null checks are ugly + Rect fromRect; + if (!_portConnectionPoints.TryGetValue(output, out fromRect)) + { + continue; + } + + var portColor = graphEditor.GetPortColor(output); + var portStyle = graphEditor.GetPortStyle(output); + + for (var k = 0; k < output.ConnectionCount; k++) { + var input = output.GetConnection(k); + + var noodleGradient = graphEditor.GetNoodleGradient(output, input); + var noodleThickness = graphEditor.GetNoodleThickness(output, input); + var noodlePath = graphEditor.GetNoodlePath(output, input); + var noodleStroke = graphEditor.GetNoodleStroke(output, input); + + // Error handling + if (input == null) + { + continue; //If a script has been updated and the port doesn't exist, it is removed and null is returned. If this happens, return. + } + + if (!input.IsConnectedTo(output)) + { + input.Connect(output); + } + + Rect toRect; + if (!_portConnectionPoints.TryGetValue(input, out toRect)) + { + continue; + } + + var reroutePoints = output.GetReroutePoints(k); + + gridPoints.Clear(); + gridPoints.Add(fromRect.center); + gridPoints.AddRange(reroutePoints); + gridPoints.Add(toRect.center); + DrawNoodle(noodleGradient, noodlePath, noodleStroke, noodleThickness, gridPoints); + + // Loop through reroute points again and draw the points + for (var i = 0; i < reroutePoints.Count; i++) { + var rerouteRef = new RerouteReference(output, k, i); + // Draw reroute point at position + var rect = new Rect(reroutePoints[i], new Vector2(12, 12)); + rect.position = new Vector2(rect.position.x - 6, rect.position.y - 6); + rect = GridToWindowRect(rect); + + // Draw selected reroute points with an outline + if (selectedReroutes.Contains(rerouteRef)) { + GUI.color = NodeEditorPreferences.GetSettings().highlightColor; + GUI.DrawTexture(rect, portStyle.normal.background); + } + + GUI.color = portColor; + GUI.DrawTexture(rect, portStyle.active.background); + if (rect.Overlaps(selectionBox)) + { + selection.Add(rerouteRef); + } + + if (rect.Contains(mousePos)) + { + hoveredReroute = rerouteRef; + } + } + } + } + } + GUI.color = col; + if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) + { + selectedReroutes = selection; + } + } + + private void DrawNodes() { + var e = Event.current; + if (e.type == EventType.Layout) { + selectionCache = new List(Selection.objects); + } + + System.Reflection.MethodInfo onValidate = null; + if (Selection.activeObject != null && Selection.activeObject is XNode.Node) { + onValidate = Selection.activeObject.GetType().GetMethod("OnValidate"); + if (onValidate != null) + { + EditorGUI.BeginChangeCheck(); + } + } + + BeginZoomed(position, zoom, topPadding); + + var mousePos = Event.current.mousePosition; + + if (e.type != EventType.Layout) { + hoveredNode = null; + hoveredPort = null; + } + + var preSelection = preBoxSelection != null ? new List(preBoxSelection) : new List(); + + // Selection box stuff + var boxStartPos = GridToWindowPositionNoClipped(dragBoxStart); + var boxSize = mousePos - boxStartPos; + if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); } + if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); } + var selectionBox = new Rect(boxStartPos, boxSize); + + //Save guiColor so we can revert it + var guiColor = GUI.color; + + var removeEntries = new List(); + + if (e.type == EventType.Layout) + { + culledNodes = new List(); + } + + for (var n = 0; n < graph.nodes.Count; n++) { + // Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable. + if (graph.nodes[n] == null) + { + continue; + } + + if (n >= graph.nodes.Count) + { + return; + } + + var node = graph.nodes[n]; + + // Culling + if (e.type == EventType.Layout) { + // Cull unselected nodes outside view + if (!Selection.Contains(node) && ShouldBeCulled(node)) { + culledNodes.Add(node); + continue; + } + } else if (culledNodes.Contains(node)) + { + continue; + } + + if (e.type == EventType.Repaint) { + removeEntries.Clear(); + foreach (var kvp in _portConnectionPoints) + { + if (kvp.Key.node == node) + { + removeEntries.Add(kvp.Key); + } + } + + foreach (var k in removeEntries) + { + _portConnectionPoints.Remove(k); + } + } + + var nodeEditor = NodeEditor.GetEditor(node, this); + + NodeEditor.portPositions.Clear(); + + // Set default label width. This is potentially overridden in OnBodyGUI + EditorGUIUtility.labelWidth = 84; + + //Get node position + var nodePos = GridToWindowPositionNoClipped(node.position); + + GUILayout.BeginArea(new Rect(nodePos, new Vector2(nodeEditor.GetWidth(), 4000))); + + var selected = selectionCache.Contains(graph.nodes[n]); + + if (selected) { + var style = new GUIStyle(nodeEditor.GetBodyStyle()); + var highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle()); + highlightStyle.padding = style.padding; + style.padding = new RectOffset(); + GUI.color = nodeEditor.GetTint(); + GUILayout.BeginVertical(style); + GUI.color = NodeEditorPreferences.GetSettings().highlightColor; + GUILayout.BeginVertical(new GUIStyle(highlightStyle)); + } else { + var style = new GUIStyle(nodeEditor.GetBodyStyle()); + GUI.color = nodeEditor.GetTint(); + GUILayout.BeginVertical(style); + } + + GUI.color = guiColor; + EditorGUI.BeginChangeCheck(); + + //Draw node contents + nodeEditor.OnHeaderGUI(); + nodeEditor.OnBodyGUI(); + + //If user changed a value, notify other scripts through onUpdateNode + if (EditorGUI.EndChangeCheck()) { + if (NodeEditor.onUpdateNode != null) + { + NodeEditor.onUpdateNode(node); + } + + EditorUtility.SetDirty(node); + nodeEditor.serializedObject.ApplyModifiedProperties(); + } + + GUILayout.EndVertical(); + + //Cache data about the node for next frame + if (e.type == EventType.Repaint) { + var size = GUILayoutUtility.GetLastRect().size; + if (nodeSizes.ContainsKey(node)) + { + nodeSizes[node] = size; + } + else + { + nodeSizes.Add(node, size); + } + + foreach (var kvp in NodeEditor.portPositions) { + var portHandlePos = kvp.Value; + portHandlePos += node.position; + var rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16); + portConnectionPoints[kvp.Key] = rect; + } + } + + if (selected) + { + GUILayout.EndVertical(); + } + + if (e.type != EventType.Layout) { + //Check if we are hovering this node + var nodeSize = GUILayoutUtility.GetLastRect().size; + var windowRect = new Rect(nodePos, nodeSize); + if (windowRect.Contains(mousePos)) + { + hoveredNode = node; + } + + //If dragging a selection box, add nodes inside to selection + if (currentActivity == NodeActivity.DragGrid) { + if (windowRect.Overlaps(selectionBox)) + { + preSelection.Add(node); + } + } + + //Check if we are hovering any of this nodes ports + //Check input ports + foreach (var input in node.Inputs) { + //Check if port rect is available + if (!portConnectionPoints.ContainsKey(input)) + { + continue; + } + + var r = GridToWindowRectNoClipped(portConnectionPoints[input]); + if (r.Contains(mousePos)) + { + hoveredPort = input; + } + } + //Check all output ports + foreach (var output in node.Outputs) { + //Check if port rect is available + if (!portConnectionPoints.ContainsKey(output)) + { + continue; + } + + var r = GridToWindowRectNoClipped(portConnectionPoints[output]); + if (r.Contains(mousePos)) + { + hoveredPort = output; + } + } + } + + GUILayout.EndArea(); + } + + if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) + { + Selection.objects = preSelection.ToArray(); + } + + EndZoomed(position, zoom, topPadding); + + //If a change in is detected in the selected node, call OnValidate method. + //This is done through reflection because OnValidate is only relevant in editor, + //and thus, the code should not be included in build. + if (onValidate != null && EditorGUI.EndChangeCheck()) + { + onValidate.Invoke(Selection.activeObject, null); + } + } + + private bool ShouldBeCulled(XNode.Node node) { + + var nodePos = GridToWindowPositionNoClipped(node.position); + if (nodePos.x / _zoom > position.width) + { + return true; // Right + } + else if (nodePos.y / _zoom > position.height) + { + return true; // Bottom + } + else if (nodeSizes.ContainsKey(node)) { + var size = nodeSizes[node]; + if (nodePos.x + size.x < 0) + { + return true; // Left + } + else if (nodePos.y + size.y < 0) + { + return true; // Top + } + } + return false; + } + + private void DrawTooltip() { + if (!NodeEditorPreferences.GetSettings().portTooltips || graphEditor == null) + { + return; + } + + string tooltip = null; + if (hoveredPort != null) { + tooltip = graphEditor.GetPortTooltip(hoveredPort); + } else if (hoveredNode != null && IsHoveringNode && IsHoveringTitle(hoveredNode)) { + tooltip = NodeEditor.GetEditor(hoveredNode, this).GetHeaderTooltip(); + } + if (string.IsNullOrEmpty(tooltip)) + { + return; + } + + var content = new GUIContent(tooltip); + var size = NodeEditorResources.styles.tooltip.CalcSize(content); + size.x += 8; + var rect = new Rect(Event.current.mousePosition - (size), size); + EditorGUI.LabelField(rect, content, NodeEditorResources.styles.tooltip); + Repaint(); + } + } +} diff --git a/Scripts/Editor/NodeEditorGUI.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUI.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorGUI.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUI.cs.meta diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUILayout.cs similarity index 68% rename from Scripts/Editor/NodeEditorGUILayout.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUILayout.cs index a0e3358..8bdf080 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUILayout.cs @@ -21,9 +21,13 @@ namespace XNodeEditor { /// Make a field for a serialized property. Automatically displays relevant node port. public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true, params GUILayoutOption[] options) { - if (property == null) throw new NullReferenceException(); - XNode.Node node = property.serializedObject.targetObject as XNode.Node; - XNode.NodePort port = node.GetPort(property.name); + if (property == null) + { + throw new NullReferenceException(); + } + + var node = property.serializedObject.targetObject as XNode.Node; + var port = node.GetPort(property.name); PropertyField(property, label, port, includeChildren); } @@ -34,61 +38,83 @@ namespace XNodeEditor { /// Make a field for a serialized property. Manual node port override. public static void PropertyField(SerializedProperty property, GUIContent label, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options) { - if (property == null) throw new NullReferenceException(); + if (property == null) + { + throw new NullReferenceException(); + } // If property is not a port, display a regular property field - if (port == null) EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); + if (port == null) + { + EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); + } else { - Rect rect = new Rect(); + var rect = new Rect(); - List propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name); + var propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name); // If property is an input, display a regular property field and put a port handle on the left side if (port.direction == XNode.NodePort.IO.Input) { // Get data from [Input] attribute - XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; + var showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.InputAttribute inputAttribute; - bool dynamicPortList = false; + var dynamicPortList = false; if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute)) { dynamicPortList = inputAttribute.dynamicPortList; showBacking = inputAttribute.backingValue; } - bool usePropertyAttributes = dynamicPortList || - showBacking == XNode.Node.ShowBackingValue.Never || - (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); + var usePropertyAttributes = dynamicPortList || + showBacking == XNode.Node.ShowBackingValue.Never || + (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); float spacePadding = 0; string tooltip = null; foreach (var attr in propertyAttributes) { if (attr is SpaceAttribute) { - if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height); - else spacePadding += (attr as SpaceAttribute).height; + if (usePropertyAttributes) + { + GUILayout.Space((attr as SpaceAttribute).height); + } + else + { + spacePadding += (attr as SpaceAttribute).height; + } } else if (attr is HeaderAttribute) { if (usePropertyAttributes) { //GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs - Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it. + var position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it. position.yMin += EditorGUIUtility.singleLineHeight * 0.5f; position = EditorGUI.IndentedRect(position); GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel); - } else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f; + } else + { + spacePadding += EditorGUIUtility.singleLineHeight * 1.5f; + } } else if (attr is TooltipAttribute) { tooltip = (attr as TooltipAttribute).tooltip; } } if (dynamicPortList) { - Type type = GetType(property); - XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; + var type = GetType(property); + var connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType); return; } switch (showBacking) { case XNode.Node.ShowBackingValue.Unconnected: // Display a label if port is connected - if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip)); + if (port.IsConnected) + { + EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip)); + } // Display an editable property field if port is not connected - else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); + else + { + EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); + } + break; case XNode.Node.ShowBackingValue.Never: // Display a label @@ -106,49 +132,65 @@ namespace XNodeEditor { // If property is an output, display a text label and put a port handle on the right side } else if (port.direction == XNode.NodePort.IO.Output) { // Get data from [Output] attribute - XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; + var showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.OutputAttribute outputAttribute; - bool dynamicPortList = false; + var dynamicPortList = false; if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute)) { dynamicPortList = outputAttribute.dynamicPortList; showBacking = outputAttribute.backingValue; } - bool usePropertyAttributes = dynamicPortList || - showBacking == XNode.Node.ShowBackingValue.Never || - (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); + var usePropertyAttributes = dynamicPortList || + showBacking == XNode.Node.ShowBackingValue.Never || + (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); float spacePadding = 0; string tooltip = null; foreach (var attr in propertyAttributes) { if (attr is SpaceAttribute) { - if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height); - else spacePadding += (attr as SpaceAttribute).height; + if (usePropertyAttributes) + { + GUILayout.Space((attr as SpaceAttribute).height); + } + else + { + spacePadding += (attr as SpaceAttribute).height; + } } else if (attr is HeaderAttribute) { if (usePropertyAttributes) { //GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs - Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it. + var position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it. position.yMin += EditorGUIUtility.singleLineHeight * 0.5f; position = EditorGUI.IndentedRect(position); GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel); - } else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f; + } else + { + spacePadding += EditorGUIUtility.singleLineHeight * 1.5f; + } } else if (attr is TooltipAttribute) { tooltip = (attr as TooltipAttribute).tooltip; } } if (dynamicPortList) { - Type type = GetType(property); - XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; + var type = GetType(property); + var connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType); return; } switch (showBacking) { case XNode.Node.ShowBackingValue.Unconnected: // Display a label if port is connected - if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30)); + if (port.IsConnected) + { + EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30)); + } // Display an editable property field if port is not connected - else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); + else + { + EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); + } + break; case XNode.Node.ShowBackingValue.Never: // Display a label @@ -167,20 +209,20 @@ namespace XNodeEditor { rect.size = new Vector2(16, 16); - Color backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port); - Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); - GUIStyle portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(port); + var backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port); + var col = NodeEditorWindow.current.graphEditor.GetPortColor(port); + var portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(port); DrawPortHandle(rect, backgroundColor, col, portStyle.normal.background, portStyle.active.background); // Register the handle position - Vector2 portPos = rect.center; + var portPos = rect.center; NodeEditor.portPositions[port] = portPos; } } private static System.Type GetType(SerializedProperty property) { - System.Type parentType = property.serializedObject.targetObject.GetType(); - System.Reflection.FieldInfo fi = parentType.GetFieldInfo(property.name); + var parentType = property.serializedObject.targetObject.GetType(); + var fi = parentType.GetFieldInfo(property.name); return fi.FieldType; } @@ -191,17 +233,25 @@ namespace XNodeEditor { /// Make a simple port field. public static void PortField(GUIContent label, XNode.NodePort port, params GUILayoutOption[] options) { - if (port == null) return; - if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) }; + if (port == null) + { + return; + } + + if (options == null) + { + options = new GUILayoutOption[] { GUILayout.MinWidth(30) }; + } + Vector2 position = Vector3.zero; - GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName)); + var content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName)); // If property is an input, display a regular property field and put a port handle on the left side if (port.direction == XNode.NodePort.IO.Input) { // Display a label EditorGUILayout.LabelField(content, options); - Rect rect = GUILayoutUtility.GetLastRect(); + var rect = GUILayoutUtility.GetLastRect(); float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left; position = rect.position - new Vector2(16 + paddingLeft, 0); } @@ -210,7 +260,7 @@ namespace XNodeEditor { // Display a label EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options); - Rect rect = GUILayoutUtility.GetLastRect(); + var rect = GUILayoutUtility.GetLastRect(); rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right; position = rect.position + new Vector2(rect.width, 0); } @@ -219,25 +269,32 @@ namespace XNodeEditor { /// Make a simple port field. public static void PortField(Vector2 position, XNode.NodePort port) { - if (port == null) return; + if (port == null) + { + return; + } - Rect rect = new Rect(position, new Vector2(16, 16)); + var rect = new Rect(position, new Vector2(16, 16)); - Color backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port); - Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); - GUIStyle portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(port); + var backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port); + var col = NodeEditorWindow.current.graphEditor.GetPortColor(port); + var portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(port); DrawPortHandle(rect, backgroundColor, col, portStyle.normal.background, portStyle.active.background); // Register the handle position - Vector2 portPos = rect.center; + var portPos = rect.center; NodeEditor.portPositions[port] = portPos; } /// Add a port field to previous layout element. public static void AddPortField(XNode.NodePort port) { - if (port == null) return; - Rect rect = new Rect(); + if (port == null) + { + return; + } + + var rect = new Rect(); // If property is an input, display a regular property field and put a port handle on the left side if (port.direction == XNode.NodePort.IO.Input) { @@ -253,14 +310,14 @@ namespace XNodeEditor { rect.size = new Vector2(16, 16); - Color backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port); - Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); - GUIStyle portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(port); + var backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port); + var col = NodeEditorWindow.current.graphEditor.GetPortColor(port); + var portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(port); DrawPortHandle(rect, backgroundColor, col, portStyle.normal.background, portStyle.active.background); // Register the handle position - Vector2 portPos = rect.center; + var portPos = rect.center; NodeEditor.portPositions[port] = portPos; } @@ -281,7 +338,7 @@ namespace XNodeEditor { /// texture for border of the dot port /// texture for the dot port public static void DrawPortHandle(Rect rect, Color backgroundColor, Color typeColor, Texture2D border, Texture2D dot) { - Color col = GUI.color; + var col = GUI.color; GUI.color = backgroundColor; GUI.DrawTexture(rect, border); GUI.color = typeColor; @@ -304,12 +361,19 @@ namespace XNodeEditor { /// Is this port part of a DynamicPortList? public static bool IsDynamicPortListPort(XNode.NodePort port) { - string[] parts = port.fieldName.Split(' '); - if (parts.Length != 2) return false; + var parts = port.fieldName.Split(' '); + if (parts.Length != 2) + { + return false; + } + Dictionary cache; if (reorderableListCache.TryGetValue(port.node, out cache)) { ReorderableList list; - if (cache.TryGetValue(parts[0], out list)) return true; + if (cache.TryGetValue(parts[0], out list)) + { + return true; + } } return false; } @@ -321,33 +385,42 @@ namespace XNodeEditor { /// Connection type of added dynamic ports /// Called on the list on creation. Use this if you want to customize the created ReorderableList public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action onCreation = null) { - XNode.Node node = serializedObject.targetObject as XNode.Node; + var node = serializedObject.targetObject as XNode.Node; var indexedPorts = node.DynamicPorts.Select(x => { - string[] split = x.fieldName.Split(' '); + var split = x.fieldName.Split(' '); if (split != null && split.Length == 2 && split[0] == fieldName) { - int i = -1; + var i = -1; if (int.TryParse(split[1], out i)) { return new { index = i, port = x }; } } return new { index = -1, port = (XNode.NodePort)null }; }).Where(x => x.port != null); - List dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList(); + var dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList(); node.UpdatePorts(); ReorderableList list = null; Dictionary rlc; if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) { - if (!rlc.TryGetValue(fieldName, out list)) list = null; + if (!rlc.TryGetValue(fieldName, out list)) + { + list = null; + } } // If a ReorderableList isn't cached for this array, do so. if (list == null) { - SerializedProperty arrayData = serializedObject.FindProperty(fieldName); + var arrayData = serializedObject.FindProperty(fieldName); list = CreateReorderableList(fieldName, dynamicPorts, arrayData, type, serializedObject, io, connectionType, typeConstraint, onCreation); - if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); - else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); + if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) + { + rlc.Add(fieldName, list); + } + else + { + reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); + } } list.list = dynamicPorts; list.DoLayoutList(); @@ -355,34 +428,45 @@ namespace XNodeEditor { } private static ReorderableList CreateReorderableList(string fieldName, List dynamicPorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action onCreation) { - bool hasArrayData = arrayData != null && arrayData.isArray; - XNode.Node node = serializedObject.targetObject as XNode.Node; - ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true); - string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName); + var hasArrayData = arrayData != null && arrayData.isArray; + var node = serializedObject.targetObject as XNode.Node; + var list = new ReorderableList(dynamicPorts, null, true, true, true, true); + var label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName); list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { - XNode.NodePort port = node.GetPort(fieldName + " " + index); + var port = node.GetPort(fieldName + " " + index); if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) { if (arrayData.arraySize <= index) { EditorGUI.LabelField(rect, "Array[" + index + "] data out of range"); return; } - SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); + var itemData = arrayData.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, itemData, true); - } else EditorGUI.LabelField(rect, port != null ? port.fieldName : ""); + } else + { + EditorGUI.LabelField(rect, port != null ? port.fieldName : ""); + } + if (port != null) { - Vector2 pos = rect.position + (port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); + var pos = rect.position + (port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); NodeEditorGUILayout.PortField(pos, port); } }; list.elementHeightCallback = (int index) => { if (hasArrayData) { - if (arrayData.arraySize <= index) return EditorGUIUtility.singleLineHeight; - SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); + if (arrayData.arraySize <= index) + { + return EditorGUIUtility.singleLineHeight; + } + + var itemData = arrayData.GetArrayElementAtIndex(index); return EditorGUI.GetPropertyHeight(itemData); - } else return EditorGUIUtility.singleLineHeight; + } else + { + return EditorGUIUtility.singleLineHeight; + } }; list.drawHeaderCallback = (Rect rect) => { @@ -395,15 +479,15 @@ namespace XNodeEditor { list.onReorderCallback = (ReorderableList rl) => { serializedObject.Update(); - bool hasRect = false; - bool hasNewRect = false; - Rect rect = Rect.zero; - Rect newRect = Rect.zero; + var hasRect = false; + var hasNewRect = false; + var rect = Rect.zero; + var newRect = Rect.zero; // Move up if (rl.index > reorderableListIndex) { - for (int i = reorderableListIndex; i < rl.index; ++i) { - XNode.NodePort port = node.GetPort(fieldName + " " + i); - XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i + 1)); + for (var i = reorderableListIndex; i < rl.index; ++i) { + var port = node.GetPort(fieldName + " " + i); + var nextPort = node.GetPort(fieldName + " " + (i + 1)); port.SwapConnections(nextPort); // Swap cached positions to mitigate twitching @@ -415,9 +499,9 @@ namespace XNodeEditor { } // Move down else { - for (int i = reorderableListIndex; i > rl.index; --i) { - XNode.NodePort port = node.GetPort(fieldName + " " + i); - XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i - 1)); + for (var i = reorderableListIndex; i > rl.index; --i) { + var port = node.GetPort(fieldName + " " + i); + var nextPort = node.GetPort(fieldName + " " + (i - 1)); port.SwapConnections(nextPort); // Swap cached positions to mitigate twitching @@ -445,12 +529,22 @@ namespace XNodeEditor { list.onAddCallback = (ReorderableList rl) => { // Add dynamic port postfixed with an index number - string newName = fieldName + " 0"; - int i = 0; - while (node.HasPort(newName)) newName = fieldName + " " + (++i); + var newName = fieldName + " 0"; + var i = 0; + while (node.HasPort(newName)) + { + newName = fieldName + " " + (++i); + } + + if (io == XNode.NodePort.IO.Output) + { + node.AddDynamicOutput(type, connectionType, XNode.Node.TypeConstraint.None, newName); + } + else + { + node.AddDynamicInput(type, connectionType, typeConstraint, newName); + } - if (io == XNode.NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, XNode.Node.TypeConstraint.None, newName); - else node.AddDynamicInput(type, connectionType, typeConstraint, newName); serializedObject.Update(); EditorUtility.SetDirty(node); if (hasArrayData) { @@ -462,9 +556,9 @@ namespace XNodeEditor { (ReorderableList rl) => { var indexedPorts = node.DynamicPorts.Select(x => { - string[] split = x.fieldName.Split(' '); + var split = x.fieldName.Split(' '); if (split != null && split.Length == 2 && split[0] == fieldName) { - int i = -1; + var i = -1; if (int.TryParse(split[1], out i)) { return new { index = i, port = x }; } @@ -473,7 +567,7 @@ namespace XNodeEditor { }).Where(x => x.port != null); dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList(); - int index = rl.index; + var index = rl.index; if (dynamicPorts[index] == null) { Debug.LogWarning("No port found at index " + index + " - Skipped"); @@ -484,9 +578,9 @@ namespace XNodeEditor { // Clear the removed ports connections dynamicPorts[index].ClearConnections(); // Move following connections one step up to replace the missing connection - for (int k = index + 1; k < dynamicPorts.Count(); k++) { - for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++) { - XNode.NodePort other = dynamicPorts[k].GetConnection(j); + for (var k = index + 1; k < dynamicPorts.Count(); k++) { + for (var j = 0; j < dynamicPorts[k].ConnectionCount; j++) { + var other = dynamicPorts[k].GetConnection(j); dynamicPorts[k].Disconnect(other); dynamicPorts[k - 1].Connect(other); } @@ -517,14 +611,25 @@ namespace XNodeEditor { }; if (hasArrayData) { - int dynamicPortCount = dynamicPorts.Count; + var dynamicPortCount = dynamicPorts.Count; while (dynamicPortCount < arrayData.arraySize) { // Add dynamic port postfixed with an index number - string newName = arrayData.name + " 0"; - int i = 0; - while (node.HasPort(newName)) newName = arrayData.name + " " + (++i); - if (io == XNode.NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, typeConstraint, newName); - else node.AddDynamicInput(type, connectionType, typeConstraint, newName); + var newName = arrayData.name + " 0"; + var i = 0; + while (node.HasPort(newName)) + { + newName = arrayData.name + " " + (++i); + } + + if (io == XNode.NodePort.IO.Output) + { + node.AddDynamicOutput(type, connectionType, typeConstraint, newName); + } + else + { + node.AddDynamicInput(type, connectionType, typeConstraint, newName); + } + EditorUtility.SetDirty(node); dynamicPortCount++; } @@ -534,8 +639,12 @@ namespace XNodeEditor { serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } - if (onCreation != null) onCreation(list); + if (onCreation != null) + { + onCreation(list); + } + return list; } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/NodeEditorGUILayout.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUILayout.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorGUILayout.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorGUILayout.cs.meta diff --git a/Scripts/Editor/NodeEditorPreferences.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorPreferences.cs similarity index 79% rename from Scripts/Editor/NodeEditorPreferences.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorPreferences.cs index 73dfe96..1d4a16b 100644 --- a/Scripts/Editor/NodeEditorPreferences.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorPreferences.cs @@ -51,14 +51,22 @@ namespace XNodeEditor { private Texture2D _gridTexture; public Texture2D gridTexture { get { - if (_gridTexture == null) _gridTexture = NodeEditorResources.GenerateGridTexture(gridLineColor, gridBgColor); + if (_gridTexture == null) + { + _gridTexture = NodeEditorResources.GenerateGridTexture(gridLineColor, gridBgColor); + } + return _gridTexture; } } private Texture2D _crossTexture; public Texture2D crossTexture { get { - if (_crossTexture == null) _crossTexture = NodeEditorResources.GenerateCrossTexture(gridLineColor); + if (_crossTexture == null) + { + _crossTexture = NodeEditorResources.GenerateCrossTexture(gridLineColor); + } + return _crossTexture; } } @@ -66,8 +74,8 @@ namespace XNodeEditor { public void OnAfterDeserialize() { // Deserialize typeColorsData typeColors = new Dictionary(); - string[] data = typeColorsData.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < data.Length; i += 2) { + var data = typeColorsData.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + for (var i = 0; i < data.Length; i += 2) { Color col; if (ColorUtility.TryParseHtmlString("#" + data[i + 1], out col)) { typeColors.Add(data[i], col); @@ -86,24 +94,34 @@ namespace XNodeEditor { /// Get settings of current active editor public static Settings GetSettings() { - if (XNodeEditor.NodeEditorWindow.current == null) return new Settings(); + if (XNodeEditor.NodeEditorWindow.current == null) + { + return new Settings(); + } if (lastEditor != XNodeEditor.NodeEditorWindow.current.graphEditor) { - object[] attribs = XNodeEditor.NodeEditorWindow.current.graphEditor.GetType().GetCustomAttributes(typeof(XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute), true); + var attribs = XNodeEditor.NodeEditorWindow.current.graphEditor.GetType().GetCustomAttributes(typeof(XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute), true); if (attribs.Length == 1) { - XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute attrib = attribs[0] as XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute; + var attrib = attribs[0] as XNodeEditor.NodeGraphEditor.CustomNodeGraphEditorAttribute; lastEditor = XNodeEditor.NodeEditorWindow.current.graphEditor; lastKey = attrib.editorPrefsKey; - } else return null; + } else + { + return null; + } } - if (!settings.ContainsKey(lastKey)) VerifyLoaded(); + if (!settings.ContainsKey(lastKey)) + { + VerifyLoaded(); + } + return settings[lastKey]; } #if UNITY_2019_1_OR_NEWER [SettingsProvider] public static SettingsProvider CreateXNodeSettingsProvider() { - SettingsProvider provider = new SettingsProvider("Preferences/Node Editor", SettingsScope.User) { + var provider = new SettingsProvider("Preferences/Node Editor", SettingsScope.User) { guiHandler = (searchContext) => { XNodeEditor.NodeEditorPreferences.PreferencesGUI(); }, keywords = new HashSet(new [] { "xNode", "node", "editor", "graph", "connections", "noodles", "ports" }) }; @@ -116,9 +134,13 @@ namespace XNodeEditor { #endif private static void PreferencesGUI() { VerifyLoaded(); - Settings settings = NodeEditorPreferences.settings[lastKey]; + var settings = NodeEditorPreferences.settings[lastKey]; + + if (GUILayout.Button(new GUIContent("Documentation", "https://github.com/Siccity/xNode/wiki"), GUILayout.Width(100))) + { + Application.OpenURL("https://github.com/Siccity/xNode/wiki"); + } - if (GUILayout.Button(new GUIContent("Documentation", "https://github.com/Siccity/xNode/wiki"), GUILayout.Width(100))) Application.OpenURL("https://github.com/Siccity/xNode/wiki"); EditorGUILayout.Space(); NodeSettingsGUI(lastKey, settings); @@ -155,7 +177,11 @@ namespace XNodeEditor { EditorGUILayout.LabelField("System", EditorStyles.boldLabel); settings.autoSave = EditorGUILayout.Toggle(new GUIContent("Autosave", "Disable for better editor performance"), settings.autoSave); settings.openOnCreate = EditorGUILayout.Toggle(new GUIContent("Open Editor on Create", "Disable to prevent openening the editor when creating a new graph"), settings.openOnCreate); - if (GUI.changed) SavePrefs(key, settings); + if (GUI.changed) + { + SavePrefs(key, settings); + } + EditorGUILayout.Space(); } @@ -188,16 +214,23 @@ namespace XNodeEditor { //Display type colors. Save them if they are edited by the user foreach (var type in typeColorKeys) { - string typeColorKey = NodeEditorUtilities.PrettyName(type); - Color col = typeColors[type]; + var typeColorKey = NodeEditorUtilities.PrettyName(type); + var col = typeColors[type]; EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal(); col = EditorGUILayout.ColorField(typeColorKey, col); EditorGUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { typeColors[type] = col; - if (settings.typeColors.ContainsKey(typeColorKey)) settings.typeColors[typeColorKey] = col; - else settings.typeColors.Add(typeColorKey, col); + if (settings.typeColors.ContainsKey(typeColorKey)) + { + settings.typeColors[typeColorKey] = col; + } + else + { + settings.typeColors.Add(typeColorKey, col); + } + SavePrefs(key, settings); NodeEditorWindow.RepaintAll(); } @@ -208,16 +241,30 @@ namespace XNodeEditor { private static Settings LoadPrefs() { // Create settings if it doesn't exist if (!EditorPrefs.HasKey(lastKey)) { - if (lastEditor != null) EditorPrefs.SetString(lastKey, JsonUtility.ToJson(lastEditor.GetDefaultPreferences())); - else EditorPrefs.SetString(lastKey, JsonUtility.ToJson(new Settings())); + if (lastEditor != null) + { + EditorPrefs.SetString(lastKey, JsonUtility.ToJson(lastEditor.GetDefaultPreferences())); + } + else + { + EditorPrefs.SetString(lastKey, JsonUtility.ToJson(new Settings())); + } } return JsonUtility.FromJson(EditorPrefs.GetString(lastKey)); } /// Delete all prefs public static void ResetPrefs() { - if (EditorPrefs.HasKey(lastKey)) EditorPrefs.DeleteKey(lastKey); - if (settings.ContainsKey(lastKey)) settings.Remove(lastKey); + if (EditorPrefs.HasKey(lastKey)) + { + EditorPrefs.DeleteKey(lastKey); + } + + if (settings.ContainsKey(lastKey)) + { + settings.Remove(lastKey); + } + typeColors = new Dictionary(); VerifyLoaded(); NodeEditorWindow.RepaintAll(); @@ -230,20 +277,30 @@ namespace XNodeEditor { /// Check if we have loaded settings for given key. If not, load them private static void VerifyLoaded() { - if (!settings.ContainsKey(lastKey)) settings.Add(lastKey, LoadPrefs()); + if (!settings.ContainsKey(lastKey)) + { + settings.Add(lastKey, LoadPrefs()); + } } /// Return color based on type public static Color GetTypeColor(System.Type type) { VerifyLoaded(); - if (type == null) return Color.gray; + if (type == null) + { + return Color.gray; + } + Color col; if (!typeColors.TryGetValue(type, out col)) { - string typeName = type.PrettyName(); - if (settings[lastKey].typeColors.ContainsKey(typeName)) typeColors.Add(type, settings[lastKey].typeColors[typeName]); + var typeName = type.PrettyName(); + if (settings[lastKey].typeColors.ContainsKey(typeName)) + { + typeColors.Add(type, settings[lastKey].typeColors[typeName]); + } else { #if UNITY_5_4_OR_NEWER - UnityEngine.Random.State oldState = UnityEngine.Random.state; + var oldState = UnityEngine.Random.state; UnityEngine.Random.InitState(typeName.GetHashCode()); #else int oldSeed = UnityEngine.Random.seed; @@ -261,4 +318,4 @@ namespace XNodeEditor { return col; } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/NodeEditorPreferences.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorPreferences.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorPreferences.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorPreferences.cs.meta diff --git a/Scripts/Editor/NodeEditorReflection.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorReflection.cs similarity index 78% rename from Scripts/Editor/NodeEditorReflection.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorReflection.cs index d401139..7866fbb 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorReflection.cs @@ -1,183 +1,198 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using UnityEditor; -using UnityEngine; -#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU -using GenericMenu = XNodeEditor.AdvancedGenericMenu; -#endif - -namespace XNodeEditor { - /// Contains reflection-related extensions built for xNode - public static class NodeEditorReflection { - [NonSerialized] private static Dictionary nodeTint; - [NonSerialized] private static Dictionary nodeWidth; - /// All available node types - public static Type[] nodeTypes { get { return _nodeTypes != null ? _nodeTypes : _nodeTypes = GetNodeTypes(); } } - - [NonSerialized] private static Type[] _nodeTypes = null; - - /// Return a delegate used to determine whether window is docked or not. It is faster to cache this delegate than run the reflection required each time. - public static Func GetIsDockedDelegate(this EditorWindow window) { - BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; - MethodInfo isDockedMethod = typeof(EditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true); - return (Func) Delegate.CreateDelegate(typeof(Func), window, isDockedMethod); - } - - public static Type[] GetNodeTypes() { - //Get all classes deriving from Node via reflection - return GetDerivedTypes(typeof(XNode.Node)); - } - - /// Custom node tint colors defined with [NodeColor(r, g, b)] - public static bool TryGetAttributeTint(this Type nodeType, out Color tint) { - if (nodeTint == null) { - CacheAttributes(ref nodeTint, x => x.color); - } - return nodeTint.TryGetValue(nodeType, out tint); - } - - /// Get custom node widths defined with [NodeWidth(width)] - public static bool TryGetAttributeWidth(this Type nodeType, out int width) { - if (nodeWidth == null) { - CacheAttributes(ref nodeWidth, x => x.width); - } - return nodeWidth.TryGetValue(nodeType, out width); - } - - private static void CacheAttributes(ref Dictionary dict, Func getter) where A : Attribute { - dict = new Dictionary(); - for (int i = 0; i < nodeTypes.Length; i++) { - object[] attribs = nodeTypes[i].GetCustomAttributes(typeof(A), true); - if (attribs == null || attribs.Length == 0) continue; - A attrib = attribs[0] as A; - dict.Add(nodeTypes[i], getter(attrib)); - } - } - - /// Get FieldInfo of a field, including those that are private and/or inherited - public static FieldInfo GetFieldInfo(this Type type, string fieldName) { - // If we can't find field in the first run, it's probably a private field in a base class. - FieldInfo field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - // Search base classes for private fields only. Public fields are found above - while (field == null && (type = type.BaseType) != typeof(XNode.Node)) field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); - return field; - } - - /// Get all classes deriving from baseType via reflection - public static Type[] GetDerivedTypes(this Type baseType) { - List types = new List(); - System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); - foreach (Assembly assembly in assemblies) { - try { - types.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray()); - } catch (ReflectionTypeLoadException) { } - } - return types.ToArray(); - } - - /// Find methods marked with the [ContextMenu] attribute and add them to the context menu - public static void AddCustomContextMenuItems(this GenericMenu contextMenu, object obj) { - KeyValuePair[] items = GetContextMenuMethods(obj); - if (items.Length != 0) { - contextMenu.AddSeparator(""); - List invalidatedEntries = new List(); - foreach (KeyValuePair checkValidate in items) { - if (checkValidate.Key.validate && !(bool) checkValidate.Value.Invoke(obj, null)) { - invalidatedEntries.Add(checkValidate.Key.menuItem); - } - } - for (int i = 0; i < items.Length; i++) { - KeyValuePair kvp = items[i]; - if (invalidatedEntries.Contains(kvp.Key.menuItem)) { - contextMenu.AddDisabledItem(new GUIContent(kvp.Key.menuItem)); - } else { - contextMenu.AddItem(new GUIContent(kvp.Key.menuItem), false, () => kvp.Value.Invoke(obj, null)); - } - } - } - } - - /// Call OnValidate on target - public static void TriggerOnValidate(this UnityEngine.Object target) { - System.Reflection.MethodInfo onValidate = null; - if (target != null) { - onValidate = target.GetType().GetMethod("OnValidate", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - if (onValidate != null) onValidate.Invoke(target, null); - } - } - - public static KeyValuePair[] GetContextMenuMethods(object obj) { - Type type = obj.GetType(); - MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - List> kvp = new List>(); - for (int i = 0; i < methods.Length; i++) { - ContextMenu[] attribs = methods[i].GetCustomAttributes(typeof(ContextMenu), true).Select(x => x as ContextMenu).ToArray(); - if (attribs == null || attribs.Length == 0) continue; - if (methods[i].GetParameters().Length != 0) { - Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " has parameters and cannot be used for context menu commands."); - continue; - } - if (methods[i].IsStatic) { - Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " is static and cannot be used for context menu commands."); - continue; - } - - for (int k = 0; k < attribs.Length; k++) { - kvp.Add(new KeyValuePair(attribs[k], methods[i])); - } - } -#if UNITY_5_5_OR_NEWER - //Sort menu items - kvp.Sort((x, y) => x.Key.priority.CompareTo(y.Key.priority)); -#endif - return kvp.ToArray(); - } - - /// Very crude. Uses a lot of reflection. - public static void OpenPreferences() { - try { -#if UNITY_2018_3_OR_NEWER - SettingsService.OpenUserPreferences("Preferences/Node Editor"); -#else - //Open preferences window - Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.EditorWindow)); - Type type = assembly.GetType("UnityEditor.PreferencesWindow"); - type.GetMethod("ShowPreferencesWindow", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null); - - //Get the window - EditorWindow window = EditorWindow.GetWindow(type); - - //Make sure custom sections are added (because waiting for it to happen automatically is too slow) - FieldInfo refreshField = type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance); - if ((bool) refreshField.GetValue(window)) { - type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null); - refreshField.SetValue(window, false); - } - - //Get sections - FieldInfo sectionsField = type.GetField("m_Sections", BindingFlags.Instance | BindingFlags.NonPublic); - IList sections = sectionsField.GetValue(window) as IList; - - //Iterate through sections and check contents - Type sectionType = sectionsField.FieldType.GetGenericArguments() [0]; - FieldInfo sectionContentField = sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public); - for (int i = 0; i < sections.Count; i++) { - GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent; - if (sectionContent.text == "Node Editor") { - //Found contents - Set index - FieldInfo sectionIndexField = type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic); - sectionIndexField.SetValue(window, i); - return; - } - } -#endif - } catch (Exception e) { - Debug.LogError(e); - Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number."); - } - } - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; +#if UNITY_2019_1_OR_NEWER && USE_ADVANCED_GENERIC_MENU +using GenericMenu = XNodeEditor.AdvancedGenericMenu; +#endif + +namespace XNodeEditor { + /// Contains reflection-related extensions built for xNode + public static class NodeEditorReflection { + [NonSerialized] private static Dictionary nodeTint; + [NonSerialized] private static Dictionary nodeWidth; + /// All available node types + public static Type[] nodeTypes { get { return _nodeTypes != null ? _nodeTypes : _nodeTypes = GetNodeTypes(); } } + + [NonSerialized] private static Type[] _nodeTypes = null; + + /// Return a delegate used to determine whether window is docked or not. It is faster to cache this delegate than run the reflection required each time. + public static Func GetIsDockedDelegate(this EditorWindow window) { + var fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + var isDockedMethod = typeof(EditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true); + return (Func) Delegate.CreateDelegate(typeof(Func), window, isDockedMethod); + } + + public static Type[] GetNodeTypes() { + //Get all classes deriving from Node via reflection + return GetDerivedTypes(typeof(XNode.Node)); + } + + /// Custom node tint colors defined with [NodeColor(r, g, b)] + public static bool TryGetAttributeTint(this Type nodeType, out Color tint) { + if (nodeTint == null) { + CacheAttributes(ref nodeTint, x => x.color); + } + return nodeTint.TryGetValue(nodeType, out tint); + } + + /// Get custom node widths defined with [NodeWidth(width)] + public static bool TryGetAttributeWidth(this Type nodeType, out int width) { + if (nodeWidth == null) { + CacheAttributes(ref nodeWidth, x => x.width); + } + return nodeWidth.TryGetValue(nodeType, out width); + } + + private static void CacheAttributes(ref Dictionary dict, Func getter) where A : Attribute { + dict = new Dictionary(); + for (var i = 0; i < nodeTypes.Length; i++) { + var attribs = nodeTypes[i].GetCustomAttributes(typeof(A), true); + if (attribs == null || attribs.Length == 0) + { + continue; + } + + var attrib = attribs[0] as A; + dict.Add(nodeTypes[i], getter(attrib)); + } + } + + /// Get FieldInfo of a field, including those that are private and/or inherited + public static FieldInfo GetFieldInfo(this Type type, string fieldName) { + // If we can't find field in the first run, it's probably a private field in a base class. + var field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + // Search base classes for private fields only. Public fields are found above + while (field == null && (type = type.BaseType) != typeof(XNode.Node)) + { + field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); + } + + return field; + } + + /// Get all classes deriving from baseType via reflection + public static Type[] GetDerivedTypes(this Type baseType) { + var types = new List(); + var assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) { + try { + types.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray()); + } catch (ReflectionTypeLoadException) { } + } + return types.ToArray(); + } + + /// Find methods marked with the [ContextMenu] attribute and add them to the context menu + public static void AddCustomContextMenuItems(this GenericMenu contextMenu, object obj) { + var items = GetContextMenuMethods(obj); + if (items.Length != 0) { + contextMenu.AddSeparator(""); + var invalidatedEntries = new List(); + foreach (var checkValidate in items) { + if (checkValidate.Key.validate && !(bool) checkValidate.Value.Invoke(obj, null)) { + invalidatedEntries.Add(checkValidate.Key.menuItem); + } + } + for (var i = 0; i < items.Length; i++) { + var kvp = items[i]; + if (invalidatedEntries.Contains(kvp.Key.menuItem)) { + contextMenu.AddDisabledItem(new GUIContent(kvp.Key.menuItem)); + } else { + contextMenu.AddItem(new GUIContent(kvp.Key.menuItem), false, () => kvp.Value.Invoke(obj, null)); + } + } + } + } + + /// Call OnValidate on target + public static void TriggerOnValidate(this UnityEngine.Object target) { + System.Reflection.MethodInfo onValidate = null; + if (target != null) { + onValidate = target.GetType().GetMethod("OnValidate", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + if (onValidate != null) + { + onValidate.Invoke(target, null); + } + } + } + + public static KeyValuePair[] GetContextMenuMethods(object obj) { + var type = obj.GetType(); + var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + var kvp = new List>(); + for (var i = 0; i < methods.Length; i++) { + var attribs = methods[i].GetCustomAttributes(typeof(ContextMenu), true).Select(x => x as ContextMenu).ToArray(); + if (attribs == null || attribs.Length == 0) + { + continue; + } + + if (methods[i].GetParameters().Length != 0) { + Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " has parameters and cannot be used for context menu commands."); + continue; + } + if (methods[i].IsStatic) { + Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " is static and cannot be used for context menu commands."); + continue; + } + + for (var k = 0; k < attribs.Length; k++) { + kvp.Add(new KeyValuePair(attribs[k], methods[i])); + } + } +#if UNITY_5_5_OR_NEWER + //Sort menu items + kvp.Sort((x, y) => x.Key.priority.CompareTo(y.Key.priority)); +#endif + return kvp.ToArray(); + } + + /// Very crude. Uses a lot of reflection. + public static void OpenPreferences() { + try { +#if UNITY_2018_3_OR_NEWER + SettingsService.OpenUserPreferences("Preferences/Node Editor"); +#else + //Open preferences window + Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.EditorWindow)); + Type type = assembly.GetType("UnityEditor.PreferencesWindow"); + type.GetMethod("ShowPreferencesWindow", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null); + + //Get the window + EditorWindow window = EditorWindow.GetWindow(type); + + //Make sure custom sections are added (because waiting for it to happen automatically is too slow) + FieldInfo refreshField = type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance); + if ((bool) refreshField.GetValue(window)) { + type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null); + refreshField.SetValue(window, false); + } + + //Get sections + FieldInfo sectionsField = type.GetField("m_Sections", BindingFlags.Instance | BindingFlags.NonPublic); + IList sections = sectionsField.GetValue(window) as IList; + + //Iterate through sections and check contents + Type sectionType = sectionsField.FieldType.GetGenericArguments() [0]; + FieldInfo sectionContentField = sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public); + for (int i = 0; i < sections.Count; i++) { + GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent; + if (sectionContent.text == "Node Editor") { + //Found contents - Set index + FieldInfo sectionIndexField = type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic); + sectionIndexField.SetValue(window, i); + return; + } + } +#endif + } catch (Exception e) { + Debug.LogError(e); + Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number."); + } + } + } +} diff --git a/Scripts/Editor/NodeEditorReflection.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorReflection.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorReflection.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorReflection.cs.meta diff --git a/Scripts/Editor/NodeEditorResources.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorResources.cs similarity index 79% rename from Scripts/Editor/NodeEditorResources.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorResources.cs index 26a79ce..df92b87 100644 --- a/Scripts/Editor/NodeEditorResources.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorResources.cs @@ -1,95 +1,107 @@ -using UnityEditor; -using UnityEngine; - -namespace XNodeEditor { - public static class NodeEditorResources { - // Textures - public static Texture2D dot { get { return _dot != null ? _dot : _dot = Resources.Load("xnode_dot"); } } - private static Texture2D _dot; - public static Texture2D dotOuter { get { return _dotOuter != null ? _dotOuter : _dotOuter = Resources.Load("xnode_dot_outer"); } } - private static Texture2D _dotOuter; - public static Texture2D nodeBody { get { return _nodeBody != null ? _nodeBody : _nodeBody = Resources.Load("xnode_node"); } } - private static Texture2D _nodeBody; - public static Texture2D nodeHighlight { get { return _nodeHighlight != null ? _nodeHighlight : _nodeHighlight = Resources.Load("xnode_node_highlight"); } } - private static Texture2D _nodeHighlight; - - // Styles - public static Styles styles { get { return _styles != null ? _styles : _styles = new Styles(); } } - public static Styles _styles = null; - public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } } - public class Styles { - public GUIStyle inputPort, outputPort, nodeHeader, nodeBody, tooltip, nodeHighlight; - - public Styles() { - GUIStyle baseStyle = new GUIStyle("Label"); - baseStyle.fixedHeight = 18; - - inputPort = new GUIStyle(baseStyle); - inputPort.alignment = TextAnchor.UpperLeft; - inputPort.padding.left = 0; - inputPort.active.background = dot; - inputPort.normal.background = dotOuter; - - outputPort = new GUIStyle(baseStyle); - outputPort.alignment = TextAnchor.UpperRight; - outputPort.padding.right = 0; - outputPort.active.background = dot; - outputPort.normal.background = dotOuter; - - nodeHeader = new GUIStyle(); - nodeHeader.alignment = TextAnchor.MiddleCenter; - nodeHeader.fontStyle = FontStyle.Bold; - nodeHeader.normal.textColor = Color.white; - - nodeBody = new GUIStyle(); - nodeBody.normal.background = NodeEditorResources.nodeBody; - nodeBody.border = new RectOffset(32, 32, 32, 32); - nodeBody.padding = new RectOffset(16, 16, 4, 16); - - nodeHighlight = new GUIStyle(); - nodeHighlight.normal.background = NodeEditorResources.nodeHighlight; - nodeHighlight.border = new RectOffset(32, 32, 32, 32); - - tooltip = new GUIStyle("helpBox"); - tooltip.alignment = TextAnchor.MiddleCenter; - } - } - - public static Texture2D GenerateGridTexture(Color line, Color bg) { - Texture2D tex = new Texture2D(64, 64); - Color[] cols = new Color[64 * 64]; - for (int y = 0; y < 64; y++) { - for (int x = 0; x < 64; x++) { - Color col = bg; - if (y % 16 == 0 || x % 16 == 0) col = Color.Lerp(line, bg, 0.65f); - if (y == 63 || x == 63) col = Color.Lerp(line, bg, 0.35f); - cols[(y * 64) + x] = col; - } - } - tex.SetPixels(cols); - tex.wrapMode = TextureWrapMode.Repeat; - tex.filterMode = FilterMode.Bilinear; - tex.name = "Grid"; - tex.Apply(); - return tex; - } - - public static Texture2D GenerateCrossTexture(Color line) { - Texture2D tex = new Texture2D(64, 64); - Color[] cols = new Color[64 * 64]; - for (int y = 0; y < 64; y++) { - for (int x = 0; x < 64; x++) { - Color col = line; - if (y != 31 && x != 31) col.a = 0; - cols[(y * 64) + x] = col; - } - } - tex.SetPixels(cols); - tex.wrapMode = TextureWrapMode.Clamp; - tex.filterMode = FilterMode.Bilinear; - tex.name = "Grid"; - tex.Apply(); - return tex; - } - } -} \ No newline at end of file +using UnityEditor; +using UnityEngine; + +namespace XNodeEditor { + public static class NodeEditorResources { + // Textures + public static Texture2D dot { get { return _dot != null ? _dot : _dot = Resources.Load("xnode_dot"); } } + private static Texture2D _dot; + public static Texture2D dotOuter { get { return _dotOuter != null ? _dotOuter : _dotOuter = Resources.Load("xnode_dot_outer"); } } + private static Texture2D _dotOuter; + public static Texture2D nodeBody { get { return _nodeBody != null ? _nodeBody : _nodeBody = Resources.Load("xnode_node"); } } + private static Texture2D _nodeBody; + public static Texture2D nodeHighlight { get { return _nodeHighlight != null ? _nodeHighlight : _nodeHighlight = Resources.Load("xnode_node_highlight"); } } + private static Texture2D _nodeHighlight; + + // Styles + public static Styles styles { get { return _styles != null ? _styles : _styles = new Styles(); } } + public static Styles _styles = null; + public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } } + public class Styles { + public GUIStyle inputPort, outputPort, nodeHeader, nodeBody, tooltip, nodeHighlight; + + public Styles() { + var baseStyle = new GUIStyle("Label"); + baseStyle.fixedHeight = 18; + + inputPort = new GUIStyle(baseStyle); + inputPort.alignment = TextAnchor.UpperLeft; + inputPort.padding.left = 0; + inputPort.active.background = dot; + inputPort.normal.background = dotOuter; + + outputPort = new GUIStyle(baseStyle); + outputPort.alignment = TextAnchor.UpperRight; + outputPort.padding.right = 0; + outputPort.active.background = dot; + outputPort.normal.background = dotOuter; + + nodeHeader = new GUIStyle(); + nodeHeader.alignment = TextAnchor.MiddleCenter; + nodeHeader.fontStyle = FontStyle.Bold; + nodeHeader.normal.textColor = Color.white; + + nodeBody = new GUIStyle(); + nodeBody.normal.background = NodeEditorResources.nodeBody; + nodeBody.border = new RectOffset(32, 32, 32, 32); + nodeBody.padding = new RectOffset(16, 16, 4, 16); + + nodeHighlight = new GUIStyle(); + nodeHighlight.normal.background = NodeEditorResources.nodeHighlight; + nodeHighlight.border = new RectOffset(32, 32, 32, 32); + + tooltip = new GUIStyle("helpBox"); + tooltip.alignment = TextAnchor.MiddleCenter; + } + } + + public static Texture2D GenerateGridTexture(Color line, Color bg) { + var tex = new Texture2D(64, 64); + var cols = new Color[64 * 64]; + for (var y = 0; y < 64; y++) { + for (var x = 0; x < 64; x++) { + var col = bg; + if (y % 16 == 0 || x % 16 == 0) + { + col = Color.Lerp(line, bg, 0.65f); + } + + if (y == 63 || x == 63) + { + col = Color.Lerp(line, bg, 0.35f); + } + + cols[(y * 64) + x] = col; + } + } + tex.SetPixels(cols); + tex.wrapMode = TextureWrapMode.Repeat; + tex.filterMode = FilterMode.Bilinear; + tex.name = "Grid"; + tex.Apply(); + return tex; + } + + public static Texture2D GenerateCrossTexture(Color line) { + var tex = new Texture2D(64, 64); + var cols = new Color[64 * 64]; + for (var y = 0; y < 64; y++) { + for (var x = 0; x < 64; x++) { + var col = line; + if (y != 31 && x != 31) + { + col.a = 0; + } + + cols[(y * 64) + x] = col; + } + } + tex.SetPixels(cols); + tex.wrapMode = TextureWrapMode.Clamp; + tex.filterMode = FilterMode.Bilinear; + tex.name = "Grid"; + tex.Apply(); + return tex; + } + } +} diff --git a/Scripts/Editor/NodeEditorResources.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorResources.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorResources.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorResources.cs.meta diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorUtilities.cs similarity index 74% rename from Scripts/Editor/NodeEditorUtilities.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorUtilities.cs index 753973b..7df2d2d 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorUtilities.cs @@ -1,317 +1,372 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using UnityEditor; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace XNodeEditor { - /// A set of editor-only utilities and extensions for xNode - public static class NodeEditorUtilities { - - /// C#'s Script Icon [The one MonoBhevaiour Scripts have]. - private static Texture2D scriptIcon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D); - - /// Saves Attribute from Type+Field for faster lookup. Resets on recompiles. - private static Dictionary>> typeAttributes = new Dictionary>>(); - - /// Saves ordered PropertyAttribute from Type+Field for faster lookup. Resets on recompiles. - private static Dictionary>> typeOrderedPropertyAttributes = new Dictionary>>(); - - public static bool GetAttrib(Type classType, out T attribOut) where T : Attribute { - object[] attribs = classType.GetCustomAttributes(typeof(T), false); - return GetAttrib(attribs, out attribOut); - } - - public static bool GetAttrib(object[] attribs, out T attribOut) where T : Attribute { - for (int i = 0; i < attribs.Length; i++) { - if (attribs[i] is T) { - attribOut = attribs[i] as T; - return true; - } - } - attribOut = null; - return false; - } - - public static bool GetAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { - // If we can't find field in the first run, it's probably a private field in a base class. - FieldInfo field = classType.GetFieldInfo(fieldName); - // This shouldn't happen. Ever. - if (field == null) { - Debug.LogWarning("Field " + fieldName + " couldnt be found"); - attribOut = null; - return false; - } - object[] attribs = field.GetCustomAttributes(typeof(T), true); - return GetAttrib(attribs, out attribOut); - } - - public static bool HasAttrib(object[] attribs) where T : Attribute { - for (int i = 0; i < attribs.Length; i++) { - if (attribs[i].GetType() == typeof(T)) { - return true; - } - } - return false; - } - - public static bool GetCachedAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { - Dictionary> typeFields; - if (!typeAttributes.TryGetValue(classType, out typeFields)) { - typeFields = new Dictionary>(); - typeAttributes.Add(classType, typeFields); - } - - Dictionary typeTypes; - if (!typeFields.TryGetValue(fieldName, out typeTypes)) { - typeTypes = new Dictionary(); - typeFields.Add(fieldName, typeTypes); - } - - Attribute attr; - if (!typeTypes.TryGetValue(typeof(T), out attr)) { - if (GetAttrib(classType, fieldName, out attribOut)) { - typeTypes.Add(typeof(T), attribOut); - return true; - } else typeTypes.Add(typeof(T), null); - } - - if (attr == null) { - attribOut = null; - return false; - } - - attribOut = attr as T; - return true; - } - - public static List GetCachedPropertyAttribs(Type classType, string fieldName) { - Dictionary> typeFields; - if (!typeOrderedPropertyAttributes.TryGetValue(classType, out typeFields)) { - typeFields = new Dictionary>(); - typeOrderedPropertyAttributes.Add(classType, typeFields); - } - - List typeAttributes; - if (!typeFields.TryGetValue(fieldName, out typeAttributes)) { - FieldInfo field = classType.GetFieldInfo(fieldName); - object[] attribs = field.GetCustomAttributes(typeof(PropertyAttribute), true); - typeAttributes = attribs.Cast().Reverse().ToList(); //Unity draws them in reverse - typeFields.Add(fieldName, typeAttributes); - } - - return typeAttributes; - } - - public static bool IsMac() { -#if UNITY_2017_1_OR_NEWER - return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX; -#else - return SystemInfo.operatingSystem.StartsWith("Mac"); -#endif - } - - /// Returns true if this can be casted to - public static bool IsCastableTo(this Type from, Type to) { - if (to.IsAssignableFrom(from)) return true; - var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static) - .Where( - m => m.ReturnType == to && - (m.Name == "op_Implicit" || - m.Name == "op_Explicit") - ); - return methods.Count() > 0; - } - - /// - /// Looking for ports with value Type compatible with a given type. - /// - /// Node to search - /// Type to find compatiblities - /// - /// True if NodeType has some port with value type compatible - public static bool HasCompatiblePortType(Type nodeType, Type compatibleType, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) { - Type findType = typeof(XNode.Node.InputAttribute); - if (direction == XNode.NodePort.IO.Output) - findType = typeof(XNode.Node.OutputAttribute); - - //Get All fields from node type and we go filter only field with portAttribute. - //This way is possible to know the values of the all ports and if have some with compatible value tue - foreach (FieldInfo f in XNode.NodeDataCache.GetNodeFields(nodeType)) { - var portAttribute = f.GetCustomAttributes(findType, false).FirstOrDefault(); - if (portAttribute != null) { - if (IsCastableTo(f.FieldType, compatibleType)) { - return true; - } - } - } - - return false; - } - - /// - /// Filter only node types that contains some port value type compatible with an given type - /// - /// List with all nodes type to filter - /// Compatible Type to Filter - /// Return Only Node Types with ports compatible, or an empty list - public static List GetCompatibleNodesTypes(Type[] nodeTypes, Type compatibleType, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) { - //Result List - List filteredTypes = new List(); - - //Return empty list - if (nodeTypes == null) { return filteredTypes; } - if (compatibleType == null) { return filteredTypes; } - - //Find compatiblity - foreach (Type findType in nodeTypes) { - if (HasCompatiblePortType(findType, compatibleType, direction)) { - filteredTypes.Add(findType); - } - } - - return filteredTypes; - } - - - /// Return a prettiefied type name. - public static string PrettyName(this Type type) { - if (type == null) return "null"; - if (type == typeof(System.Object)) return "object"; - if (type == typeof(float)) return "float"; - else if (type == typeof(int)) return "int"; - else if (type == typeof(long)) return "long"; - else if (type == typeof(double)) return "double"; - else if (type == typeof(string)) return "string"; - else if (type == typeof(bool)) return "bool"; - else if (type.IsGenericType) { - string s = ""; - Type genericType = type.GetGenericTypeDefinition(); - if (genericType == typeof(List<>)) s = "List"; - else s = type.GetGenericTypeDefinition().ToString(); - - Type[] types = type.GetGenericArguments(); - string[] stypes = new string[types.Length]; - for (int i = 0; i < types.Length; i++) { - stypes[i] = types[i].PrettyName(); - } - return s + "<" + string.Join(", ", stypes) + ">"; - } else if (type.IsArray) { - string rank = ""; - for (int i = 1; i < type.GetArrayRank(); i++) { - rank += ","; - } - Type elementType = type.GetElementType(); - if (!elementType.IsArray) return elementType.PrettyName() + "[" + rank + "]"; - else { - string s = elementType.PrettyName(); - int i = s.IndexOf('['); - return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i); - } - } else return type.ToString(); - } - - /// Returns the default name for the node type. - public static string NodeDefaultName(Type type) { - string typeName = type.Name; - // Automatically remove redundant 'Node' postfix - if (typeName.EndsWith("Node")) typeName = typeName.Substring(0, typeName.LastIndexOf("Node")); - typeName = UnityEditor.ObjectNames.NicifyVariableName(typeName); - return typeName; - } - - /// Returns the default creation path for the node type. - public static string NodeDefaultPath(Type type) { - string typePath = type.ToString().Replace('.', '/'); - // Automatically remove redundant 'Node' postfix - if (typePath.EndsWith("Node")) typePath = typePath.Substring(0, typePath.LastIndexOf("Node")); - typePath = UnityEditor.ObjectNames.NicifyVariableName(typePath); - return typePath; - } - - /// Creates a new C# Class. - [MenuItem("Assets/Create/xNode/Node C# Script", false, 89)] - private static void CreateNode() { - string[] guids = AssetDatabase.FindAssets("xNode_NodeTemplate.cs"); - if (guids.Length == 0) { - Debug.LogWarning("xNode_NodeTemplate.cs.txt not found in asset database"); - return; - } - string path = AssetDatabase.GUIDToAssetPath(guids[0]); - CreateFromTemplate( - "NewNode.cs", - path - ); - } - - /// Creates a new C# Class. - [MenuItem("Assets/Create/xNode/NodeGraph C# Script", false, 89)] - private static void CreateGraph() { - string[] guids = AssetDatabase.FindAssets("xNode_NodeGraphTemplate.cs"); - if (guids.Length == 0) { - Debug.LogWarning("xNode_NodeGraphTemplate.cs.txt not found in asset database"); - return; - } - string path = AssetDatabase.GUIDToAssetPath(guids[0]); - CreateFromTemplate( - "NewNodeGraph.cs", - path - ); - } - - public static void CreateFromTemplate(string initialName, string templatePath) { - ProjectWindowUtil.StartNameEditingIfProjectWindowExists( - 0, - ScriptableObject.CreateInstance(), - initialName, - scriptIcon, - templatePath - ); - } - - /// Inherits from EndNameAction, must override EndNameAction.Action - public class DoCreateCodeFile : UnityEditor.ProjectWindowCallback.EndNameEditAction { - public override void Action(int instanceId, string pathName, string resourceFile) { - Object o = CreateScript(pathName, resourceFile); - ProjectWindowUtil.ShowCreatedAsset(o); - } - } - - /// Creates Script from Template's path. - internal static UnityEngine.Object CreateScript(string pathName, string templatePath) { - string className = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty); - string templateText = string.Empty; - - UTF8Encoding encoding = new UTF8Encoding(true, false); - - if (File.Exists(templatePath)) { - /// Read procedures. - StreamReader reader = new StreamReader(templatePath); - templateText = reader.ReadToEnd(); - reader.Close(); - - templateText = templateText.Replace("#SCRIPTNAME#", className); - templateText = templateText.Replace("#NOTRIM#", string.Empty); - /// You can replace as many tags you make on your templates, just repeat Replace function - /// e.g.: - /// templateText = templateText.Replace("#NEWTAG#", "MyText"); - - /// Write procedures. - - StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding); - writer.Write(templateText); - writer.Close(); - - AssetDatabase.ImportAsset(pathName); - return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object)); - } else { - Debug.LogError(string.Format("The template file was not found: {0}", templatePath)); - return null; - } - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using UnityEditor; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace XNodeEditor { + /// A set of editor-only utilities and extensions for xNode + public static class NodeEditorUtilities { + + /// C#'s Script Icon [The one MonoBhevaiour Scripts have]. + private static Texture2D scriptIcon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D); + + /// Saves Attribute from Type+Field for faster lookup. Resets on recompiles. + private static Dictionary>> typeAttributes = new Dictionary>>(); + + /// Saves ordered PropertyAttribute from Type+Field for faster lookup. Resets on recompiles. + private static Dictionary>> typeOrderedPropertyAttributes = new Dictionary>>(); + + public static bool GetAttrib(Type classType, out T attribOut) where T : Attribute { + var attribs = classType.GetCustomAttributes(typeof(T), false); + return GetAttrib(attribs, out attribOut); + } + + public static bool GetAttrib(object[] attribs, out T attribOut) where T : Attribute { + for (var i = 0; i < attribs.Length; i++) { + if (attribs[i] is T) { + attribOut = attribs[i] as T; + return true; + } + } + attribOut = null; + return false; + } + + public static bool GetAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { + // If we can't find field in the first run, it's probably a private field in a base class. + var field = classType.GetFieldInfo(fieldName); + // This shouldn't happen. Ever. + if (field == null) { + Debug.LogWarning("Field " + fieldName + " couldnt be found"); + attribOut = null; + return false; + } + var attribs = field.GetCustomAttributes(typeof(T), true); + return GetAttrib(attribs, out attribOut); + } + + public static bool HasAttrib(object[] attribs) where T : Attribute { + for (var i = 0; i < attribs.Length; i++) { + if (attribs[i].GetType() == typeof(T)) { + return true; + } + } + return false; + } + + public static bool GetCachedAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { + Dictionary> typeFields; + if (!typeAttributes.TryGetValue(classType, out typeFields)) { + typeFields = new Dictionary>(); + typeAttributes.Add(classType, typeFields); + } + + Dictionary typeTypes; + if (!typeFields.TryGetValue(fieldName, out typeTypes)) { + typeTypes = new Dictionary(); + typeFields.Add(fieldName, typeTypes); + } + + Attribute attr; + if (!typeTypes.TryGetValue(typeof(T), out attr)) { + if (GetAttrib(classType, fieldName, out attribOut)) { + typeTypes.Add(typeof(T), attribOut); + return true; + } else + { + typeTypes.Add(typeof(T), null); + } + } + + if (attr == null) { + attribOut = null; + return false; + } + + attribOut = attr as T; + return true; + } + + public static List GetCachedPropertyAttribs(Type classType, string fieldName) { + Dictionary> typeFields; + if (!typeOrderedPropertyAttributes.TryGetValue(classType, out typeFields)) { + typeFields = new Dictionary>(); + typeOrderedPropertyAttributes.Add(classType, typeFields); + } + + List typeAttributes; + if (!typeFields.TryGetValue(fieldName, out typeAttributes)) { + var field = classType.GetFieldInfo(fieldName); + var attribs = field.GetCustomAttributes(typeof(PropertyAttribute), true); + typeAttributes = attribs.Cast().Reverse().ToList(); //Unity draws them in reverse + typeFields.Add(fieldName, typeAttributes); + } + + return typeAttributes; + } + + public static bool IsMac() { +#if UNITY_2017_1_OR_NEWER + return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX; +#else + return SystemInfo.operatingSystem.StartsWith("Mac"); +#endif + } + + /// Returns true if this can be casted to + public static bool IsCastableTo(this Type from, Type to) { + if (to.IsAssignableFrom(from)) + { + return true; + } + + var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where( + m => m.ReturnType == to && + (m.Name == "op_Implicit" || + m.Name == "op_Explicit") + ); + return methods.Count() > 0; + } + + /// + /// Looking for ports with value Type compatible with a given type. + /// + /// Node to search + /// Type to find compatiblities + /// + /// True if NodeType has some port with value type compatible + public static bool HasCompatiblePortType(Type nodeType, Type compatibleType, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) { + var findType = typeof(XNode.Node.InputAttribute); + if (direction == XNode.NodePort.IO.Output) + { + findType = typeof(XNode.Node.OutputAttribute); + } + + //Get All fields from node type and we go filter only field with portAttribute. + //This way is possible to know the values of the all ports and if have some with compatible value tue + foreach (var f in XNode.NodeDataCache.GetNodeFields(nodeType)) { + var portAttribute = f.GetCustomAttributes(findType, false).FirstOrDefault(); + if (portAttribute != null) { + if (IsCastableTo(f.FieldType, compatibleType)) { + return true; + } + } + } + + return false; + } + + /// + /// Filter only node types that contains some port value type compatible with an given type + /// + /// List with all nodes type to filter + /// Compatible Type to Filter + /// Return Only Node Types with ports compatible, or an empty list + public static List GetCompatibleNodesTypes(Type[] nodeTypes, Type compatibleType, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) { + //Result List + var filteredTypes = new List(); + + //Return empty list + if (nodeTypes == null) { return filteredTypes; } + if (compatibleType == null) { return filteredTypes; } + + //Find compatiblity + foreach (var findType in nodeTypes) { + if (HasCompatiblePortType(findType, compatibleType, direction)) { + filteredTypes.Add(findType); + } + } + + return filteredTypes; + } + + + /// Return a prettiefied type name. + public static string PrettyName(this Type type) { + if (type == null) + { + return "null"; + } + + if (type == typeof(System.Object)) + { + return "object"; + } + + if (type == typeof(float)) + { + return "float"; + } + else if (type == typeof(int)) + { + return "int"; + } + else if (type == typeof(long)) + { + return "long"; + } + else if (type == typeof(double)) + { + return "double"; + } + else if (type == typeof(string)) + { + return "string"; + } + else if (type == typeof(bool)) + { + return "bool"; + } + else if (type.IsGenericType) { + var s = ""; + var genericType = type.GetGenericTypeDefinition(); + if (genericType == typeof(List<>)) + { + s = "List"; + } + else + { + s = type.GetGenericTypeDefinition().ToString(); + } + + var types = type.GetGenericArguments(); + var stypes = new string[types.Length]; + for (var i = 0; i < types.Length; i++) { + stypes[i] = types[i].PrettyName(); + } + return s + "<" + string.Join(", ", stypes) + ">"; + } else if (type.IsArray) { + var rank = ""; + for (var i = 1; i < type.GetArrayRank(); i++) { + rank += ","; + } + var elementType = type.GetElementType(); + if (!elementType.IsArray) + { + return elementType.PrettyName() + "[" + rank + "]"; + } + else { + string s = elementType.PrettyName(); + var i = s.IndexOf('['); + return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i); + } + } else + { + return type.ToString(); + } + } + + /// Returns the default name for the node type. + public static string NodeDefaultName(Type type) { + var typeName = type.Name; + // Automatically remove redundant 'Node' postfix + if (typeName.EndsWith("Node")) + { + typeName = typeName.Substring(0, typeName.LastIndexOf("Node")); + } + + typeName = UnityEditor.ObjectNames.NicifyVariableName(typeName); + return typeName; + } + + /// Returns the default creation path for the node type. + public static string NodeDefaultPath(Type type) { + var typePath = type.ToString().Replace('.', '/'); + // Automatically remove redundant 'Node' postfix + if (typePath.EndsWith("Node")) + { + typePath = typePath.Substring(0, typePath.LastIndexOf("Node")); + } + + typePath = UnityEditor.ObjectNames.NicifyVariableName(typePath); + return typePath; + } + + /// Creates a new C# Class. + [MenuItem("Assets/Create/xNode/Node C# Script", false, 89)] + private static void CreateNode() { + var guids = AssetDatabase.FindAssets("xNode_NodeTemplate.cs"); + if (guids.Length == 0) { + Debug.LogWarning("xNode_NodeTemplate.cs.txt not found in asset database"); + return; + } + var path = AssetDatabase.GUIDToAssetPath(guids[0]); + CreateFromTemplate( + "NewNode.cs", + path + ); + } + + /// Creates a new C# Class. + [MenuItem("Assets/Create/xNode/NodeGraph C# Script", false, 89)] + private static void CreateGraph() { + var guids = AssetDatabase.FindAssets("xNode_NodeGraphTemplate.cs"); + if (guids.Length == 0) { + Debug.LogWarning("xNode_NodeGraphTemplate.cs.txt not found in asset database"); + return; + } + var path = AssetDatabase.GUIDToAssetPath(guids[0]); + CreateFromTemplate( + "NewNodeGraph.cs", + path + ); + } + + public static void CreateFromTemplate(string initialName, string templatePath) { + ProjectWindowUtil.StartNameEditingIfProjectWindowExists( + 0, + ScriptableObject.CreateInstance(), + initialName, + scriptIcon, + templatePath + ); + } + + /// Inherits from EndNameAction, must override EndNameAction.Action + public class DoCreateCodeFile : UnityEditor.ProjectWindowCallback.EndNameEditAction { + public override void Action(int instanceId, string pathName, string resourceFile) { + var o = CreateScript(pathName, resourceFile); + ProjectWindowUtil.ShowCreatedAsset(o); + } + } + + /// Creates Script from Template's path. + internal static UnityEngine.Object CreateScript(string pathName, string templatePath) { + var className = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty); + var templateText = string.Empty; + + var encoding = new UTF8Encoding(true, false); + + if (File.Exists(templatePath)) { + /// Read procedures. + var reader = new StreamReader(templatePath); + templateText = reader.ReadToEnd(); + reader.Close(); + + templateText = templateText.Replace("#SCRIPTNAME#", className); + templateText = templateText.Replace("#NOTRIM#", string.Empty); + /// You can replace as many tags you make on your templates, just repeat Replace function + /// e.g.: + /// templateText = templateText.Replace("#NEWTAG#", "MyText"); + + /// Write procedures. + + var writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding); + writer.Write(templateText); + writer.Close(); + + AssetDatabase.ImportAsset(pathName); + return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object)); + } else { + Debug.LogError(string.Format("The template file was not found: {0}", templatePath)); + return null; + } + } + } +} diff --git a/Scripts/Editor/NodeEditorUtilities.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorUtilities.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorUtilities.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorUtilities.cs.meta diff --git a/Scripts/Editor/NodeEditorWindow.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorWindow.cs similarity index 72% rename from Scripts/Editor/NodeEditorWindow.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorWindow.cs index a7ec96b..459d93d 100644 --- a/Scripts/Editor/NodeEditorWindow.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorWindow.cs @@ -1,216 +1,253 @@ -using System.Collections.Generic; -using UnityEditor; -using UnityEditor.Callbacks; -using UnityEngine; -using System; -using Object = UnityEngine.Object; - -namespace XNodeEditor { - [InitializeOnLoad] - public partial class NodeEditorWindow : EditorWindow { - public static NodeEditorWindow current; - - /// Stores node positions for all nodePorts. - public Dictionary portConnectionPoints { get { return _portConnectionPoints; } } - private Dictionary _portConnectionPoints = new Dictionary(); - [SerializeField] private NodePortReference[] _references = new NodePortReference[0]; - [SerializeField] private Rect[] _rects = new Rect[0]; - - private Func isDocked { - get { - if (_isDocked == null) _isDocked = this.GetIsDockedDelegate(); - return _isDocked; - } - } - private Func _isDocked; - - [System.Serializable] private class NodePortReference { - [SerializeField] private XNode.Node _node; - [SerializeField] private string _name; - - public NodePortReference(XNode.NodePort nodePort) { - _node = nodePort.node; - _name = nodePort.fieldName; - } - - public XNode.NodePort GetNodePort() { - if (_node == null) { - return null; - } - return _node.GetPort(_name); - } - } - - private void OnDisable() { - // Cache portConnectionPoints before serialization starts - int count = portConnectionPoints.Count; - _references = new NodePortReference[count]; - _rects = new Rect[count]; - int index = 0; - foreach (var portConnectionPoint in portConnectionPoints) { - _references[index] = new NodePortReference(portConnectionPoint.Key); - _rects[index] = portConnectionPoint.Value; - index++; - } - } - - private void OnEnable() { - // Reload portConnectionPoints if there are any - int length = _references.Length; - if (length == _rects.Length) { - for (int i = 0; i < length; i++) { - XNode.NodePort nodePort = _references[i].GetNodePort(); - if (nodePort != null) - _portConnectionPoints.Add(nodePort, _rects[i]); - } - } - } - - public Dictionary nodeSizes { get { return _nodeSizes; } } - private Dictionary _nodeSizes = new Dictionary(); - public XNode.NodeGraph graph; - public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } } - private Vector2 _panOffset; - public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom, NodeEditorPreferences.GetSettings().maxZoom); Repaint(); } } - private float _zoom = 1; - - void OnFocus() { - current = this; - ValidateGraphEditor(); - if (graphEditor != null) { - graphEditor.OnWindowFocus(); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } - - dragThreshold = Math.Max(1f, Screen.width / 1000f); - } - - void OnLostFocus() { - if (graphEditor != null) graphEditor.OnWindowFocusLost(); - } - - [InitializeOnLoadMethod] - private static void OnLoad() { - Selection.selectionChanged -= OnSelectionChanged; - Selection.selectionChanged += OnSelectionChanged; - } - - /// Handle Selection Change events - private static void OnSelectionChanged() { - XNode.NodeGraph nodeGraph = Selection.activeObject as XNode.NodeGraph; - if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) { - if (NodeEditorPreferences.GetSettings().openOnCreate) Open(nodeGraph); - } - } - - /// Make sure the graph editor is assigned and to the right object - private void ValidateGraphEditor() { - NodeGraphEditor graphEditor = NodeGraphEditor.GetEditor(graph, this); - if (this.graphEditor != graphEditor && graphEditor != null) { - this.graphEditor = graphEditor; - graphEditor.OnOpen(); - } - } - - /// Create editor window - public static NodeEditorWindow Init() { - NodeEditorWindow w = CreateInstance(); - w.titleContent = new GUIContent("xNode"); - w.wantsMouseMove = true; - w.Show(); - return w; - } - - public void Save() { - if (AssetDatabase.Contains(graph)) { - EditorUtility.SetDirty(graph); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } else SaveAs(); - } - - public void SaveAs() { - string path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", ""); - if (string.IsNullOrEmpty(path)) return; - else { - XNode.NodeGraph existingGraph = AssetDatabase.LoadAssetAtPath(path); - if (existingGraph != null) AssetDatabase.DeleteAsset(path); - AssetDatabase.CreateAsset(graph, path); - EditorUtility.SetDirty(graph); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - } - } - - private void DraggableWindow(int windowID) { - GUI.DragWindow(); - } - - public Vector2 WindowToGridPosition(Vector2 windowPosition) { - return (windowPosition - (position.size * 0.5f) - (panOffset / zoom)) * zoom; - } - - public Vector2 GridToWindowPosition(Vector2 gridPosition) { - return (position.size * 0.5f) + (panOffset / zoom) + (gridPosition / zoom); - } - - public Rect GridToWindowRectNoClipped(Rect gridRect) { - gridRect.position = GridToWindowPositionNoClipped(gridRect.position); - return gridRect; - } - - public Rect GridToWindowRect(Rect gridRect) { - gridRect.position = GridToWindowPosition(gridRect.position); - gridRect.size /= zoom; - return gridRect; - } - - public Vector2 GridToWindowPositionNoClipped(Vector2 gridPosition) { - Vector2 center = position.size * 0.5f; - // UI Sharpness complete fix - Round final offset not panOffset - float xOffset = Mathf.Round(center.x * zoom + (panOffset.x + gridPosition.x)); - float yOffset = Mathf.Round(center.y * zoom + (panOffset.y + gridPosition.y)); - return new Vector2(xOffset, yOffset); - } - - public void SelectNode(XNode.Node node, bool add) { - if (add) { - List selection = new List(Selection.objects); - selection.Add(node); - Selection.objects = selection.ToArray(); - } else Selection.objects = new Object[] { node }; - } - - public void DeselectNode(XNode.Node node) { - List selection = new List(Selection.objects); - selection.Remove(node); - Selection.objects = selection.ToArray(); - } - - [OnOpenAsset(0)] - public static bool OnOpen(int instanceID, int line) { - XNode.NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as XNode.NodeGraph; - if (nodeGraph != null) { - Open(nodeGraph); - return true; - } - return false; - } - - /// Open the provided graph in the NodeEditor - public static NodeEditorWindow Open(XNode.NodeGraph graph) { - if (!graph) return null; - - NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow; - w.wantsMouseMove = true; - w.graph = graph; - return w; - } - - /// Repaint all open NodeEditorWindows. - public static void RepaintAll() { - NodeEditorWindow[] windows = Resources.FindObjectsOfTypeAll(); - for (int i = 0; i < windows.Length; i++) { - windows[i].Repaint(); - } - } - } -} +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEngine; +using System; +using Object = UnityEngine.Object; + +namespace XNodeEditor { + [InitializeOnLoad] + public partial class NodeEditorWindow : EditorWindow { + public static NodeEditorWindow current; + + /// Stores node positions for all nodePorts. + public Dictionary portConnectionPoints { get { return _portConnectionPoints; } } + private Dictionary _portConnectionPoints = new Dictionary(); + [SerializeField] private NodePortReference[] _references = new NodePortReference[0]; + [SerializeField] private Rect[] _rects = new Rect[0]; + + private Func isDocked { + get { + if (_isDocked == null) + { + _isDocked = this.GetIsDockedDelegate(); + } + + return _isDocked; + } + } + private Func _isDocked; + + [System.Serializable] private class NodePortReference { + [SerializeField] private XNode.Node _node; + [SerializeField] private string _name; + + public NodePortReference(XNode.NodePort nodePort) { + _node = nodePort.node; + _name = nodePort.fieldName; + } + + public XNode.NodePort GetNodePort() { + if (_node == null) { + return null; + } + return _node.GetPort(_name); + } + } + + private void OnDisable() { + // Cache portConnectionPoints before serialization starts + var count = portConnectionPoints.Count; + _references = new NodePortReference[count]; + _rects = new Rect[count]; + var index = 0; + foreach (var portConnectionPoint in portConnectionPoints) { + _references[index] = new NodePortReference(portConnectionPoint.Key); + _rects[index] = portConnectionPoint.Value; + index++; + } + } + + private void OnEnable() { + // Reload portConnectionPoints if there are any + var length = _references.Length; + if (length == _rects.Length) { + for (var i = 0; i < length; i++) { + var nodePort = _references[i].GetNodePort(); + if (nodePort != null) + { + _portConnectionPoints.Add(nodePort, _rects[i]); + } + } + } + } + + public Dictionary nodeSizes { get { return _nodeSizes; } } + private Dictionary _nodeSizes = new Dictionary(); + public XNode.NodeGraph graph; + public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } } + private Vector2 _panOffset; + public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom, NodeEditorPreferences.GetSettings().maxZoom); Repaint(); } } + private float _zoom = 1; + + private void OnFocus() { + current = this; + ValidateGraphEditor(); + if (graphEditor != null) { + graphEditor.OnWindowFocus(); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } + + dragThreshold = Math.Max(1f, Screen.width / 1000f); + } + + private void OnLostFocus() { + if (graphEditor != null) + { + graphEditor.OnWindowFocusLost(); + } + } + + [InitializeOnLoadMethod] + private static void OnLoad() { + Selection.selectionChanged -= OnSelectionChanged; + Selection.selectionChanged += OnSelectionChanged; + } + + /// Handle Selection Change events + private static void OnSelectionChanged() { + var nodeGraph = Selection.activeObject as XNode.NodeGraph; + if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) { + if (NodeEditorPreferences.GetSettings().openOnCreate) + { + Open(nodeGraph); + } + } + } + + /// Make sure the graph editor is assigned and to the right object + private void ValidateGraphEditor() { + var graphEditor = NodeGraphEditor.GetEditor(graph, this); + if (this.graphEditor != graphEditor && graphEditor != null) { + this.graphEditor = graphEditor; + graphEditor.OnOpen(); + } + } + + /// Create editor window + public static NodeEditorWindow Init() { + var w = CreateInstance(); + w.titleContent = new GUIContent("xNode"); + w.wantsMouseMove = true; + w.Show(); + return w; + } + + public void Save() { + if (AssetDatabase.Contains(graph)) { + EditorUtility.SetDirty(graph); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } else + { + SaveAs(); + } + } + + public void SaveAs() { + var path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", ""); + if (string.IsNullOrEmpty(path)) + { + return; + } + else { + var existingGraph = AssetDatabase.LoadAssetAtPath(path); + if (existingGraph != null) + { + AssetDatabase.DeleteAsset(path); + } + + AssetDatabase.CreateAsset(graph, path); + EditorUtility.SetDirty(graph); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + } + } + + private void DraggableWindow(int windowID) { + GUI.DragWindow(); + } + + public Vector2 WindowToGridPosition(Vector2 windowPosition) { + return (windowPosition - (position.size * 0.5f) - (panOffset / zoom)) * zoom; + } + + public Vector2 GridToWindowPosition(Vector2 gridPosition) { + return (position.size * 0.5f) + (panOffset / zoom) + (gridPosition / zoom); + } + + public Rect GridToWindowRectNoClipped(Rect gridRect) { + gridRect.position = GridToWindowPositionNoClipped(gridRect.position); + return gridRect; + } + + public Rect GridToWindowRect(Rect gridRect) { + gridRect.position = GridToWindowPosition(gridRect.position); + gridRect.size /= zoom; + return gridRect; + } + + public Vector2 GridToWindowPositionNoClipped(Vector2 gridPosition) { + var center = position.size * 0.5f; + // UI Sharpness complete fix - Round final offset not panOffset + var xOffset = Mathf.Round(center.x * zoom + (panOffset.x + gridPosition.x)); + var yOffset = Mathf.Round(center.y * zoom + (panOffset.y + gridPosition.y)); + return new Vector2(xOffset, yOffset); + } + + public void SelectNode(XNode.Node node, bool add) { + if (add) { + var selection = new List(Selection.objects); + selection.Add(node); + Selection.objects = selection.ToArray(); + } else + { + Selection.objects = new Object[] { node }; + } + } + + public void DeselectNode(XNode.Node node) { + var selection = new List(Selection.objects); + selection.Remove(node); + Selection.objects = selection.ToArray(); + } + + [OnOpenAsset(0)] + public static bool OnOpen(int instanceID, int line) { + var nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as XNode.NodeGraph; + if (nodeGraph != null) { + Open(nodeGraph); + return true; + } + return false; + } + + /// Open the provided graph in the NodeEditor + public static NodeEditorWindow Open(XNode.NodeGraph graph) { + if (!graph) + { + return null; + } + + var w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow; + w.wantsMouseMove = true; + w.graph = graph; + return w; + } + + /// Repaint all open NodeEditorWindows. + public static void RepaintAll() { + var windows = Resources.FindObjectsOfTypeAll(); + for (var i = 0; i < windows.Length; i++) { + windows[i].Repaint(); + } + } + } +} diff --git a/Scripts/Editor/NodeEditorWindow.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorWindow.cs.meta similarity index 100% rename from Scripts/Editor/NodeEditorWindow.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeEditorWindow.cs.meta diff --git a/Scripts/Editor/NodeGraphEditor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphEditor.cs similarity index 78% rename from Scripts/Editor/NodeGraphEditor.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphEditor.cs index 60b0cdb..e3a2493 100644 --- a/Scripts/Editor/NodeGraphEditor.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphEditor.cs @@ -44,9 +44,13 @@ namespace XNodeEditor { //Check if type has the CreateNodeMenuAttribute XNode.Node.CreateNodeMenuAttribute attrib; if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path + { return attrib.menuName; + } else // Return generated path + { return NodeEditorUtilities.NodeDefaultPath(type); + } } /// The order by which the menu items are displayed. @@ -54,9 +58,13 @@ namespace XNodeEditor { //Check if type has the CreateNodeMenuAttribute XNode.Node.CreateNodeMenuAttribute attrib; if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path + { return attrib.order; + } else + { return 0; + } } /// @@ -74,7 +82,7 @@ namespace XNodeEditor { /// Use it to filter only nodes with ports value type, compatible with this type /// Direction of the compatiblity public virtual void AddContextMenuItems(GenericMenu menu, Type compatibleType = null, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) { - Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition); + var pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition); Type[] nodeTypes; @@ -84,31 +92,53 @@ namespace XNodeEditor { nodeTypes = NodeEditorReflection.nodeTypes.OrderBy(GetNodeMenuOrder).ToArray(); } - for (int i = 0; i < nodeTypes.Length; i++) { - Type type = nodeTypes[i]; + for (var i = 0; i < nodeTypes.Length; i++) { + var type = nodeTypes[i]; //Get node context menu path - string path = GetNodeMenuName(type); - if (string.IsNullOrEmpty(path)) continue; + var path = GetNodeMenuName(type); + if (string.IsNullOrEmpty(path)) + { + continue; + } // Check if user is allowed to add more of given node type XNode.Node.DisallowMultipleNodesAttribute disallowAttrib; - bool disallowed = false; + var disallowed = false; if (NodeEditorUtilities.GetAttrib(type, out disallowAttrib)) { - int typeCount = target.nodes.Count(x => x.GetType() == type); - if (typeCount >= disallowAttrib.max) disallowed = true; + var typeCount = target.nodes.Count(x => x.GetType() == type); + if (typeCount >= disallowAttrib.max) + { + disallowed = true; + } } // Add node entry to context menu - if (disallowed) menu.AddItem(new GUIContent(path), false, null); - else menu.AddItem(new GUIContent(path), false, () => { - XNode.Node node = CreateNode(type, pos); - if (node != null) NodeEditorWindow.current.AutoConnect(node); // handle null nodes to avoid nullref exceptions - }); + if (disallowed) + { + menu.AddItem(new GUIContent(path), false, null); + } + else + { + menu.AddItem(new GUIContent(path), false, () => { + var node = CreateNode(type, pos); + if (node != null) + { + NodeEditorWindow.current.AutoConnect(node); // handle null nodes to avoid nullref exceptions + } + }); + } } menu.AddSeparator(""); - if (NodeEditorWindow.copyBuffer != null && NodeEditorWindow.copyBuffer.Length > 0) menu.AddItem(new GUIContent("Paste"), false, () => NodeEditorWindow.current.PasteNodes(pos)); - else menu.AddDisabledItem(new GUIContent("Paste")); + if (NodeEditorWindow.copyBuffer != null && NodeEditorWindow.copyBuffer.Length > 0) + { + menu.AddItem(new GUIContent("Paste"), false, () => NodeEditorWindow.current.PasteNodes(pos)); + } + else + { + menu.AddDisabledItem(new GUIContent("Paste")); + } + menu.AddItem(new GUIContent("Preferences"), false, () => NodeEditorReflection.OpenPreferences()); menu.AddCustomContextMenuItems(target); } @@ -117,11 +147,11 @@ namespace XNodeEditor { /// The output this noodle comes from. Never null. /// The output this noodle comes from. Can be null if we are dragging the noodle. public virtual Gradient GetNoodleGradient(XNode.NodePort output, XNode.NodePort input) { - Gradient grad = new Gradient(); + var grad = new Gradient(); // If dragging the noodle, draw solid, slightly transparent if (input == null) { - Color a = GetTypeColor(output.ValueType); + var a = GetTypeColor(output.ValueType); grad.SetKeys( new GradientColorKey[] { new GradientColorKey(a, 0f) }, new GradientAlphaKey[] { new GradientAlphaKey(0.6f, 0f) } @@ -129,8 +159,8 @@ namespace XNodeEditor { } // If normal, draw gradient fading from one input color to the other else { - Color a = GetTypeColor(output.ValueType); - Color b = GetTypeColor(input.ValueType); + var a = GetTypeColor(output.ValueType); + var b = GetTypeColor(input.ValueType); // If any port is hovered, tint white if (window.hoveredPort == output || window.hoveredPort == input) { a = Color.Lerp(a, Color.white, 0.8f); @@ -176,7 +206,9 @@ namespace XNodeEditor { /// public virtual GUIStyle GetPortStyle(XNode.NodePort port) { if (port.direction == XNode.NodePort.IO.Input) + { return NodeEditorResources.styles.inputPort; + } return NodeEditorResources.styles.outputPort; } @@ -194,11 +226,11 @@ namespace XNodeEditor { /// Override to display custom tooltips public virtual string GetPortTooltip(XNode.NodePort port) { - Type portType = port.ValueType; - string tooltip = ""; + var portType = port.ValueType; + var tooltip = ""; tooltip = portType.PrettyName(); if (port.IsOutput) { - object obj = port.node.GetValue(port); + var obj = port.node.GetValue(port); tooltip += " = " + (obj != null ? obj.ToString() : "null"); } return tooltip; @@ -206,19 +238,38 @@ namespace XNodeEditor { /// Deal with objects dropped into the graph through DragAndDrop public virtual void OnDropObjects(UnityEngine.Object[] objects) { - if (GetType() != typeof(NodeGraphEditor)) Debug.Log("No OnDropObjects override defined for " + GetType()); + if (GetType() != typeof(NodeGraphEditor)) + { + Debug.Log("No OnDropObjects override defined for " + GetType()); + } } /// Create a node and save it in the graph asset public virtual XNode.Node CreateNode(Type type, Vector2 position) { Undo.RecordObject(target, "Create Node"); - XNode.Node node = target.AddNode(type); - if (node == null) return null; // handle null nodes to avoid nullref exceptions + var node = target.AddNode(type); + if (node == null) + { + return null; // handle null nodes to avoid nullref exceptions + } + Undo.RegisterCreatedObjectUndo(node, "Create Node"); node.position = position; - if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type); - if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) AssetDatabase.AddObjectToAsset(node, target); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); + if (node.name == null || node.name.Trim() == "") + { + node.name = NodeEditorUtilities.NodeDefaultName(type); + } + + if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) + { + AssetDatabase.AddObjectToAsset(node, target); + } + + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + NodeEditorWindow.RepaintAll(); return node; } @@ -226,19 +277,27 @@ namespace XNodeEditor { /// Creates a copy of the original node in the graph public virtual XNode.Node CopyNode(XNode.Node original) { Undo.RecordObject(target, "Duplicate Node"); - XNode.Node node = target.CopyNode(original); + var node = target.CopyNode(original); Undo.RegisterCreatedObjectUndo(node, "Duplicate Node"); node.name = original.name; - if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) AssetDatabase.AddObjectToAsset(node, target); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); + if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) + { + AssetDatabase.AddObjectToAsset(node, target); + } + + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } + return node; } /// Return false for nodes that can't be removed public virtual bool CanRemove(XNode.Node node) { // Check graph attributes to see if this node is required - Type graphType = target.GetType(); - XNode.NodeGraph.RequireNodeAttribute[] attribs = Array.ConvertAll( + var graphType = target.GetType(); + var attribs = Array.ConvertAll( graphType.GetCustomAttributes(typeof(XNode.NodeGraph.RequireNodeAttribute), true), x => x as XNode.NodeGraph.RequireNodeAttribute); if (attribs.Any(x => x.Requires(node.GetType()))) { if (target.nodes.Count(x => x.GetType() == node.GetType()) <= 1) { @@ -250,17 +309,26 @@ namespace XNodeEditor { /// Safely remove a node and all its connections. public virtual void RemoveNode(XNode.Node node) { - if (!CanRemove(node)) return; + if (!CanRemove(node)) + { + return; + } // Remove the node Undo.RecordObject(node, "Delete Node"); Undo.RecordObject(target, "Delete Node"); foreach (var port in node.Ports) foreach (var conn in port.GetConnections()) + { Undo.RecordObject(conn.node, "Delete Node"); + } + target.RemoveNode(node); Undo.DestroyObjectImmediate(node); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); + if (NodeEditorPreferences.GetSettings().autoSave) + { + AssetDatabase.SaveAssets(); + } } [AttributeUsage(AttributeTargets.Class)] @@ -281,4 +349,4 @@ namespace XNodeEditor { } } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/NodeGraphEditor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphEditor.cs.meta similarity index 100% rename from Scripts/Editor/NodeGraphEditor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphEditor.cs.meta diff --git a/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphImporter.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphImporter.cs new file mode 100644 index 0000000..fd71b5e --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphImporter.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.Experimental.AssetImporters; +using UnityEngine; +using XNode; + +namespace XNodeEditor { + /// Deals with modified assets + internal class NodeGraphImporter : AssetPostprocessor { + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { + foreach (var path in importedAssets) { + // Skip processing anything without the .asset extension + if (Path.GetExtension(path) != ".asset") + { + continue; + } + + // Get the object that is requested for deletion + var graph = AssetDatabase.LoadAssetAtPath(path); + if (graph == null) + { + continue; + } + + // Get attributes + var graphType = graph.GetType(); + var attribs = Array.ConvertAll( + graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true), x => x as NodeGraph.RequireNodeAttribute); + + var position = Vector2.zero; + foreach (var attrib in attribs) { + if (attrib.type0 != null) + { + AddRequired(graph, attrib.type0, ref position); + } + + if (attrib.type1 != null) + { + AddRequired(graph, attrib.type1, ref position); + } + + if (attrib.type2 != null) + { + AddRequired(graph, attrib.type2, ref position); + } + } + } + } + + private static void AddRequired(NodeGraph graph, Type type, ref Vector2 position) { + if (!graph.nodes.Any(x => x.GetType() == type)) { + var node = graph.AddNode(type); + node.position = position; + position.x += 200; + if (node.name == null || node.name.Trim() == "") + { + node.name = NodeEditorUtilities.NodeDefaultName(type); + } + + if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(graph))) + { + AssetDatabase.AddObjectToAsset(node, graph); + } + } + } + } +} diff --git a/Scripts/Editor/NodeGraphImporter.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphImporter.cs.meta similarity index 100% rename from Scripts/Editor/NodeGraphImporter.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/NodeGraphImporter.cs.meta diff --git a/Scripts/Editor/RenamePopup.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/RenamePopup.cs similarity index 90% rename from Scripts/Editor/RenamePopup.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/RenamePopup.cs index ca1ee15..0d00072 100644 --- a/Scripts/Editor/RenamePopup.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/RenamePopup.cs @@ -14,8 +14,12 @@ namespace XNodeEditor { /// Show a rename popup for an asset at mouse position. Will trigger reimport of the asset on apply. public static RenamePopup Show(Object target, float width = 200) { - RenamePopup window = EditorWindow.GetWindow(true, "Rename " + target.name, true); - if (current != null) current.Close(); + var window = EditorWindow.GetWindow(true, "Rename " + target.name, true); + if (current != null) + { + current.Close(); + } + current = window; window.target = target; window.input = target.name; @@ -26,9 +30,13 @@ namespace XNodeEditor { } private void UpdatePositionToMouse() { - if (Event.current == null) return; + if (Event.current == null) + { + return; + } + Vector3 mousePoint = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); - Rect pos = position; + var pos = position; pos.x = mousePoint.x - position.width * 0.5f; pos.y = mousePoint.y - 10; position = pos; @@ -47,7 +55,7 @@ namespace XNodeEditor { GUI.SetNextControlName(inputControlName); input = EditorGUILayout.TextField(input); EditorGUI.FocusTextInControl(inputControlName); - Event e = Event.current; + var e = Event.current; // If input is empty, revert name to default instead if (input == null || input.Trim() == "") { if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) { @@ -84,4 +92,4 @@ namespace XNodeEditor { EditorGUIUtility.editingTextField = false; } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/RenamePopup.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/RenamePopup.cs.meta similarity index 100% rename from Scripts/Editor/RenamePopup.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/RenamePopup.cs.meta diff --git a/Scripts/Editor/Resources.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources.meta similarity index 100% rename from Scripts/Editor/Resources.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources.meta diff --git a/Scripts/Editor/Resources/ScriptTemplates.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates.meta similarity index 100% rename from Scripts/Editor/Resources/ScriptTemplates.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates.meta diff --git a/Scripts/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt similarity index 100% rename from Scripts/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt diff --git a/Scripts/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt.meta similarity index 100% rename from Scripts/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeGraphTemplate.cs.txt.meta diff --git a/Scripts/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt similarity index 100% rename from Scripts/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt diff --git a/Scripts/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt.meta similarity index 100% rename from Scripts/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/ScriptTemplates/xNode_NodeTemplate.cs.txt.meta diff --git a/Scripts/Editor/Resources/xnode_dot.png b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot.png similarity index 100% rename from Scripts/Editor/Resources/xnode_dot.png rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot.png diff --git a/Scripts/Editor/Resources/xnode_dot.png.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot.png.meta similarity index 100% rename from Scripts/Editor/Resources/xnode_dot.png.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot.png.meta diff --git a/Scripts/Editor/Resources/xnode_dot_outer.png b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot_outer.png similarity index 100% rename from Scripts/Editor/Resources/xnode_dot_outer.png rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot_outer.png diff --git a/Scripts/Editor/Resources/xnode_dot_outer.png.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot_outer.png.meta similarity index 100% rename from Scripts/Editor/Resources/xnode_dot_outer.png.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_dot_outer.png.meta diff --git a/Scripts/Editor/Resources/xnode_node.png b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node.png similarity index 100% rename from Scripts/Editor/Resources/xnode_node.png rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node.png diff --git a/Scripts/Editor/Resources/xnode_node.png.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node.png.meta similarity index 100% rename from Scripts/Editor/Resources/xnode_node.png.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node.png.meta diff --git a/Scripts/Editor/Resources/xnode_node_highlight.png b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_highlight.png similarity index 100% rename from Scripts/Editor/Resources/xnode_node_highlight.png rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_highlight.png diff --git a/Scripts/Editor/Resources/xnode_node_highlight.png.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_highlight.png.meta similarity index 100% rename from Scripts/Editor/Resources/xnode_node_highlight.png.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_highlight.png.meta diff --git a/Scripts/Editor/Resources/xnode_node_workfile.psd b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_workfile.psd similarity index 100% rename from Scripts/Editor/Resources/xnode_node_workfile.psd rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_workfile.psd diff --git a/Scripts/Editor/Resources/xnode_node_workfile.psd.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_workfile.psd.meta similarity index 100% rename from Scripts/Editor/Resources/xnode_node_workfile.psd.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/Resources/xnode_node_workfile.psd.meta diff --git a/Scripts/Editor/SceneGraphEditor.cs b/xNode/Packages/com.pillow.xnode/Runtime/Editor/SceneGraphEditor.cs similarity index 86% rename from Scripts/Editor/SceneGraphEditor.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/SceneGraphEditor.cs index dd290a8..df7cc97 100644 --- a/Scripts/Editor/SceneGraphEditor.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Editor/SceneGraphEditor.cs @@ -16,10 +16,10 @@ namespace XNodeEditor { if (sceneGraph.graph == null) { if (GUILayout.Button("New graph", GUILayout.Height(40))) { if (graphType == null) { - Type[] graphTypes = NodeEditorReflection.GetDerivedTypes(typeof(NodeGraph)); - GenericMenu menu = new GenericMenu(); - for (int i = 0; i < graphTypes.Length; i++) { - Type graphType = graphTypes[i]; + var graphTypes = NodeEditorReflection.GetDerivedTypes(typeof(NodeGraph)); + var menu = new GenericMenu(); + for (var i = 0; i < graphTypes.Length; i++) { + var graphType = graphTypes[i]; menu.AddItem(new GUIContent(graphType.Name), false, () => CreateGraph(graphType)); } menu.ShowAsContext(); @@ -58,11 +58,11 @@ namespace XNodeEditor { private void OnEnable() { sceneGraph = target as SceneGraph; - Type sceneGraphType = sceneGraph.GetType(); + var sceneGraphType = sceneGraph.GetType(); if (sceneGraphType == typeof(SceneGraph)) { graphType = null; } else { - Type baseType = sceneGraphType.BaseType; + var baseType = sceneGraphType.BaseType; if (baseType.IsGenericType) { graphType = sceneGraphType = baseType.GetGenericArguments() [0]; } @@ -75,4 +75,4 @@ namespace XNodeEditor { sceneGraph.graph.name = sceneGraph.name + "-graph"; } } -} \ No newline at end of file +} diff --git a/Scripts/Editor/SceneGraphEditor.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/SceneGraphEditor.cs.meta similarity index 100% rename from Scripts/Editor/SceneGraphEditor.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/SceneGraphEditor.cs.meta diff --git a/Scripts/Editor/XNodeEditor.asmdef b/xNode/Packages/com.pillow.xnode/Runtime/Editor/XNodeEditor.asmdef similarity index 100% rename from Scripts/Editor/XNodeEditor.asmdef rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/XNodeEditor.asmdef diff --git a/Scripts/Editor/XNodeEditor.asmdef.meta b/xNode/Packages/com.pillow.xnode/Runtime/Editor/XNodeEditor.asmdef.meta similarity index 100% rename from Scripts/Editor/XNodeEditor.asmdef.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Editor/XNodeEditor.asmdef.meta diff --git a/Scripts/Node.cs b/xNode/Packages/com.pillow.xnode/Runtime/Node.cs similarity index 89% rename from Scripts/Node.cs rename to xNode/Packages/com.pillow.xnode/Runtime/Node.cs index 62a2f4a..862ba94 100644 --- a/Scripts/Node.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/Node.cs @@ -1,421 +1,503 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace XNode { - /// - /// Base class for all nodes - /// - /// - /// Classes extending this class will be considered as valid nodes by xNode. - /// - /// [System.Serializable] - /// public class Adder : Node { - /// [Input] public float a; - /// [Input] public float b; - /// [Output] public float result; - /// - /// // GetValue should be overridden to return a value for any specified output port - /// public override object GetValue(NodePort port) { - /// return a + b; - /// } - /// } - /// - /// - [Serializable] - public abstract class Node : ScriptableObject { - /// Used by and to determine when to display the field value associated with a - public enum ShowBackingValue { - /// Never show the backing value - Never, - /// Show the backing value only when the port does not have any active connections - Unconnected, - /// Always show the backing value - Always - } - - public enum ConnectionType { - /// Allow multiple connections - Multiple, - /// always override the current connection - Override, - } - - /// Tells which types of input to allow - public enum TypeConstraint { - /// Allow all types of input - None, - /// Allow connections where input value type is assignable from output value type (eg. ScriptableObject --> Object) - Inherited, - /// Allow only similar types - Strict, - /// Allow connections where output value type is assignable from input value type (eg. Object --> ScriptableObject) - InheritedInverse, - /// Allow connections where output value type is assignable from input value or input value type is assignable from output value type - InheritedAny - } - -#region Obsolete - [Obsolete("Use DynamicPorts instead")] - public IEnumerable InstancePorts { get { return DynamicPorts; } } - - [Obsolete("Use DynamicOutputs instead")] - public IEnumerable InstanceOutputs { get { return DynamicOutputs; } } - - [Obsolete("Use DynamicInputs instead")] - public IEnumerable InstanceInputs { get { return DynamicInputs; } } - - [Obsolete("Use AddDynamicInput instead")] - public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { - return AddDynamicInput(type, connectionType, typeConstraint, fieldName); - } - - [Obsolete("Use AddDynamicOutput instead")] - public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { - return AddDynamicOutput(type, connectionType, typeConstraint, fieldName); - } - - [Obsolete("Use AddDynamicPort instead")] - private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { - return AddDynamicPort(type, direction, connectionType, typeConstraint, fieldName); - } - - [Obsolete("Use RemoveDynamicPort instead")] - public void RemoveInstancePort(string fieldName) { - RemoveDynamicPort(fieldName); - } - - [Obsolete("Use RemoveDynamicPort instead")] - public void RemoveInstancePort(NodePort port) { - RemoveDynamicPort(port); - } - - [Obsolete("Use ClearDynamicPorts instead")] - public void ClearInstancePorts() { - ClearDynamicPorts(); - } -#endregion - - /// Iterate over all ports on this node. - public IEnumerable Ports { get { foreach (NodePort port in ports.Values) yield return port; } } - /// Iterate over all outputs on this node. - public IEnumerable Outputs { get { foreach (NodePort port in Ports) { if (port.IsOutput) yield return port; } } } - /// Iterate over all inputs on this node. - public IEnumerable Inputs { get { foreach (NodePort port in Ports) { if (port.IsInput) yield return port; } } } - /// Iterate over all dynamic ports on this node. - public IEnumerable DynamicPorts { get { foreach (NodePort port in Ports) { if (port.IsDynamic) yield return port; } } } - /// Iterate over all dynamic outputs on this node. - public IEnumerable DynamicOutputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsOutput) yield return port; } } } - /// Iterate over all dynamic inputs on this node. - public IEnumerable DynamicInputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsInput) yield return port; } } } - /// Parent - [SerializeField] public NodeGraph graph; - /// Position on the - [SerializeField] public Vector2 position; - /// It is recommended not to modify these at hand. Instead, see and - [SerializeField] private NodePortDictionary ports = new NodePortDictionary(); - - /// Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable - public static NodeGraph graphHotfix; - - protected void OnEnable() { - if (graphHotfix != null) graph = graphHotfix; - graphHotfix = null; - UpdatePorts(); - Init(); - } - - /// Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. This happens automatically on enable or on redrawing a dynamic port list. - public void UpdatePorts() { - NodeDataCache.UpdatePorts(this, ports); - } - - /// Initialize node. Called on enable. - protected virtual void Init() { } - - /// Checks all connections for invalid references, and removes them. - public void VerifyConnections() { - foreach (NodePort port in Ports) port.VerifyConnections(); - } - -#region Dynamic Ports - /// Convenience function. - /// - /// - public NodePort AddDynamicInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { - return AddDynamicPort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName); - } - - /// Convenience function. - /// - /// - public NodePort AddDynamicOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { - return AddDynamicPort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName); - } - - /// Add a dynamic, serialized port to this node. - /// - /// - private NodePort AddDynamicPort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { - if (fieldName == null) { - fieldName = "dynamicInput_0"; - int i = 0; - while (HasPort(fieldName)) fieldName = "dynamicInput_" + (++i); - } else if (HasPort(fieldName)) { - Debug.LogWarning("Port '" + fieldName + "' already exists in " + name, this); - return ports[fieldName]; - } - NodePort port = new NodePort(fieldName, type, direction, connectionType, typeConstraint, this); - ports.Add(fieldName, port); - return port; - } - - /// Remove an dynamic port from the node - public void RemoveDynamicPort(string fieldName) { - NodePort dynamicPort = GetPort(fieldName); - if (dynamicPort == null) throw new ArgumentException("port " + fieldName + " doesn't exist"); - RemoveDynamicPort(GetPort(fieldName)); - } - - /// Remove an dynamic port from the node - public void RemoveDynamicPort(NodePort port) { - if (port == null) throw new ArgumentNullException("port"); - else if (port.IsStatic) throw new ArgumentException("cannot remove static port"); - port.ClearConnections(); - ports.Remove(port.fieldName); - } - - /// Removes all dynamic ports from the node - [ContextMenu("Clear Dynamic Ports")] - public void ClearDynamicPorts() { - List dynamicPorts = new List(DynamicPorts); - foreach (NodePort port in dynamicPorts) { - RemoveDynamicPort(port); - } - } -#endregion - -#region Ports - /// Returns output port which matches fieldName - public NodePort GetOutputPort(string fieldName) { - NodePort port = GetPort(fieldName); - if (port == null || port.direction != NodePort.IO.Output) return null; - else return port; - } - - /// Returns input port which matches fieldName - public NodePort GetInputPort(string fieldName) { - NodePort port = GetPort(fieldName); - if (port == null || port.direction != NodePort.IO.Input) return null; - else return port; - } - - /// Returns port which matches fieldName - public NodePort GetPort(string fieldName) { - NodePort port; - if (ports.TryGetValue(fieldName, out port)) return port; - else return null; - } - - public bool HasPort(string fieldName) { - return ports.ContainsKey(fieldName); - } -#endregion - -#region Inputs/Outputs - /// Return input value for a specified port. Returns fallback value if no ports are connected - /// Field name of requested input port - /// If no ports are connected, this value will be returned - public T GetInputValue(string fieldName, T fallback = default(T)) { - NodePort port = GetPort(fieldName); - if (port != null && port.IsConnected) return port.GetInputValue(); - else return fallback; - } - - /// Return all input values for a specified port. Returns fallback value if no ports are connected - /// Field name of requested input port - /// If no ports are connected, this value will be returned - public T[] GetInputValues(string fieldName, params T[] fallback) { - NodePort port = GetPort(fieldName); - if (port != null && port.IsConnected) return port.GetInputValues(); - else return fallback; - } - - /// Returns a value based on requested port output. Should be overridden in all derived nodes with outputs. - /// The requested port. - public virtual object GetValue(NodePort port) { - Debug.LogWarning("No GetValue(NodePort port) override defined for " + GetType()); - return null; - } -#endregion - - /// Called after a connection between two s is created - /// Output Input - public virtual void OnCreateConnection(NodePort from, NodePort to) { } - - /// Called after a connection is removed from this port - /// Output or Input - public virtual void OnRemoveConnection(NodePort port) { } - - /// Disconnect everything from this node - public void ClearConnections() { - foreach (NodePort port in Ports) port.ClearConnections(); - } - -#region Attributes - /// Mark a serializable field as an input port. You can access this through - [AttributeUsage(AttributeTargets.Field)] - public class InputAttribute : Attribute { - public ShowBackingValue backingValue; - public ConnectionType connectionType; - [Obsolete("Use dynamicPortList instead")] - public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } } - public bool dynamicPortList; - public TypeConstraint typeConstraint; - - /// Mark a serializable field as an input port. You can access this through - /// Should we display the backing value for this port as an editor field? - /// Should we allow multiple connections? - /// Constrains which input connections can be made to this port - /// If true, will display a reorderable list of inputs instead of a single port. Will automatically add and display values for lists and arrays - public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) { - this.backingValue = backingValue; - this.connectionType = connectionType; - this.dynamicPortList = dynamicPortList; - this.typeConstraint = typeConstraint; - } - } - - /// Mark a serializable field as an output port. You can access this through - [AttributeUsage(AttributeTargets.Field)] - public class OutputAttribute : Attribute { - public ShowBackingValue backingValue; - public ConnectionType connectionType; - [Obsolete("Use dynamicPortList instead")] - public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } } - public bool dynamicPortList; - public TypeConstraint typeConstraint; - - /// Mark a serializable field as an output port. You can access this through - /// Should we display the backing value for this port as an editor field? - /// Should we allow multiple connections? - /// Constrains which input connections can be made from this port - /// If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays - public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) { - this.backingValue = backingValue; - this.connectionType = connectionType; - this.dynamicPortList = dynamicPortList; - this.typeConstraint = typeConstraint; - } - - /// Mark a serializable field as an output port. You can access this through - /// Should we display the backing value for this port as an editor field? - /// Should we allow multiple connections? - /// If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays - [Obsolete("Use constructor with TypeConstraint")] - public OutputAttribute(ShowBackingValue backingValue, ConnectionType connectionType, bool dynamicPortList) : this(backingValue, connectionType, TypeConstraint.None, dynamicPortList) { } - } - - /// Manually supply node class with a context menu path - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class CreateNodeMenuAttribute : Attribute { - public string menuName; - public int order; - /// Manually supply node class with a context menu path - /// Path to this node in the context menu. Null or empty hides it. - public CreateNodeMenuAttribute(string menuName) { - this.menuName = menuName; - this.order = 0; - } - - /// Manually supply node class with a context menu path - /// Path to this node in the context menu. Null or empty hides it. - /// The order by which the menu items are displayed. - public CreateNodeMenuAttribute(string menuName, int order) { - this.menuName = menuName; - this.order = order; - } - } - - /// Prevents Node of the same type to be added more than once (configurable) to a NodeGraph - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class DisallowMultipleNodesAttribute : Attribute { - // TODO: Make inheritance work in such a way that applying [DisallowMultipleNodes(1)] to type NodeBar : Node - // while type NodeFoo : NodeBar exists, will let you add *either one* of these nodes, but not both. - public int max; - /// Prevents Node of the same type to be added more than once (configurable) to a NodeGraph - /// How many nodes to allow. Defaults to 1. - public DisallowMultipleNodesAttribute(int max = 1) { - this.max = max; - } - } - - /// Specify a color for this node type - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class NodeTintAttribute : Attribute { - public Color color; - /// Specify a color for this node type - /// Red [0.0f .. 1.0f] - /// Green [0.0f .. 1.0f] - /// Blue [0.0f .. 1.0f] - public NodeTintAttribute(float r, float g, float b) { - color = new Color(r, g, b); - } - - /// Specify a color for this node type - /// HEX color value - public NodeTintAttribute(string hex) { - ColorUtility.TryParseHtmlString(hex, out color); - } - - /// Specify a color for this node type - /// Red [0 .. 255] - /// Green [0 .. 255] - /// Blue [0 .. 255] - public NodeTintAttribute(byte r, byte g, byte b) { - color = new Color32(r, g, b, byte.MaxValue); - } - } - - /// Specify a width for this node type - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class NodeWidthAttribute : Attribute { - public int width; - /// Specify a width for this node type - /// Width - public NodeWidthAttribute(int width) { - this.width = width; - } - } -#endregion - - [Serializable] private class NodePortDictionary : Dictionary, ISerializationCallbackReceiver { - [SerializeField] private List keys = new List(); - [SerializeField] private List values = new List(); - - public void OnBeforeSerialize() { - keys.Clear(); - values.Clear(); - keys.Capacity = this.Count; - values.Capacity = this.Count; - foreach (KeyValuePair pair in this) { - keys.Add(pair.Key); - values.Add(pair.Value); - } - } - - public void OnAfterDeserialize() { - this.Clear(); -#if UNITY_2021_3_OR_NEWER - this.EnsureCapacity(keys.Count); -#endif - - if (keys.Count != values.Count) - throw new System.Exception("there are " + keys.Count + " keys and " + values.Count + " values after deserialization. Make sure that both key and value types are serializable."); - - for (int i = 0; i < keys.Count; i++) - this.Add(keys[i], values[i]); - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace XNode { + /// + /// Base class for all nodes + /// + /// + /// Classes extending this class will be considered as valid nodes by xNode. + /// + /// [System.Serializable] + /// public class Adder : Node { + /// [Input] public float a; + /// [Input] public float b; + /// [Output] public float result; + /// + /// // GetValue should be overridden to return a value for any specified output port + /// public override object GetValue(NodePort port) { + /// return a + b; + /// } + /// } + /// + /// + [Serializable] + public abstract class Node : ScriptableObject { + /// Used by and to determine when to display the field value associated with a + public enum ShowBackingValue { + /// Never show the backing value + Never, + /// Show the backing value only when the port does not have any active connections + Unconnected, + /// Always show the backing value + Always + } + + public enum ConnectionType { + /// Allow multiple connections + Multiple, + /// always override the current connection + Override, + } + + /// Tells which types of input to allow + public enum TypeConstraint { + /// Allow all types of input + None, + /// Allow connections where input value type is assignable from output value type (eg. ScriptableObject --> Object) + Inherited, + /// Allow only similar types + Strict, + /// Allow connections where output value type is assignable from input value type (eg. Object --> ScriptableObject) + InheritedInverse, + /// Allow connections where output value type is assignable from input value or input value type is assignable from output value type + InheritedAny + } + +#region Obsolete + [Obsolete("Use DynamicPorts instead")] + public IEnumerable InstancePorts { get { return DynamicPorts; } } + + [Obsolete("Use DynamicOutputs instead")] + public IEnumerable InstanceOutputs { get { return DynamicOutputs; } } + + [Obsolete("Use DynamicInputs instead")] + public IEnumerable InstanceInputs { get { return DynamicInputs; } } + + [Obsolete("Use AddDynamicInput instead")] + public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddDynamicInput(type, connectionType, typeConstraint, fieldName); + } + + [Obsolete("Use AddDynamicOutput instead")] + public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddDynamicOutput(type, connectionType, typeConstraint, fieldName); + } + + [Obsolete("Use AddDynamicPort instead")] + private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddDynamicPort(type, direction, connectionType, typeConstraint, fieldName); + } + + [Obsolete("Use RemoveDynamicPort instead")] + public void RemoveInstancePort(string fieldName) { + RemoveDynamicPort(fieldName); + } + + [Obsolete("Use RemoveDynamicPort instead")] + public void RemoveInstancePort(NodePort port) { + RemoveDynamicPort(port); + } + + [Obsolete("Use ClearDynamicPorts instead")] + public void ClearInstancePorts() { + ClearDynamicPorts(); + } +#endregion + + /// Iterate over all ports on this node. + public IEnumerable Ports { get { foreach (NodePort port in ports.Values) + { + yield return port; + } + } } + /// Iterate over all outputs on this node. + public IEnumerable Outputs { get { foreach (NodePort port in Ports) { if (port.IsOutput) + { + yield return port; + } + } } } + /// Iterate over all inputs on this node. + public IEnumerable Inputs { get { foreach (NodePort port in Ports) { if (port.IsInput) + { + yield return port; + } + } } } + /// Iterate over all dynamic ports on this node. + public IEnumerable DynamicPorts { get { foreach (NodePort port in Ports) { if (port.IsDynamic) + { + yield return port; + } + } } } + /// Iterate over all dynamic outputs on this node. + public IEnumerable DynamicOutputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsOutput) + { + yield return port; + } + } } } + /// Iterate over all dynamic inputs on this node. + public IEnumerable DynamicInputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsInput) + { + yield return port; + } + } } } + /// Parent + [SerializeField] public NodeGraph graph; + /// Position on the + [SerializeField] public Vector2 position; + /// It is recommended not to modify these at hand. Instead, see and + [SerializeField] private NodePortDictionary ports = new NodePortDictionary(); + + /// Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable + public static NodeGraph graphHotfix; + + protected void OnEnable() { + if (graphHotfix != null) + { + graph = graphHotfix; + } + + graphHotfix = null; + UpdatePorts(); + Init(); + } + + /// Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. This happens automatically on enable or on redrawing a dynamic port list. + public void UpdatePorts() { + NodeDataCache.UpdatePorts(this, ports); + } + + /// Initialize node. Called on enable. + protected virtual void Init() { } + + /// Checks all connections for invalid references, and removes them. + public void VerifyConnections() { + foreach (NodePort port in Ports) + { + port.VerifyConnections(); + } + } + +#region Dynamic Ports + /// Convenience function. + /// + /// + public NodePort AddDynamicInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddDynamicPort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName); + } + + /// Convenience function. + /// + /// + public NodePort AddDynamicOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddDynamicPort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName); + } + + /// Add a dynamic, serialized port to this node. + /// + /// + private NodePort AddDynamicPort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + if (fieldName == null) { + fieldName = "dynamicInput_0"; + var i = 0; + while (HasPort(fieldName)) + { + fieldName = "dynamicInput_" + (++i); + } + } else if (HasPort(fieldName)) { + Debug.LogWarning("Port '" + fieldName + "' already exists in " + name, this); + return ports[fieldName]; + } + NodePort port = new NodePort(fieldName, type, direction, connectionType, typeConstraint, this); + ports.Add(fieldName, port); + return port; + } + + /// Remove an dynamic port from the node + public void RemoveDynamicPort(string fieldName) { + NodePort dynamicPort = GetPort(fieldName); + if (dynamicPort == null) + { + throw new ArgumentException("port " + fieldName + " doesn't exist"); + } + + RemoveDynamicPort(GetPort(fieldName)); + } + + /// Remove an dynamic port from the node + public void RemoveDynamicPort(NodePort port) { + if (port == null) + { + throw new ArgumentNullException("port"); + } + else if (port.IsStatic) + { + throw new ArgumentException("cannot remove static port"); + } + + port.ClearConnections(); + ports.Remove(port.fieldName); + } + + /// Removes all dynamic ports from the node + [ContextMenu("Clear Dynamic Ports")] + public void ClearDynamicPorts() { + List dynamicPorts = new List(DynamicPorts); + foreach (NodePort port in dynamicPorts) { + RemoveDynamicPort(port); + } + } +#endregion + +#region Ports + /// Returns output port which matches fieldName + public NodePort GetOutputPort(string fieldName) { + NodePort port = GetPort(fieldName); + if (port == null || port.direction != NodePort.IO.Output) + { + return null; + } + else + { + return port; + } + } + + /// Returns input port which matches fieldName + public NodePort GetInputPort(string fieldName) { + NodePort port = GetPort(fieldName); + if (port == null || port.direction != NodePort.IO.Input) + { + return null; + } + else + { + return port; + } + } + + /// Returns port which matches fieldName + public NodePort GetPort(string fieldName) { + NodePort port; + if (ports.TryGetValue(fieldName, out port)) + { + return port; + } + else + { + return null; + } + } + + public bool HasPort(string fieldName) { + return ports.ContainsKey(fieldName); + } +#endregion + +#region Inputs/Outputs + /// Return input value for a specified port. Returns fallback value if no ports are connected + /// Field name of requested input port + /// If no ports are connected, this value will be returned + public T GetInputValue(string fieldName, T fallback = default(T)) { + NodePort port = GetPort(fieldName); + if (port != null && port.IsConnected) + { + return port.GetInputValue(); + } + else + { + return fallback; + } + } + + /// Return all input values for a specified port. Returns fallback value if no ports are connected + /// Field name of requested input port + /// If no ports are connected, this value will be returned + public T[] GetInputValues(string fieldName, params T[] fallback) { + NodePort port = GetPort(fieldName); + if (port != null && port.IsConnected) + { + return port.GetInputValues(); + } + else + { + return fallback; + } + } + + /// Returns a value based on requested port output. Should be overridden in all derived nodes with outputs. + /// The requested port. + public virtual object GetValue(NodePort port) { + Debug.LogWarning("No GetValue(NodePort port) override defined for " + GetType()); + return null; + } +#endregion + + /// Called after a connection between two s is created + /// Output Input + public virtual void OnCreateConnection(NodePort from, NodePort to) { } + + /// Called after a connection is removed from this port + /// Output or Input + public virtual void OnRemoveConnection(NodePort port) { } + + /// Disconnect everything from this node + public void ClearConnections() { + foreach (NodePort port in Ports) + { + port.ClearConnections(); + } + } + +#region Attributes + /// Mark a serializable field as an input port. You can access this through + [AttributeUsage(AttributeTargets.Field)] + public class InputAttribute : Attribute { + public ShowBackingValue backingValue; + public ConnectionType connectionType; + [Obsolete("Use dynamicPortList instead")] + public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } } + public bool dynamicPortList; + public TypeConstraint typeConstraint; + + /// Mark a serializable field as an input port. You can access this through + /// Should we display the backing value for this port as an editor field? + /// Should we allow multiple connections? + /// Constrains which input connections can be made to this port + /// If true, will display a reorderable list of inputs instead of a single port. Will automatically add and display values for lists and arrays + public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) { + this.backingValue = backingValue; + this.connectionType = connectionType; + this.dynamicPortList = dynamicPortList; + this.typeConstraint = typeConstraint; + } + } + + /// Mark a serializable field as an output port. You can access this through + [AttributeUsage(AttributeTargets.Field)] + public class OutputAttribute : Attribute { + public ShowBackingValue backingValue; + public ConnectionType connectionType; + [Obsolete("Use dynamicPortList instead")] + public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } } + public bool dynamicPortList; + public TypeConstraint typeConstraint; + + /// Mark a serializable field as an output port. You can access this through + /// Should we display the backing value for this port as an editor field? + /// Should we allow multiple connections? + /// Constrains which input connections can be made from this port + /// If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays + public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) { + this.backingValue = backingValue; + this.connectionType = connectionType; + this.dynamicPortList = dynamicPortList; + this.typeConstraint = typeConstraint; + } + + /// Mark a serializable field as an output port. You can access this through + /// Should we display the backing value for this port as an editor field? + /// Should we allow multiple connections? + /// If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays + [Obsolete("Use constructor with TypeConstraint")] + public OutputAttribute(ShowBackingValue backingValue, ConnectionType connectionType, bool dynamicPortList) : this(backingValue, connectionType, TypeConstraint.None, dynamicPortList) { } + } + + /// Manually supply node class with a context menu path + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class CreateNodeMenuAttribute : Attribute { + public string menuName; + public int order; + /// Manually supply node class with a context menu path + /// Path to this node in the context menu. Null or empty hides it. + public CreateNodeMenuAttribute(string menuName) { + this.menuName = menuName; + this.order = 0; + } + + /// Manually supply node class with a context menu path + /// Path to this node in the context menu. Null or empty hides it. + /// The order by which the menu items are displayed. + public CreateNodeMenuAttribute(string menuName, int order) { + this.menuName = menuName; + this.order = order; + } + } + + /// Prevents Node of the same type to be added more than once (configurable) to a NodeGraph + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class DisallowMultipleNodesAttribute : Attribute { + // TODO: Make inheritance work in such a way that applying [DisallowMultipleNodes(1)] to type NodeBar : Node + // while type NodeFoo : NodeBar exists, will let you add *either one* of these nodes, but not both. + public int max; + /// Prevents Node of the same type to be added more than once (configurable) to a NodeGraph + /// How many nodes to allow. Defaults to 1. + public DisallowMultipleNodesAttribute(int max = 1) { + this.max = max; + } + } + + /// Specify a color for this node type + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class NodeTintAttribute : Attribute { + public Color color; + /// Specify a color for this node type + /// Red [0.0f .. 1.0f] + /// Green [0.0f .. 1.0f] + /// Blue [0.0f .. 1.0f] + public NodeTintAttribute(float r, float g, float b) { + color = new Color(r, g, b); + } + + /// Specify a color for this node type + /// HEX color value + public NodeTintAttribute(string hex) { + ColorUtility.TryParseHtmlString(hex, out color); + } + + /// Specify a color for this node type + /// Red [0 .. 255] + /// Green [0 .. 255] + /// Blue [0 .. 255] + public NodeTintAttribute(byte r, byte g, byte b) { + color = new Color32(r, g, b, byte.MaxValue); + } + } + + /// Specify a width for this node type + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class NodeWidthAttribute : Attribute { + public int width; + /// Specify a width for this node type + /// Width + public NodeWidthAttribute(int width) { + this.width = width; + } + } +#endregion + + [Serializable] private class NodePortDictionary : Dictionary, ISerializationCallbackReceiver { + [SerializeField] private List keys = new List(); + [SerializeField] private List values = new List(); + + public void OnBeforeSerialize() { + keys.Clear(); + values.Clear(); + keys.Capacity = this.Count; + values.Capacity = this.Count; + foreach (KeyValuePair pair in this) { + keys.Add(pair.Key); + values.Add(pair.Value); + } + } + + public void OnAfterDeserialize() { + this.Clear(); +#if UNITY_2021_3_OR_NEWER + this.EnsureCapacity(keys.Count); +#endif + + if (keys.Count != values.Count) + { + throw new System.Exception("there are " + keys.Count + " keys and " + values.Count + " values after deserialization. Make sure that both key and value types are serializable."); + } + + for (var i = 0; i < keys.Count; i++) + { + this.Add(keys[i], values[i]); + } + } + } + } +} diff --git a/Scripts/Node.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/Node.cs.meta similarity index 100% rename from Scripts/Node.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/Node.cs.meta diff --git a/Scripts/NodeDataCache.cs b/xNode/Packages/com.pillow.xnode/Runtime/NodeDataCache.cs similarity index 75% rename from Scripts/NodeDataCache.cs rename to xNode/Packages/com.pillow.xnode/Runtime/NodeDataCache.cs index 4f4937d..46197f7 100644 --- a/Scripts/NodeDataCache.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/NodeDataCache.cs @@ -12,8 +12,11 @@ namespace XNode { private static bool Initialized { get { return portDataCache != null; } } public static string GetTypeQualifiedName(System.Type type) { - if(typeQualifiedNameCache == null) typeQualifiedNameCache = new Dictionary(); - + if(typeQualifiedNameCache == null) + { + typeQualifiedNameCache = new Dictionary(); + } + string name; if (!typeQualifiedNameCache.TryGetValue(type, out name)) { name = type.AssemblyQualifiedName; @@ -24,13 +27,19 @@ namespace XNode { /// Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. public static void UpdatePorts(Node node, Dictionary ports) { - if (!Initialized) BuildCache(); + if (!Initialized) + { + BuildCache(); + } Dictionary> removedPorts = new Dictionary>(); System.Type nodeType = node.GetType(); Dictionary formerlySerializedAs = null; - if (formerlySerializedAsCache != null) formerlySerializedAsCache.TryGetValue(nodeType, out formerlySerializedAs); + if (formerlySerializedAsCache != null) + { + formerlySerializedAsCache.TryGetValue(nodeType, out formerlySerializedAs); + } List dynamicListPorts = new List(); @@ -49,17 +58,27 @@ namespace XNode { // If port exists but with wrong settings, remove it. Re-add it later. if (port.IsDynamic || port.direction != staticPort.direction || port.connectionType != staticPort.connectionType || port.typeConstraint != staticPort.typeConstraint) { // If port is not dynamic and direction hasn't changed, add it to the list so we can try reconnecting the ports connections. - if (!port.IsDynamic && port.direction == staticPort.direction) removedPorts.Add(port.fieldName, port.GetConnections()); + if (!port.IsDynamic && port.direction == staticPort.direction) + { + removedPorts.Add(port.fieldName, port.GetConnections()); + } + port.ClearConnections(); ports.Remove(port.fieldName); - } else port.ValueType = staticPort.ValueType; + } else + { + port.ValueType = staticPort.ValueType; + } } // If port doesn't exist anymore, remove it else if (port.IsStatic) { //See if the field is tagged with FormerlySerializedAs, if so add the port with its new field name to removedPorts // so it can be reconnected in missing ports stage. string newName = null; - if (formerlySerializedAs != null && formerlySerializedAs.TryGetValue(port.fieldName, out newName)) removedPorts.Add(newName, port.GetConnections()); + if (formerlySerializedAs != null && formerlySerializedAs.TryGetValue(port.fieldName, out newName)) + { + removedPorts.Add(newName, port.GetConnections()); + } port.ClearConnections(); ports.Remove(port.fieldName); @@ -76,13 +95,20 @@ namespace XNode { //If we just removed the port, try re-adding the connections List reconnectConnections; if (removedPorts.TryGetValue(staticPort.fieldName, out reconnectConnections)) { - for (int i = 0; i < reconnectConnections.Count; i++) { + for (var i = 0; i < reconnectConnections.Count; i++) { NodePort connection = reconnectConnections[i]; - if (connection == null) continue; + if (connection == null) + { + continue; + } + // CAVEAT: Ports connected under special conditions defined in graphEditor.CanConnect overrides will not auto-connect. // To fix this, this code would need to be moved to an editor script and call graphEditor.CanConnect instead of port.CanConnectTo. // This is only a problem in the rare edge case where user is using non-standard CanConnect overrides and changes port type of an already connected port - if (port.CanConnectTo(connection)) port.Connect(connection); + if (port.CanConnectTo(connection)) + { + port.Connect(connection); + } } } ports.Add(staticPort.fieldName, port); @@ -93,7 +119,7 @@ namespace XNode { foreach (NodePort listPort in dynamicListPorts) { // At this point we know that ports here are dynamic list ports // which have passed name/"backing port" checks, ergo we can proceed more safely. - string backingPortName = listPort.fieldName.Substring(0, listPort.fieldName.IndexOf(' ')); + var backingPortName = listPort.fieldName.Substring(0, listPort.fieldName.IndexOf(' ')); NodePort backingPort = staticPorts[backingPortName]; // Update port constraints. Creating a new port instead will break the editor, mandating the need for setters. @@ -124,13 +150,19 @@ namespace XNode { // Ports flagged as "dynamicPortList = true" end up having a "backing port" and a name with an index, but we have // no guarantee that a dynamic port called "output 0" is an element in a list backed by a static "output" port. // Thus, we need to check for attributes... (but at least we don't need to look at all fields this time) - string[] fieldNameParts = port.fieldName.Split(' '); - if (fieldNameParts.Length != 2) return false; + var fieldNameParts = port.fieldName.Split(' '); + if (fieldNameParts.Length != 2) + { + return false; + } FieldInfo backingPortInfo = port.node.GetType().GetField(fieldNameParts[0]); - if (backingPortInfo == null) return false; + if (backingPortInfo == null) + { + return false; + } - object[] attribs = backingPortInfo.GetCustomAttributes(true); + var attribs = backingPortInfo.GetCustomAttributes(true); return attribs.Any(x => { Node.InputAttribute inputAttribute = x as Node.InputAttribute; Node.OutputAttribute outputAttribute = x as Node.OutputAttribute; @@ -149,9 +181,13 @@ namespace XNode { // Loop through assemblies and add node types to list foreach (Assembly assembly in assemblies) { // Skip certain dlls to improve performance - string assemblyName = assembly.GetName().Name; - int index = assemblyName.IndexOf('.'); - if (index != -1) assemblyName = assemblyName.Substring(0, index); + var assemblyName = assembly.GetName().Name; + var index = assemblyName.IndexOf('.'); + if (index != -1) + { + assemblyName = assemblyName.Substring(0, index); + } + switch (assemblyName) { // The following assemblies, and sub-assemblies (eg. UnityEngine.UI) are skipped case "UnityEditor": @@ -167,7 +203,7 @@ namespace XNode { } } - for (int i = 0; i < nodeTypes.Count; i++) { + for (var i = 0; i < nodeTypes.Count; i++) { CachePorts(nodeTypes[i]); } } @@ -179,7 +215,7 @@ namespace XNode { System.Type tempType = nodeType; while ((tempType = tempType.BaseType) != typeof(XNode.Node)) { FieldInfo[] parentFields = tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); - for (int i = 0; i < parentFields.Length; i++) { + for (var i = 0; i < parentFields.Length; i++) { // Ensure that we do not already have a member with this type and name FieldInfo parentField = parentFields[i]; if (fieldInfo.TrueForAll(x => x.Name != parentField.Name)) { @@ -193,29 +229,52 @@ namespace XNode { private static void CachePorts(System.Type nodeType) { List fieldInfo = GetNodeFields(nodeType); - for (int i = 0; i < fieldInfo.Count; i++) { + for (var i = 0; i < fieldInfo.Count; i++) { //Get InputAttribute and OutputAttribute - object[] attribs = fieldInfo[i].GetCustomAttributes(true); + var attribs = fieldInfo[i].GetCustomAttributes(true); Node.InputAttribute inputAttrib = attribs.FirstOrDefault(x => x is Node.InputAttribute) as Node.InputAttribute; Node.OutputAttribute outputAttrib = attribs.FirstOrDefault(x => x is Node.OutputAttribute) as Node.OutputAttribute; UnityEngine.Serialization.FormerlySerializedAsAttribute formerlySerializedAsAttribute = attribs.FirstOrDefault(x => x is UnityEngine.Serialization.FormerlySerializedAsAttribute) as UnityEngine.Serialization.FormerlySerializedAsAttribute; - if (inputAttrib == null && outputAttrib == null) continue; + if (inputAttrib == null && outputAttrib == null) + { + continue; + } - if (inputAttrib != null && outputAttrib != null) Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName + " cannot be both input and output."); + if (inputAttrib != null && outputAttrib != null) + { + Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName + " cannot be both input and output."); + } else { - if (!portDataCache.ContainsKey(nodeType)) portDataCache.Add(nodeType, new Dictionary()); - NodePort port = new NodePort(fieldInfo[i]); + if (!portDataCache.ContainsKey(nodeType)) + { + portDataCache.Add(nodeType, new Dictionary()); + } + + NodePort port = new NodePort(fieldInfo[i]); portDataCache[nodeType].Add(port.fieldName, port); } if (formerlySerializedAsAttribute != null) { - if (formerlySerializedAsCache == null) formerlySerializedAsCache = new Dictionary>(); - if (!formerlySerializedAsCache.ContainsKey(nodeType)) formerlySerializedAsCache.Add(nodeType, new Dictionary()); + if (formerlySerializedAsCache == null) + { + formerlySerializedAsCache = new Dictionary>(); + } - if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName)) Debug.LogError("Another FormerlySerializedAs with value '" + formerlySerializedAsAttribute.oldName + "' already exist on this node."); - else formerlySerializedAsCache[nodeType].Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name); + if (!formerlySerializedAsCache.ContainsKey(nodeType)) + { + formerlySerializedAsCache.Add(nodeType, new Dictionary()); + } + + if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName)) + { + Debug.LogError("Another FormerlySerializedAs with value '" + formerlySerializedAsAttribute.oldName + "' already exist on this node."); + } + else + { + formerlySerializedAsCache[nodeType].Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name); + } } } } diff --git a/Scripts/NodeDataCache.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/NodeDataCache.cs.meta similarity index 100% rename from Scripts/NodeDataCache.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/NodeDataCache.cs.meta diff --git a/Scripts/NodeGraph.cs b/xNode/Packages/com.pillow.xnode/Runtime/NodeGraph.cs similarity index 79% rename from Scripts/NodeGraph.cs rename to xNode/Packages/com.pillow.xnode/Runtime/NodeGraph.cs index 347bc8e..ee1e67a 100644 --- a/Scripts/NodeGraph.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/NodeGraph.cs @@ -1,124 +1,152 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace XNode { - /// Base class for all node graphs - [Serializable] - public abstract class NodeGraph : ScriptableObject { - - /// All nodes in the graph. - /// See: - [SerializeField] public List nodes = new List(); - - /// Add a node to the graph by type (convenience method - will call the System.Type version) - public T AddNode() where T : Node { - return AddNode(typeof(T)) as T; - } - - /// Add a node to the graph by type - public virtual Node AddNode(Type type) { - Node.graphHotfix = this; - Node node = ScriptableObject.CreateInstance(type) as Node; - node.graph = this; - nodes.Add(node); - return node; - } - - /// Creates a copy of the original node in the graph - public virtual Node CopyNode(Node original) { - Node.graphHotfix = this; - Node node = ScriptableObject.Instantiate(original); - node.graph = this; - node.ClearConnections(); - nodes.Add(node); - return node; - } - - /// Safely remove a node and all its connections - /// The node to remove - public virtual void RemoveNode(Node node) { - node.ClearConnections(); - nodes.Remove(node); - if (Application.isPlaying) Destroy(node); - } - - /// Remove all nodes and connections from the graph - public virtual void Clear() { - if (Application.isPlaying) { - for (int i = 0; i < nodes.Count; i++) { - if (nodes[i] != null) Destroy(nodes[i]); - } - } - nodes.Clear(); - } - - /// Create a new deep copy of this graph - public virtual XNode.NodeGraph Copy() { - // Instantiate a new nodegraph instance - NodeGraph graph = Instantiate(this); - // Instantiate all nodes inside the graph - for (int i = 0; i < nodes.Count; i++) { - if (nodes[i] == null) continue; - Node.graphHotfix = graph; - Node node = Instantiate(nodes[i]) as Node; - node.graph = graph; - graph.nodes[i] = node; - } - - // Redirect all connections - for (int i = 0; i < graph.nodes.Count; i++) { - if (graph.nodes[i] == null) continue; - foreach (NodePort port in graph.nodes[i].Ports) { - port.Redirect(nodes, graph.nodes); - } - } - - return graph; - } - - protected virtual void OnDestroy() { - // Remove all nodes prior to graph destruction - Clear(); - } - -#region Attributes - /// Automatically ensures the existance of a certain node type, and prevents it from being deleted. - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - public class RequireNodeAttribute : Attribute { - public Type type0; - public Type type1; - public Type type2; - - /// Automatically ensures the existance of a certain node type, and prevents it from being deleted - public RequireNodeAttribute(Type type) { - this.type0 = type; - this.type1 = null; - this.type2 = null; - } - - /// Automatically ensures the existance of a certain node type, and prevents it from being deleted - public RequireNodeAttribute(Type type, Type type2) { - this.type0 = type; - this.type1 = type2; - this.type2 = null; - } - - /// Automatically ensures the existance of a certain node type, and prevents it from being deleted - public RequireNodeAttribute(Type type, Type type2, Type type3) { - this.type0 = type; - this.type1 = type2; - this.type2 = type3; - } - - public bool Requires(Type type) { - if (type == null) return false; - if (type == type0) return true; - else if (type == type1) return true; - else if (type == type2) return true; - return false; - } - } -#endregion - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace XNode { + /// Base class for all node graphs + [Serializable] + public abstract class NodeGraph : ScriptableObject { + + /// All nodes in the graph. + /// See: + [SerializeField] public List nodes = new List(); + + /// Add a node to the graph by type (convenience method - will call the System.Type version) + public T AddNode() where T : Node { + return AddNode(typeof(T)) as T; + } + + /// Add a node to the graph by type + public virtual Node AddNode(Type type) { + Node.graphHotfix = this; + Node node = ScriptableObject.CreateInstance(type) as Node; + node.graph = this; + nodes.Add(node); + return node; + } + + /// Creates a copy of the original node in the graph + public virtual Node CopyNode(Node original) { + Node.graphHotfix = this; + Node node = ScriptableObject.Instantiate(original); + node.graph = this; + node.ClearConnections(); + nodes.Add(node); + return node; + } + + /// Safely remove a node and all its connections + /// The node to remove + public virtual void RemoveNode(Node node) { + node.ClearConnections(); + nodes.Remove(node); + if (Application.isPlaying) + { + Destroy(node); + } + } + + /// Remove all nodes and connections from the graph + public virtual void Clear() { + if (Application.isPlaying) { + for (var i = 0; i < nodes.Count; i++) { + if (nodes[i] != null) + { + Destroy(nodes[i]); + } + } + } + nodes.Clear(); + } + + /// Create a new deep copy of this graph + public virtual XNode.NodeGraph Copy() { + // Instantiate a new nodegraph instance + NodeGraph graph = Instantiate(this); + // Instantiate all nodes inside the graph + for (var i = 0; i < nodes.Count; i++) { + if (nodes[i] == null) + { + continue; + } + + Node.graphHotfix = graph; + Node node = Instantiate(nodes[i]) as Node; + node.graph = graph; + graph.nodes[i] = node; + } + + // Redirect all connections + for (var i = 0; i < graph.nodes.Count; i++) { + if (graph.nodes[i] == null) + { + continue; + } + + foreach (NodePort port in graph.nodes[i].Ports) { + port.Redirect(nodes, graph.nodes); + } + } + + return graph; + } + + protected virtual void OnDestroy() { + // Remove all nodes prior to graph destruction + Clear(); + } + +#region Attributes + /// Automatically ensures the existance of a certain node type, and prevents it from being deleted. + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + public class RequireNodeAttribute : Attribute { + public Type type0; + public Type type1; + public Type type2; + + /// Automatically ensures the existance of a certain node type, and prevents it from being deleted + public RequireNodeAttribute(Type type) { + this.type0 = type; + this.type1 = null; + this.type2 = null; + } + + /// Automatically ensures the existance of a certain node type, and prevents it from being deleted + public RequireNodeAttribute(Type type, Type type2) { + this.type0 = type; + this.type1 = type2; + this.type2 = null; + } + + /// Automatically ensures the existance of a certain node type, and prevents it from being deleted + public RequireNodeAttribute(Type type, Type type2, Type type3) { + this.type0 = type; + this.type1 = type2; + this.type2 = type3; + } + + public bool Requires(Type type) { + if (type == null) + { + return false; + } + + if (type == type0) + { + return true; + } + else if (type == type1) + { + return true; + } + else if (type == type2) + { + return true; + } + + return false; + } + } +#endregion + } +} diff --git a/Scripts/NodeGraph.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/NodeGraph.cs.meta similarity index 100% rename from Scripts/NodeGraph.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/NodeGraph.cs.meta diff --git a/Scripts/NodePort.cs b/xNode/Packages/com.pillow.xnode/Runtime/NodePort.cs similarity index 74% rename from Scripts/NodePort.cs rename to xNode/Packages/com.pillow.xnode/Runtime/NodePort.cs index 1fbc62f..4e3cdbf 100644 --- a/Scripts/NodePort.cs +++ b/xNode/Packages/com.pillow.xnode/Runtime/NodePort.cs @@ -1,422 +1,552 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using UnityEngine; - -namespace XNode { - [Serializable] - public class NodePort { - public enum IO { Input, Output } - - public int ConnectionCount { get { return connections.Count; } } - /// Return the first non-null connection - public NodePort Connection { - get { - for (int i = 0; i < connections.Count; i++) { - if (connections[i] != null) return connections[i].Port; - } - return null; - } - } - - public IO direction { - get { return _direction; } - internal set { _direction = value; } - } - public Node.ConnectionType connectionType { - get { return _connectionType; } - internal set { _connectionType = value; } - } - public Node.TypeConstraint typeConstraint { - get { return _typeConstraint; } - internal set { _typeConstraint = value; } - } - - /// Is this port connected to anytihng? - public bool IsConnected { get { return connections.Count != 0; } } - public bool IsInput { get { return direction == IO.Input; } } - public bool IsOutput { get { return direction == IO.Output; } } - - public string fieldName { get { return _fieldName; } } - public Node node { get { return _node; } } - public bool IsDynamic { get { return _dynamic; } } - public bool IsStatic { get { return !_dynamic; } } - public Type ValueType { - get { - if (valueType == null && !string.IsNullOrEmpty(_typeQualifiedName)) valueType = Type.GetType(_typeQualifiedName, false); - return valueType; - } - set { - if (valueType == value) return; - valueType = value; - if (value != null) _typeQualifiedName = NodeDataCache.GetTypeQualifiedName(value); - } - } - private Type valueType; - - [SerializeField] private string _fieldName; - [SerializeField] private Node _node; - [SerializeField] private string _typeQualifiedName; - [SerializeField] private List connections = new List(); - [SerializeField] private IO _direction; - [SerializeField] private Node.ConnectionType _connectionType; - [SerializeField] private Node.TypeConstraint _typeConstraint; - [SerializeField] private bool _dynamic; - - /// Construct a static targetless nodeport. Used as a template. - public NodePort(FieldInfo fieldInfo) { - _fieldName = fieldInfo.Name; - ValueType = fieldInfo.FieldType; - _dynamic = false; - var attribs = fieldInfo.GetCustomAttributes(false); - for (int i = 0; i < attribs.Length; i++) { - if (attribs[i] is Node.InputAttribute) { - _direction = IO.Input; - _connectionType = (attribs[i] as Node.InputAttribute).connectionType; - _typeConstraint = (attribs[i] as Node.InputAttribute).typeConstraint; - } else if (attribs[i] is Node.OutputAttribute) { - _direction = IO.Output; - _connectionType = (attribs[i] as Node.OutputAttribute).connectionType; - _typeConstraint = (attribs[i] as Node.OutputAttribute).typeConstraint; - } - // Override ValueType of the Port - if(attribs[i] is PortTypeOverrideAttribute) { - ValueType = (attribs[i] as PortTypeOverrideAttribute).type; - } - } - } - - /// Copy a nodePort but assign it to another node. - public NodePort(NodePort nodePort, Node node) { - _fieldName = nodePort._fieldName; - ValueType = nodePort.valueType; - _direction = nodePort.direction; - _dynamic = nodePort._dynamic; - _connectionType = nodePort._connectionType; - _typeConstraint = nodePort._typeConstraint; - _node = node; - } - - /// Construct a dynamic port. Dynamic ports are not forgotten on reimport, and is ideal for runtime-created ports. - public NodePort(string fieldName, Type type, IO direction, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Node node) { - _fieldName = fieldName; - this.ValueType = type; - _direction = direction; - _node = node; - _dynamic = true; - _connectionType = connectionType; - _typeConstraint = typeConstraint; - } - - /// Checks all connections for invalid references, and removes them. - public void VerifyConnections() { - for (int i = connections.Count - 1; i >= 0; i--) { - if (connections[i].node != null && - !string.IsNullOrEmpty(connections[i].fieldName) && - connections[i].node.GetPort(connections[i].fieldName) != null) - continue; - connections.RemoveAt(i); - } - } - - /// Return the output value of this node through its parent nodes GetValue override method. - /// - public object GetOutputValue() { - if (direction == IO.Input) return null; - return node.GetValue(this); - } - - /// Return the output value of the first connected port. Returns null if none found or invalid. - /// - public object GetInputValue() { - NodePort connectedPort = Connection; - if (connectedPort == null) return null; - return connectedPort.GetOutputValue(); - } - - /// Return the output values of all connected ports. - /// - public object[] GetInputValues() { - object[] objs = new object[ConnectionCount]; - for (int i = 0; i < ConnectionCount; i++) { - NodePort connectedPort = connections[i].Port; - if (connectedPort == null) { // if we happen to find a null port, remove it and look again - connections.RemoveAt(i); - i--; - continue; - } - objs[i] = connectedPort.GetOutputValue(); - } - return objs; - } - - /// Return the output value of the first connected port. Returns null if none found or invalid. - /// - public T GetInputValue() { - object obj = GetInputValue(); - return obj is T ? (T) obj : default(T); - } - - /// Return the output values of all connected ports. - /// - public T[] GetInputValues() { - object[] objs = GetInputValues(); - T[] ts = new T[objs.Length]; - for (int i = 0; i < objs.Length; i++) { - if (objs[i] is T) ts[i] = (T) objs[i]; - } - return ts; - } - - /// Return true if port is connected and has a valid input. - /// - public bool TryGetInputValue(out T value) { - object obj = GetInputValue(); - if (obj is T) { - value = (T) obj; - return true; - } else { - value = default(T); - return false; - } - } - - /// Return the sum of all inputs. - /// - public float GetInputSum(float fallback) { - object[] objs = GetInputValues(); - if (objs.Length == 0) return fallback; - float result = 0; - for (int i = 0; i < objs.Length; i++) { - if (objs[i] is float) result += (float) objs[i]; - } - return result; - } - - /// Return the sum of all inputs. - /// - public int GetInputSum(int fallback) { - object[] objs = GetInputValues(); - if (objs.Length == 0) return fallback; - int result = 0; - for (int i = 0; i < objs.Length; i++) { - if (objs[i] is int) result += (int) objs[i]; - } - return result; - } - - /// Connect this to another - /// The to connect to - public void Connect(NodePort port) { - if (connections == null) connections = new List(); - if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; } - if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; } - if (IsConnectedTo(port)) { Debug.LogWarning("Port already connected. "); return; } - if (direction == port.direction) { Debug.LogWarning("Cannot connect two " + (direction == IO.Input ? "input" : "output") + " connections"); return; } -#if UNITY_EDITOR - UnityEditor.Undo.RecordObject(node, "Connect Port"); - UnityEditor.Undo.RecordObject(port.node, "Connect Port"); -#endif - if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); } - if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); } - connections.Add(new PortConnection(port)); - if (port.connections == null) port.connections = new List(); - if (!port.IsConnectedTo(this)) port.connections.Add(new PortConnection(this)); - node.OnCreateConnection(this, port); - port.node.OnCreateConnection(this, port); - } - - public List GetConnections() { - List result = new List(); - for (int i = 0; i < connections.Count; i++) { - NodePort port = GetConnection(i); - if (port != null) result.Add(port); - } - return result; - } - - public NodePort GetConnection(int i) { - //If the connection is broken for some reason, remove it. - if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) { - connections.RemoveAt(i); - return null; - } - NodePort port = connections[i].node.GetPort(connections[i].fieldName); - if (port == null) { - connections.RemoveAt(i); - return null; - } - return port; - } - - /// Get index of the connection connecting this and specified ports - public int GetConnectionIndex(NodePort port) { - for (int i = 0; i < ConnectionCount; i++) { - if (connections[i].Port == port) return i; - } - return -1; - } - - public bool IsConnectedTo(NodePort port) { - for (int i = 0; i < connections.Count; i++) { - if (connections[i].Port == port) return true; - } - return false; - } - - /// Returns true if this port can connect to specified port - public bool CanConnectTo(NodePort port) { - // Figure out which is input and which is output - NodePort input = null, output = null; - if (IsInput) input = this; - else output = this; - if (port.IsInput) input = port; - else output = port; - // If there isn't one of each, they can't connect - if (input == null || output == null) return false; - // Check input type constraints - if (input.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false; - if (input.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false; - if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false; - if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) return false; - // Check output type constraints - if (output.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false; - if (output.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false; - if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false; - if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) return false; - // Success - return true; - } - - /// Disconnect this port from another port - public void Disconnect(NodePort port) { - // Remove this ports connection to the other - for (int i = connections.Count - 1; i >= 0; i--) { - if (connections[i].Port == port) { - connections.RemoveAt(i); - } - } - if (port != null) { - // Remove the other ports connection to this port - for (int i = 0; i < port.connections.Count; i++) { - if (port.connections[i].Port == this) { - port.connections.RemoveAt(i); - // Trigger OnRemoveConnection from this side port - port.node.OnRemoveConnection(port); - } - } - } - // Trigger OnRemoveConnection - node.OnRemoveConnection(this); - } - - /// Disconnect this port from another port - public void Disconnect(int i) { - // Remove the other ports connection to this port - NodePort otherPort = connections[i].Port; - if (otherPort != null) { - otherPort.connections.RemoveAll(it => { return it.Port == this; }); - } - // Remove this ports connection to the other - connections.RemoveAt(i); - - // Trigger OnRemoveConnection - node.OnRemoveConnection(this); - if (otherPort != null) otherPort.node.OnRemoveConnection(otherPort); - } - - public void ClearConnections() { - while (connections.Count > 0) { - Disconnect(connections[0].Port); - } - } - - /// Get reroute points for a given connection. This is used for organization - public List GetReroutePoints(int index) { - return connections[index].reroutePoints; - } - - /// Swap connections with another node - public void SwapConnections(NodePort targetPort) { - int aConnectionCount = connections.Count; - int bConnectionCount = targetPort.connections.Count; - - List portConnections = new List(); - List targetPortConnections = new List(); - - // Cache port connections - for (int i = 0; i < aConnectionCount; i++) - portConnections.Add(connections[i].Port); - - // Cache target port connections - for (int i = 0; i < bConnectionCount; i++) - targetPortConnections.Add(targetPort.connections[i].Port); - - ClearConnections(); - targetPort.ClearConnections(); - - // Add port connections to targetPort - for (int i = 0; i < portConnections.Count; i++) - targetPort.Connect(portConnections[i]); - - // Add target port connections to this one - for (int i = 0; i < targetPortConnections.Count; i++) - Connect(targetPortConnections[i]); - - } - - /// Copy all connections pointing to a node and add them to this one - public void AddConnections(NodePort targetPort) { - int connectionCount = targetPort.ConnectionCount; - for (int i = 0; i < connectionCount; i++) { - PortConnection connection = targetPort.connections[i]; - NodePort otherPort = connection.Port; - Connect(otherPort); - } - } - - /// Move all connections pointing to this node, to another node - public void MoveConnections(NodePort targetPort) { - int connectionCount = connections.Count; - - // Add connections to target port - for (int i = 0; i < connectionCount; i++) { - PortConnection connection = targetPort.connections[i]; - NodePort otherPort = connection.Port; - Connect(otherPort); - } - ClearConnections(); - } - - /// Swap connected nodes from the old list with nodes from the new list - public void Redirect(List oldNodes, List newNodes) { - foreach (PortConnection connection in connections) { - int index = oldNodes.IndexOf(connection.node); - if (index >= 0) connection.node = newNodes[index]; - } - } - - [Serializable] - private class PortConnection { - [SerializeField] public string fieldName; - [SerializeField] public Node node; - public NodePort Port { get { return port != null ? port : port = GetPort(); } } - - [NonSerialized] private NodePort port; - /// Extra connection path points for organization - [SerializeField] public List reroutePoints = new List(); - - public PortConnection(NodePort port) { - this.port = port; - node = port.node; - fieldName = port.fieldName; - } - - /// Returns the port that this points to - private NodePort GetPort() { - if (node == null || string.IsNullOrEmpty(fieldName)) return null; - return node.GetPort(fieldName); - } - } - } -} +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; + +namespace XNode { + [Serializable] + public class NodePort { + public enum IO { Input, Output } + + public int ConnectionCount { get { return connections.Count; } } + /// Return the first non-null connection + public NodePort Connection { + get { + for (var i = 0; i < connections.Count; i++) { + if (connections[i] != null) + { + return connections[i].Port; + } + } + return null; + } + } + + public IO direction { + get { return _direction; } + internal set { _direction = value; } + } + public Node.ConnectionType connectionType { + get { return _connectionType; } + internal set { _connectionType = value; } + } + public Node.TypeConstraint typeConstraint { + get { return _typeConstraint; } + internal set { _typeConstraint = value; } + } + + /// Is this port connected to anytihng? + public bool IsConnected { get { return connections.Count != 0; } } + public bool IsInput { get { return direction == IO.Input; } } + public bool IsOutput { get { return direction == IO.Output; } } + + public string fieldName { get { return _fieldName; } } + public Node node { get { return _node; } } + public bool IsDynamic { get { return _dynamic; } } + public bool IsStatic { get { return !_dynamic; } } + public Type ValueType { + get { + if (valueType == null && !string.IsNullOrEmpty(_typeQualifiedName)) + { + valueType = Type.GetType(_typeQualifiedName, false); + } + + return valueType; + } + set { + if (valueType == value) + { + return; + } + + valueType = value; + if (value != null) + { + _typeQualifiedName = NodeDataCache.GetTypeQualifiedName(value); + } + } + } + private Type valueType; + + [SerializeField] private string _fieldName; + [SerializeField] private Node _node; + [SerializeField] private string _typeQualifiedName; + [SerializeField] private List connections = new List(); + [SerializeField] private IO _direction; + [SerializeField] private Node.ConnectionType _connectionType; + [SerializeField] private Node.TypeConstraint _typeConstraint; + [SerializeField] private bool _dynamic; + + /// Construct a static targetless nodeport. Used as a template. + public NodePort(FieldInfo fieldInfo) { + _fieldName = fieldInfo.Name; + ValueType = fieldInfo.FieldType; + _dynamic = false; + var attribs = fieldInfo.GetCustomAttributes(false); + for (var i = 0; i < attribs.Length; i++) { + if (attribs[i] is Node.InputAttribute) { + _direction = IO.Input; + _connectionType = (attribs[i] as Node.InputAttribute).connectionType; + _typeConstraint = (attribs[i] as Node.InputAttribute).typeConstraint; + } else if (attribs[i] is Node.OutputAttribute) { + _direction = IO.Output; + _connectionType = (attribs[i] as Node.OutputAttribute).connectionType; + _typeConstraint = (attribs[i] as Node.OutputAttribute).typeConstraint; + } + // Override ValueType of the Port + if(attribs[i] is PortTypeOverrideAttribute) { + ValueType = (attribs[i] as PortTypeOverrideAttribute).type; + } + } + } + + /// Copy a nodePort but assign it to another node. + public NodePort(NodePort nodePort, Node node) { + _fieldName = nodePort._fieldName; + ValueType = nodePort.valueType; + _direction = nodePort.direction; + _dynamic = nodePort._dynamic; + _connectionType = nodePort._connectionType; + _typeConstraint = nodePort._typeConstraint; + _node = node; + } + + /// Construct a dynamic port. Dynamic ports are not forgotten on reimport, and is ideal for runtime-created ports. + public NodePort(string fieldName, Type type, IO direction, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Node node) { + _fieldName = fieldName; + this.ValueType = type; + _direction = direction; + _node = node; + _dynamic = true; + _connectionType = connectionType; + _typeConstraint = typeConstraint; + } + + /// Checks all connections for invalid references, and removes them. + public void VerifyConnections() { + for (var i = connections.Count - 1; i >= 0; i--) { + if (connections[i].node != null && + !string.IsNullOrEmpty(connections[i].fieldName) && + connections[i].node.GetPort(connections[i].fieldName) != null) + { + continue; + } + + connections.RemoveAt(i); + } + } + + /// Return the output value of this node through its parent nodes GetValue override method. + /// + public object GetOutputValue() { + if (direction == IO.Input) + { + return null; + } + + return node.GetValue(this); + } + + /// Return the output value of the first connected port. Returns null if none found or invalid. + /// + public object GetInputValue() { + NodePort connectedPort = Connection; + if (connectedPort == null) + { + return null; + } + + return connectedPort.GetOutputValue(); + } + + /// Return the output values of all connected ports. + /// + public object[] GetInputValues() { + var objs = new object[ConnectionCount]; + for (var i = 0; i < ConnectionCount; i++) { + NodePort connectedPort = connections[i].Port; + if (connectedPort == null) { // if we happen to find a null port, remove it and look again + connections.RemoveAt(i); + i--; + continue; + } + objs[i] = connectedPort.GetOutputValue(); + } + return objs; + } + + /// Return the output value of the first connected port. Returns null if none found or invalid. + /// + public T GetInputValue() { + var obj = GetInputValue(); + return obj is T ? (T) obj : default(T); + } + + /// Return the output values of all connected ports. + /// + public T[] GetInputValues() { + var objs = GetInputValues(); + T[] ts = new T[objs.Length]; + for (var i = 0; i < objs.Length; i++) { + if (objs[i] is T) + { + ts[i] = (T) objs[i]; + } + } + return ts; + } + + /// Return true if port is connected and has a valid input. + /// + public bool TryGetInputValue(out T value) { + var obj = GetInputValue(); + if (obj is T) { + value = (T) obj; + return true; + } else { + value = default(T); + return false; + } + } + + /// Return the sum of all inputs. + /// + public float GetInputSum(float fallback) { + var objs = GetInputValues(); + if (objs.Length == 0) + { + return fallback; + } + + float result = 0; + for (var i = 0; i < objs.Length; i++) { + if (objs[i] is float) + { + result += (float) objs[i]; + } + } + return result; + } + + /// Return the sum of all inputs. + /// + public int GetInputSum(int fallback) { + var objs = GetInputValues(); + if (objs.Length == 0) + { + return fallback; + } + + var result = 0; + for (var i = 0; i < objs.Length; i++) { + if (objs[i] is int) + { + result += (int) objs[i]; + } + } + return result; + } + + /// Connect this to another + /// The to connect to + public void Connect(NodePort port) { + if (connections == null) + { + connections = new List(); + } + + if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; } + if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; } + if (IsConnectedTo(port)) { Debug.LogWarning("Port already connected. "); return; } + if (direction == port.direction) { Debug.LogWarning("Cannot connect two " + (direction == IO.Input ? "input" : "output") + " connections"); return; } +#if UNITY_EDITOR + UnityEditor.Undo.RecordObject(node, "Connect Port"); + UnityEditor.Undo.RecordObject(port.node, "Connect Port"); +#endif + if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); } + if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); } + connections.Add(new PortConnection(port)); + if (port.connections == null) + { + port.connections = new List(); + } + + if (!port.IsConnectedTo(this)) + { + port.connections.Add(new PortConnection(this)); + } + + node.OnCreateConnection(this, port); + port.node.OnCreateConnection(this, port); + } + + public List GetConnections() { + List result = new List(); + for (var i = 0; i < connections.Count; i++) { + NodePort port = GetConnection(i); + if (port != null) + { + result.Add(port); + } + } + return result; + } + + public NodePort GetConnection(int i) { + //If the connection is broken for some reason, remove it. + if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) { + connections.RemoveAt(i); + return null; + } + NodePort port = connections[i].node.GetPort(connections[i].fieldName); + if (port == null) { + connections.RemoveAt(i); + return null; + } + return port; + } + + /// Get index of the connection connecting this and specified ports + public int GetConnectionIndex(NodePort port) { + for (var i = 0; i < ConnectionCount; i++) { + if (connections[i].Port == port) + { + return i; + } + } + return -1; + } + + public bool IsConnectedTo(NodePort port) { + for (var i = 0; i < connections.Count; i++) { + if (connections[i].Port == port) + { + return true; + } + } + return false; + } + + /// Returns true if this port can connect to specified port + public bool CanConnectTo(NodePort port) { + // Figure out which is input and which is output + NodePort input = null, output = null; + if (IsInput) + { + input = this; + } + else + { + output = this; + } + + if (port.IsInput) + { + input = port; + } + else + { + output = port; + } + + // If there isn't one of each, they can't connect + if (input == null || output == null) + { + return false; + } + + // Check input type constraints + if (input.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) + { + return false; + } + + if (input.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) + { + return false; + } + + if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) + { + return false; + } + + if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) + { + return false; + } + + // Check output type constraints + if (output.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) + { + return false; + } + + if (output.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) + { + return false; + } + + if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) + { + return false; + } + + if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) + { + return false; + } + + // Success + return true; + } + + /// Disconnect this port from another port + public void Disconnect(NodePort port) { + // Remove this ports connection to the other + for (var i = connections.Count - 1; i >= 0; i--) { + if (connections[i].Port == port) { + connections.RemoveAt(i); + } + } + if (port != null) { + // Remove the other ports connection to this port + for (var i = 0; i < port.connections.Count; i++) { + if (port.connections[i].Port == this) { + port.connections.RemoveAt(i); + // Trigger OnRemoveConnection from this side port + port.node.OnRemoveConnection(port); + } + } + } + // Trigger OnRemoveConnection + node.OnRemoveConnection(this); + } + + /// Disconnect this port from another port + public void Disconnect(int i) { + // Remove the other ports connection to this port + NodePort otherPort = connections[i].Port; + if (otherPort != null) { + otherPort.connections.RemoveAll(it => { return it.Port == this; }); + } + // Remove this ports connection to the other + connections.RemoveAt(i); + + // Trigger OnRemoveConnection + node.OnRemoveConnection(this); + if (otherPort != null) + { + otherPort.node.OnRemoveConnection(otherPort); + } + } + + public void ClearConnections() { + while (connections.Count > 0) { + Disconnect(connections[0].Port); + } + } + + /// Get reroute points for a given connection. This is used for organization + public List GetReroutePoints(int index) { + return connections[index].reroutePoints; + } + + /// Swap connections with another node + public void SwapConnections(NodePort targetPort) { + var aConnectionCount = connections.Count; + var bConnectionCount = targetPort.connections.Count; + + List portConnections = new List(); + List targetPortConnections = new List(); + + // Cache port connections + for (var i = 0; i < aConnectionCount; i++) + { + portConnections.Add(connections[i].Port); + } + + // Cache target port connections + for (var i = 0; i < bConnectionCount; i++) + { + targetPortConnections.Add(targetPort.connections[i].Port); + } + + ClearConnections(); + targetPort.ClearConnections(); + + // Add port connections to targetPort + for (var i = 0; i < portConnections.Count; i++) + { + targetPort.Connect(portConnections[i]); + } + + // Add target port connections to this one + for (var i = 0; i < targetPortConnections.Count; i++) + { + Connect(targetPortConnections[i]); + } + } + + /// Copy all connections pointing to a node and add them to this one + public void AddConnections(NodePort targetPort) { + var connectionCount = targetPort.ConnectionCount; + for (var i = 0; i < connectionCount; i++) { + PortConnection connection = targetPort.connections[i]; + NodePort otherPort = connection.Port; + Connect(otherPort); + } + } + + /// Move all connections pointing to this node, to another node + public void MoveConnections(NodePort targetPort) { + var connectionCount = connections.Count; + + // Add connections to target port + for (var i = 0; i < connectionCount; i++) { + PortConnection connection = targetPort.connections[i]; + NodePort otherPort = connection.Port; + Connect(otherPort); + } + ClearConnections(); + } + + /// Swap connected nodes from the old list with nodes from the new list + public void Redirect(List oldNodes, List newNodes) { + foreach (PortConnection connection in connections) { + var index = oldNodes.IndexOf(connection.node); + if (index >= 0) + { + connection.node = newNodes[index]; + } + } + } + + [Serializable] + private class PortConnection { + [SerializeField] public string fieldName; + [SerializeField] public Node node; + public NodePort Port { get { return port != null ? port : port = GetPort(); } } + + [NonSerialized] private NodePort port; + /// Extra connection path points for organization + [SerializeField] public List reroutePoints = new List(); + + public PortConnection(NodePort port) { + this.port = port; + node = port.node; + fieldName = port.fieldName; + } + + /// Returns the port that this points to + private NodePort GetPort() { + if (node == null || string.IsNullOrEmpty(fieldName)) + { + return null; + } + + return node.GetPort(fieldName); + } + } + } +} diff --git a/Scripts/NodePort.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/NodePort.cs.meta similarity index 100% rename from Scripts/NodePort.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/NodePort.cs.meta diff --git a/Scripts/SceneGraph.cs b/xNode/Packages/com.pillow.xnode/Runtime/SceneGraph.cs similarity index 100% rename from Scripts/SceneGraph.cs rename to xNode/Packages/com.pillow.xnode/Runtime/SceneGraph.cs diff --git a/Scripts/SceneGraph.cs.meta b/xNode/Packages/com.pillow.xnode/Runtime/SceneGraph.cs.meta similarity index 100% rename from Scripts/SceneGraph.cs.meta rename to xNode/Packages/com.pillow.xnode/Runtime/SceneGraph.cs.meta diff --git a/Scripts/XNode.asmdef b/xNode/Packages/com.pillow.xnode/Runtime/XNode.asmdef similarity index 100% rename from Scripts/XNode.asmdef rename to xNode/Packages/com.pillow.xnode/Runtime/XNode.asmdef diff --git a/Scripts/XNode.asmdef.meta b/xNode/Packages/com.pillow.xnode/Runtime/XNode.asmdef.meta similarity index 100% rename from Scripts/XNode.asmdef.meta rename to xNode/Packages/com.pillow.xnode/Runtime/XNode.asmdef.meta diff --git a/xNode/Packages/com.pillow.xnode/package.json b/xNode/Packages/com.pillow.xnode/package.json new file mode 100644 index 0000000..708e5b6 --- /dev/null +++ b/xNode/Packages/com.pillow.xnode/package.json @@ -0,0 +1,20 @@ +{ + "name": "com.pillow.xnode", + "displayName": "xNode", + "description": "xNode provides a set of APIs and an editor interface for creating and editing custom node graphs.", + "keywords": [], + "version": "1.8.0", + "unity": "2021.3", + "repository": { + "type": "git", + "repository": "https://github.com/TogetherXR/com.pillow.xnode.git" + }, + "author": { + "name": "Pillow Inc.", + "url": "https://github.com/TogetherXR" + }, + "publishConfig": { + "registry": "http://upm.pillow.social:4873" + }, + "hideInEditor": false +} \ No newline at end of file diff --git a/package.json.meta b/xNode/Packages/com.pillow.xnode/package.json.meta similarity index 100% rename from package.json.meta rename to xNode/Packages/com.pillow.xnode/package.json.meta diff --git a/README.md b/xNode/Packages/com.pillow.xnode/~Documentation~/README.md similarity index 100% rename from README.md rename to xNode/Packages/com.pillow.xnode/~Documentation~/README.md diff --git a/xNode/Packages/manifest.json b/xNode/Packages/manifest.json new file mode 100644 index 0000000..7a18c96 --- /dev/null +++ b/xNode/Packages/manifest.json @@ -0,0 +1,38 @@ +{ + "dependencies": { + "com.unity.feature.development": "1.0.1", + "com.unity.textmeshpro": "3.0.6", + "com.unity.ugui": "1.0.0", + "com.unity.visualscripting": "1.8.0", + "com.unity.modules.androidjni": "1.0.0", + "com.unity.modules.animation": "1.0.0", + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.cloth": "1.0.0", + "com.unity.modules.director": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0", + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.particlesystem": "1.0.0", + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.physics2d": "1.0.0", + "com.unity.modules.screencapture": "1.0.0", + "com.unity.modules.terrain": "1.0.0", + "com.unity.modules.terrainphysics": "1.0.0", + "com.unity.modules.tilemap": "1.0.0", + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.uielements": "1.0.0", + "com.unity.modules.umbra": "1.0.0", + "com.unity.modules.unityanalytics": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.unitywebrequestassetbundle": "1.0.0", + "com.unity.modules.unitywebrequestaudio": "1.0.0", + "com.unity.modules.unitywebrequesttexture": "1.0.0", + "com.unity.modules.unitywebrequestwww": "1.0.0", + "com.unity.modules.vehicles": "1.0.0", + "com.unity.modules.video": "1.0.0", + "com.unity.modules.vr": "1.0.0", + "com.unity.modules.wind": "1.0.0", + "com.unity.modules.xr": "1.0.0" + } +} diff --git a/xNode/ProjectSettings/AudioManager.asset b/xNode/ProjectSettings/AudioManager.asset new file mode 100644 index 0000000..07ebfb0 --- /dev/null +++ b/xNode/ProjectSettings/AudioManager.asset @@ -0,0 +1,19 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!11 &1 +AudioManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Volume: 1 + Rolloff Scale: 1 + Doppler Factor: 1 + Default Speaker Mode: 2 + m_SampleRate: 0 + m_DSPBufferSize: 1024 + m_VirtualVoiceCount: 512 + m_RealVoiceCount: 32 + m_SpatializerPlugin: + m_AmbisonicDecoderPlugin: + m_DisableAudio: 0 + m_VirtualizeEffects: 1 + m_RequestedDSPBufferSize: 1024 diff --git a/xNode/ProjectSettings/ClusterInputManager.asset b/xNode/ProjectSettings/ClusterInputManager.asset new file mode 100644 index 0000000..e7886b2 --- /dev/null +++ b/xNode/ProjectSettings/ClusterInputManager.asset @@ -0,0 +1,6 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!236 &1 +ClusterInputManager: + m_ObjectHideFlags: 0 + m_Inputs: [] diff --git a/xNode/ProjectSettings/DynamicsManager.asset b/xNode/ProjectSettings/DynamicsManager.asset new file mode 100644 index 0000000..cdc1f3e --- /dev/null +++ b/xNode/ProjectSettings/DynamicsManager.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!55 &1 +PhysicsManager: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_Gravity: {x: 0, y: -9.81, z: 0} + m_DefaultMaterial: {fileID: 0} + m_BounceThreshold: 2 + m_SleepThreshold: 0.005 + m_DefaultContactOffset: 0.01 + m_DefaultSolverIterations: 6 + m_DefaultSolverVelocityIterations: 1 + m_QueriesHitBackfaces: 0 + m_QueriesHitTriggers: 1 + m_EnableAdaptiveForce: 0 + m_ClothInterCollisionDistance: 0 + m_ClothInterCollisionStiffness: 0 + m_ContactsGeneration: 1 + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + m_AutoSimulation: 1 + m_AutoSyncTransforms: 0 + m_ReuseCollisionCallbacks: 1 + m_ClothInterCollisionSettingsToggle: 0 + m_ContactPairsMode: 0 + m_BroadphaseType: 0 + m_WorldBounds: + m_Center: {x: 0, y: 0, z: 0} + m_Extent: {x: 250, y: 250, z: 250} + m_WorldSubdivisions: 8 + m_FrictionType: 0 + m_EnableEnhancedDeterminism: 0 + m_EnableUnifiedHeightmaps: 1 + m_DefaultMaxAngluarSpeed: 7 diff --git a/xNode/ProjectSettings/EditorBuildSettings.asset b/xNode/ProjectSettings/EditorBuildSettings.asset new file mode 100644 index 0000000..0147887 --- /dev/null +++ b/xNode/ProjectSettings/EditorBuildSettings.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1045 &1 +EditorBuildSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Scenes: [] + m_configObjects: {} diff --git a/xNode/ProjectSettings/EditorSettings.asset b/xNode/ProjectSettings/EditorSettings.asset new file mode 100644 index 0000000..1e44a0a --- /dev/null +++ b/xNode/ProjectSettings/EditorSettings.asset @@ -0,0 +1,30 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!159 &1 +EditorSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_ExternalVersionControlSupport: Visible Meta Files + m_SerializationMode: 2 + m_LineEndingsForNewScripts: 0 + m_DefaultBehaviorMode: 0 + m_PrefabRegularEnvironment: {fileID: 0} + m_PrefabUIEnvironment: {fileID: 0} + m_SpritePackerMode: 0 + m_SpritePackerPaddingPower: 1 + m_EtcTextureCompressorBehavior: 1 + m_EtcTextureFastCompressor: 1 + m_EtcTextureNormalCompressor: 2 + m_EtcTextureBestCompressor: 4 + m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;rsp;asmref + m_ProjectGenerationRootNamespace: + m_CollabEditorSettings: + inProgressEnabled: 1 + m_EnableTextureStreamingInEditMode: 1 + m_EnableTextureStreamingInPlayMode: 1 + m_AsyncShaderCompilation: 1 + m_EnterPlayModeOptionsEnabled: 0 + m_EnterPlayModeOptions: 3 + m_ShowLightmapResolutionOverlay: 1 + m_UseLegacyProbeSampleCount: 0 + m_SerializeInlineMappingsOnOneLine: 1 diff --git a/xNode/ProjectSettings/GraphicsSettings.asset b/xNode/ProjectSettings/GraphicsSettings.asset new file mode 100644 index 0000000..43369e3 --- /dev/null +++ b/xNode/ProjectSettings/GraphicsSettings.asset @@ -0,0 +1,63 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!30 &1 +GraphicsSettings: + m_ObjectHideFlags: 0 + serializedVersion: 13 + m_Deferred: + m_Mode: 1 + m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0} + m_DeferredReflections: + m_Mode: 1 + m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0} + m_ScreenSpaceShadows: + m_Mode: 1 + m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0} + m_LegacyDeferred: + m_Mode: 1 + m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0} + m_DepthNormals: + m_Mode: 1 + m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0} + m_MotionVectors: + m_Mode: 1 + m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0} + m_LightHalo: + m_Mode: 1 + m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0} + m_LensFlare: + m_Mode: 1 + m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0} + m_AlwaysIncludedShaders: + - {fileID: 7, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0} + m_PreloadedShaders: [] + m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000, + type: 0} + m_CustomRenderPipeline: {fileID: 0} + m_TransparencySortMode: 0 + m_TransparencySortAxis: {x: 0, y: 0, z: 1} + m_DefaultRenderingPath: 1 + m_DefaultMobileRenderingPath: 1 + m_TierSettings: [] + m_LightmapStripping: 0 + m_FogStripping: 0 + m_InstancingStripping: 0 + m_LightmapKeepPlain: 1 + m_LightmapKeepDirCombined: 1 + m_LightmapKeepDynamicPlain: 1 + m_LightmapKeepDynamicDirCombined: 1 + m_LightmapKeepShadowMask: 1 + m_LightmapKeepSubtractive: 1 + m_FogKeepLinear: 1 + m_FogKeepExp: 1 + m_FogKeepExp2: 1 + m_AlbedoSwatchInfos: [] + m_LightsUseLinearIntensity: 0 + m_LightsUseColorTemperature: 0 + m_LogWhenShaderIsCompiled: 0 + m_AllowEnlightenSupportForUpgradedProject: 0 diff --git a/xNode/ProjectSettings/InputManager.asset b/xNode/ProjectSettings/InputManager.asset new file mode 100644 index 0000000..17c8f53 --- /dev/null +++ b/xNode/ProjectSettings/InputManager.asset @@ -0,0 +1,295 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!13 &1 +InputManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Axes: + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: left + positiveButton: right + altNegativeButton: a + altPositiveButton: d + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: down + positiveButton: up + altNegativeButton: s + altPositiveButton: w + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left ctrl + altNegativeButton: + altPositiveButton: mouse 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left alt + altNegativeButton: + altPositiveButton: mouse 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left shift + altNegativeButton: + altPositiveButton: mouse 2 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: space + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse X + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse Y + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse ScrollWheel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 2 + joyNum: 0 + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 0 + type: 2 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 1 + type: 2 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 0 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 1 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 2 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 3 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: return + altNegativeButton: + altPositiveButton: joystick button 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: enter + altNegativeButton: + altPositiveButton: space + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Cancel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: escape + altNegativeButton: + altPositiveButton: joystick button 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 diff --git a/xNode/ProjectSettings/MemorySettings.asset b/xNode/ProjectSettings/MemorySettings.asset new file mode 100644 index 0000000..5b5face --- /dev/null +++ b/xNode/ProjectSettings/MemorySettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!387306366 &1 +MemorySettings: + m_ObjectHideFlags: 0 + m_EditorMemorySettings: + m_MainAllocatorBlockSize: -1 + m_ThreadAllocatorBlockSize: -1 + m_MainGfxBlockSize: -1 + m_ThreadGfxBlockSize: -1 + m_CacheBlockSize: -1 + m_TypetreeBlockSize: -1 + m_ProfilerBlockSize: -1 + m_ProfilerEditorBlockSize: -1 + m_BucketAllocatorGranularity: -1 + m_BucketAllocatorBucketsCount: -1 + m_BucketAllocatorBlockSize: -1 + m_BucketAllocatorBlockCount: -1 + m_ProfilerBucketAllocatorGranularity: -1 + m_ProfilerBucketAllocatorBucketsCount: -1 + m_ProfilerBucketAllocatorBlockSize: -1 + m_ProfilerBucketAllocatorBlockCount: -1 + m_TempAllocatorSizeMain: -1 + m_JobTempAllocatorBlockSize: -1 + m_BackgroundJobTempAllocatorBlockSize: -1 + m_JobTempAllocatorReducedBlockSize: -1 + m_TempAllocatorSizeGIBakingWorker: -1 + m_TempAllocatorSizeNavMeshWorker: -1 + m_TempAllocatorSizeAudioWorker: -1 + m_TempAllocatorSizeCloudWorker: -1 + m_TempAllocatorSizeGfx: -1 + m_TempAllocatorSizeJobWorker: -1 + m_TempAllocatorSizeBackgroundWorker: -1 + m_TempAllocatorSizePreloadManager: -1 + m_PlatformMemorySettings: {} diff --git a/xNode/ProjectSettings/NavMeshAreas.asset b/xNode/ProjectSettings/NavMeshAreas.asset new file mode 100644 index 0000000..3b0b7c3 --- /dev/null +++ b/xNode/ProjectSettings/NavMeshAreas.asset @@ -0,0 +1,91 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!126 &1 +NavMeshProjectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + areas: + - name: Walkable + cost: 1 + - name: Not Walkable + cost: 1 + - name: Jump + cost: 2 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + m_LastAgentTypeID: -887442657 + m_Settings: + - serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.75 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_SettingNames: + - Humanoid diff --git a/xNode/ProjectSettings/PackageManagerSettings.asset b/xNode/ProjectSettings/PackageManagerSettings.asset new file mode 100644 index 0000000..112a053 --- /dev/null +++ b/xNode/ProjectSettings/PackageManagerSettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &1 +MonoBehaviour: + m_ObjectHideFlags: 61 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 13964, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_EnablePreReleasePackages: 0 + m_EnablePackageDependencies: 0 + m_AdvancedSettingsExpanded: 1 + m_ScopedRegistriesSettingsExpanded: 1 + m_SeeAllPackageVersions: 0 + oneTimeWarningShown: 0 + m_Registries: + - m_Id: main + m_Name: + m_Url: https://packages.unity.com + m_Scopes: [] + m_IsDefault: 1 + m_Capabilities: 7 + m_UserSelectedRegistryName: + m_UserAddingNewScopedRegistry: 0 + m_RegistryInfoDraft: + m_Modified: 0 + m_ErrorMessage: + m_UserModificationsInstanceId: -830 + m_OriginalInstanceId: -832 + m_LoadAssets: 0 diff --git a/xNode/ProjectSettings/Packages/com.unity.testtools.codecoverage/Settings.json b/xNode/ProjectSettings/Packages/com.unity.testtools.codecoverage/Settings.json new file mode 100644 index 0000000..3c7b4c1 --- /dev/null +++ b/xNode/ProjectSettings/Packages/com.unity.testtools.codecoverage/Settings.json @@ -0,0 +1,5 @@ +{ + "m_Dictionary": { + "m_DictionaryValues": [] + } +} \ No newline at end of file diff --git a/xNode/ProjectSettings/Physics2DSettings.asset b/xNode/ProjectSettings/Physics2DSettings.asset new file mode 100644 index 0000000..47880b1 --- /dev/null +++ b/xNode/ProjectSettings/Physics2DSettings.asset @@ -0,0 +1,56 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!19 &1 +Physics2DSettings: + m_ObjectHideFlags: 0 + serializedVersion: 4 + m_Gravity: {x: 0, y: -9.81} + m_DefaultMaterial: {fileID: 0} + m_VelocityIterations: 8 + m_PositionIterations: 3 + m_VelocityThreshold: 1 + m_MaxLinearCorrection: 0.2 + m_MaxAngularCorrection: 8 + m_MaxTranslationSpeed: 100 + m_MaxRotationSpeed: 360 + m_BaumgarteScale: 0.2 + m_BaumgarteTimeOfImpactScale: 0.75 + m_TimeToSleep: 0.5 + m_LinearSleepTolerance: 0.01 + m_AngularSleepTolerance: 2 + m_DefaultContactOffset: 0.01 + m_JobOptions: + serializedVersion: 2 + useMultithreading: 0 + useConsistencySorting: 0 + m_InterpolationPosesPerJob: 100 + m_NewContactsPerJob: 30 + m_CollideContactsPerJob: 100 + m_ClearFlagsPerJob: 200 + m_ClearBodyForcesPerJob: 200 + m_SyncDiscreteFixturesPerJob: 50 + m_SyncContinuousFixturesPerJob: 50 + m_FindNearestContactsPerJob: 100 + m_UpdateTriggerContactsPerJob: 100 + m_IslandSolverCostThreshold: 100 + m_IslandSolverBodyCostScale: 1 + m_IslandSolverContactCostScale: 10 + m_IslandSolverJointCostScale: 10 + m_IslandSolverBodiesPerJob: 50 + m_IslandSolverContactsPerJob: 50 + m_AutoSimulation: 1 + m_QueriesHitTriggers: 1 + m_QueriesStartInColliders: 1 + m_CallbacksOnDisable: 1 + m_ReuseCollisionCallbacks: 1 + m_AutoSyncTransforms: 0 + m_AlwaysShowColliders: 0 + m_ShowColliderSleep: 1 + m_ShowColliderContacts: 0 + m_ShowColliderAABB: 0 + m_ContactArrowScale: 0.2 + m_ColliderAwakeColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.7529412} + m_ColliderAsleepColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.36078432} + m_ColliderContactColor: {r: 1, g: 0, b: 1, a: 0.6862745} + m_ColliderAABBColor: {r: 1, g: 1, b: 0, a: 0.2509804} + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff diff --git a/xNode/ProjectSettings/PresetManager.asset b/xNode/ProjectSettings/PresetManager.asset new file mode 100644 index 0000000..67a94da --- /dev/null +++ b/xNode/ProjectSettings/PresetManager.asset @@ -0,0 +1,7 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1386491679 &1 +PresetManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_DefaultPresets: {} diff --git a/xNode/ProjectSettings/ProjectSettings.asset b/xNode/ProjectSettings/ProjectSettings.asset new file mode 100644 index 0000000..6df2541 --- /dev/null +++ b/xNode/ProjectSettings/ProjectSettings.asset @@ -0,0 +1,759 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!129 &1 +PlayerSettings: + m_ObjectHideFlags: 0 + serializedVersion: 26 + productGUID: f270f84906a1d71449023fafb0c64296 + AndroidProfiler: 0 + AndroidFilterTouchesWhenObscured: 0 + AndroidEnableSustainedPerformanceMode: 0 + defaultScreenOrientation: 4 + targetDevice: 2 + useOnDemandResources: 0 + accelerometerFrequency: 60 + companyName: DefaultCompany + productName: xNode + defaultCursor: {fileID: 0} + cursorHotspot: {x: 0, y: 0} + m_SplashScreenBackgroundColor: {r: 0.13725491, g: 0.12156863, b: 0.1254902, a: 1} + m_ShowUnitySplashScreen: 1 + m_ShowUnitySplashLogo: 1 + m_SplashScreenOverlayOpacity: 1 + m_SplashScreenAnimation: 1 + m_SplashScreenLogoStyle: 1 + m_SplashScreenDrawMode: 0 + m_SplashScreenBackgroundAnimationZoom: 1 + m_SplashScreenLogoAnimationZoom: 1 + m_SplashScreenBackgroundLandscapeAspect: 1 + m_SplashScreenBackgroundPortraitAspect: 1 + m_SplashScreenBackgroundLandscapeUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenBackgroundPortraitUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenLogos: [] + m_VirtualRealitySplashScreen: {fileID: 0} + m_HolographicTrackingLossScreen: {fileID: 0} + defaultScreenWidth: 1920 + defaultScreenHeight: 1080 + defaultScreenWidthWeb: 960 + defaultScreenHeightWeb: 600 + m_StereoRenderingPath: 0 + m_ActiveColorSpace: 0 + m_SpriteBatchVertexThreshold: 300 + m_MTRendering: 1 + mipStripping: 0 + numberOfMipsStripped: 0 + numberOfMipsStrippedPerMipmapLimitGroup: {} + m_StackTraceTypes: 010000000100000001000000010000000100000001000000 + iosShowActivityIndicatorOnLoading: -1 + androidShowActivityIndicatorOnLoading: -1 + iosUseCustomAppBackgroundBehavior: 0 + allowedAutorotateToPortrait: 1 + allowedAutorotateToPortraitUpsideDown: 1 + allowedAutorotateToLandscapeRight: 1 + allowedAutorotateToLandscapeLeft: 1 + useOSAutorotation: 1 + use32BitDisplayBuffer: 1 + preserveFramebufferAlpha: 0 + disableDepthAndStencilBuffers: 0 + androidStartInFullscreen: 1 + androidRenderOutsideSafeArea: 1 + androidUseSwappy: 1 + androidBlitType: 0 + androidResizableWindow: 0 + androidDefaultWindowWidth: 1920 + androidDefaultWindowHeight: 1080 + androidMinimumWindowWidth: 400 + androidMinimumWindowHeight: 300 + androidFullscreenMode: 1 + defaultIsNativeResolution: 1 + macRetinaSupport: 1 + runInBackground: 1 + captureSingleScreen: 0 + muteOtherAudioSources: 0 + Prepare IOS For Recording: 0 + Force IOS Speakers When Recording: 0 + deferSystemGesturesMode: 0 + hideHomeButton: 0 + submitAnalytics: 1 + usePlayerLog: 1 + bakeCollisionMeshes: 0 + forceSingleInstance: 0 + useFlipModelSwapchain: 1 + resizableWindow: 0 + useMacAppStoreValidation: 0 + macAppStoreCategory: public.app-category.games + gpuSkinning: 1 + xboxPIXTextureCapture: 0 + xboxEnableAvatar: 0 + xboxEnableKinect: 0 + xboxEnableKinectAutoTracking: 0 + xboxEnableFitness: 0 + visibleInBackground: 1 + allowFullscreenSwitch: 1 + fullscreenMode: 1 + xboxSpeechDB: 0 + xboxEnableHeadOrientation: 0 + xboxEnableGuest: 0 + xboxEnablePIXSampling: 0 + metalFramebufferOnly: 0 + xboxOneResolution: 0 + xboxOneSResolution: 0 + xboxOneXResolution: 3 + xboxOneMonoLoggingLevel: 0 + xboxOneLoggingLevel: 1 + xboxOneDisableEsram: 0 + xboxOneEnableTypeOptimization: 0 + xboxOnePresentImmediateThreshold: 0 + switchQueueCommandMemory: 0 + switchQueueControlMemory: 16384 + switchQueueComputeMemory: 262144 + switchNVNShaderPoolsGranularity: 33554432 + switchNVNDefaultPoolsGranularity: 16777216 + switchNVNOtherPoolsGranularity: 16777216 + switchGpuScratchPoolGranularity: 2097152 + switchAllowGpuScratchShrinking: 0 + switchNVNMaxPublicTextureIDCount: 0 + switchNVNMaxPublicSamplerIDCount: 0 + switchNVNGraphicsFirmwareMemory: 32 + stadiaPresentMode: 0 + stadiaTargetFramerate: 0 + vulkanNumSwapchainBuffers: 3 + vulkanEnableSetSRGBWrite: 0 + vulkanEnablePreTransform: 1 + vulkanEnableLateAcquireNextImage: 0 + vulkanEnableCommandBufferRecycling: 1 + loadStoreDebugModeEnabled: 0 + bundleVersion: 0.1 + preloadedAssets: [] + metroInputSource: 0 + wsaTransparentSwapchain: 0 + m_HolographicPauseOnTrackingLoss: 1 + xboxOneDisableKinectGpuReservation: 1 + xboxOneEnable7thCore: 1 + vrSettings: + enable360StereoCapture: 0 + isWsaHolographicRemotingEnabled: 0 + enableFrameTimingStats: 0 + enableOpenGLProfilerGPURecorders: 1 + useHDRDisplay: 0 + hdrBitDepth: 0 + m_ColorGamuts: 00000000 + targetPixelDensity: 30 + resolutionScalingMode: 0 + resetResolutionOnWindowResize: 0 + androidSupportedAspectRatio: 1 + androidMaxAspectRatio: 2.1 + applicationIdentifier: {} + buildNumber: + Standalone: 0 + VisionOS: 0 + iPhone: 0 + tvOS: 0 + overrideDefaultApplicationIdentifier: 0 + AndroidBundleVersionCode: 1 + AndroidMinSdkVersion: 22 + AndroidTargetSdkVersion: 0 + AndroidPreferredInstallLocation: 1 + aotOptions: + stripEngineCode: 1 + iPhoneStrippingLevel: 0 + iPhoneScriptCallOptimization: 0 + ForceInternetPermission: 0 + ForceSDCardPermission: 0 + CreateWallpaper: 0 + APKExpansionFiles: 0 + keepLoadedShadersAlive: 0 + StripUnusedMeshComponents: 1 + strictShaderVariantMatching: 0 + VertexChannelCompressionMask: 4054 + iPhoneSdkVersion: 988 + iOSTargetOSVersionString: 12.0 + tvOSSdkVersion: 0 + tvOSRequireExtendedGameController: 0 + tvOSTargetOSVersionString: 12.0 + VisionOSSdkVersion: 0 + VisionOSTargetOSVersionString: 1.0 + uIPrerenderedIcon: 0 + uIRequiresPersistentWiFi: 0 + uIRequiresFullScreen: 1 + uIStatusBarHidden: 1 + uIExitOnSuspend: 0 + uIStatusBarStyle: 0 + appleTVSplashScreen: {fileID: 0} + appleTVSplashScreen2x: {fileID: 0} + tvOSSmallIconLayers: [] + tvOSSmallIconLayers2x: [] + tvOSLargeIconLayers: [] + tvOSLargeIconLayers2x: [] + tvOSTopShelfImageLayers: [] + tvOSTopShelfImageLayers2x: [] + tvOSTopShelfImageWideLayers: [] + tvOSTopShelfImageWideLayers2x: [] + iOSLaunchScreenType: 0 + iOSLaunchScreenPortrait: {fileID: 0} + iOSLaunchScreenLandscape: {fileID: 0} + iOSLaunchScreenBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreenFillPct: 100 + iOSLaunchScreenSize: 100 + iOSLaunchScreenCustomXibPath: + iOSLaunchScreeniPadType: 0 + iOSLaunchScreeniPadImage: {fileID: 0} + iOSLaunchScreeniPadBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreeniPadFillPct: 100 + iOSLaunchScreeniPadSize: 100 + iOSLaunchScreeniPadCustomXibPath: + iOSLaunchScreenCustomStoryboardPath: + iOSLaunchScreeniPadCustomStoryboardPath: + iOSDeviceRequirements: [] + iOSURLSchemes: [] + macOSURLSchemes: [] + iOSBackgroundModes: 0 + iOSMetalForceHardShadows: 0 + metalEditorSupport: 1 + metalAPIValidation: 1 + iOSRenderExtraFrameOnPause: 0 + iosCopyPluginsCodeInsteadOfSymlink: 0 + appleDeveloperTeamID: + iOSManualSigningProvisioningProfileID: + tvOSManualSigningProvisioningProfileID: + VisionOSManualSigningProvisioningProfileID: + iOSManualSigningProvisioningProfileType: 0 + tvOSManualSigningProvisioningProfileType: 0 + VisionOSManualSigningProvisioningProfileType: 0 + appleEnableAutomaticSigning: 0 + iOSRequireARKit: 0 + iOSAutomaticallyDetectAndAddCapabilities: 1 + appleEnableProMotion: 0 + shaderPrecisionModel: 0 + clonedFromGUID: c0afd0d1d80e3634a9dac47e8a0426ea + templatePackageId: com.unity.template.3d@8.1.1 + templateDefaultScene: Assets/Scenes/SampleScene.unity + useCustomMainManifest: 0 + useCustomLauncherManifest: 0 + useCustomMainGradleTemplate: 0 + useCustomLauncherGradleManifest: 0 + useCustomBaseGradleTemplate: 0 + useCustomGradlePropertiesTemplate: 0 + useCustomGradleSettingsTemplate: 0 + useCustomProguardFile: 0 + AndroidTargetArchitectures: 1 + AndroidTargetDevices: 0 + AndroidSplashScreenScale: 0 + androidSplashScreen: {fileID: 0} + AndroidKeystoreName: + AndroidKeyaliasName: + AndroidEnableArmv9SecurityFeatures: 0 + AndroidBuildApkPerCpuArchitecture: 0 + AndroidTVCompatibility: 0 + AndroidIsGame: 1 + AndroidEnableTango: 0 + androidEnableBanner: 1 + androidUseLowAccuracyLocation: 0 + androidUseCustomKeystore: 0 + m_AndroidBanners: + - width: 320 + height: 180 + banner: {fileID: 0} + androidGamepadSupportLevel: 0 + chromeosInputEmulation: 1 + AndroidMinifyRelease: 0 + AndroidMinifyDebug: 0 + AndroidValidateAppBundleSize: 1 + AndroidAppBundleSizeToValidate: 150 + m_BuildTargetIcons: [] + m_BuildTargetPlatformIcons: [] + m_BuildTargetBatching: + - m_BuildTarget: Standalone + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: tvOS + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: Android + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: iPhone + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: WebGL + m_StaticBatching: 0 + m_DynamicBatching: 0 + m_BuildTargetShaderSettings: [] + m_BuildTargetGraphicsJobs: + - m_BuildTarget: MacStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: Switch + m_GraphicsJobs: 1 + - m_BuildTarget: MetroSupport + m_GraphicsJobs: 1 + - m_BuildTarget: AppleTVSupport + m_GraphicsJobs: 0 + - m_BuildTarget: BJMSupport + m_GraphicsJobs: 1 + - m_BuildTarget: LinuxStandaloneSupport + m_GraphicsJobs: 1 + - m_BuildTarget: PS4Player + m_GraphicsJobs: 1 + - m_BuildTarget: iOSSupport + m_GraphicsJobs: 0 + - m_BuildTarget: WindowsStandaloneSupport + m_GraphicsJobs: 1 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobs: 1 + - m_BuildTarget: LuminSupport + m_GraphicsJobs: 0 + - m_BuildTarget: AndroidPlayer + m_GraphicsJobs: 0 + - m_BuildTarget: WebGLSupport + m_GraphicsJobs: 0 + m_BuildTargetGraphicsJobMode: + - m_BuildTarget: PS4Player + m_GraphicsJobMode: 0 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobMode: 0 + m_BuildTargetGraphicsAPIs: + - m_BuildTarget: AndroidPlayer + m_APIs: 150000000b000000 + m_Automatic: 1 + - m_BuildTarget: iOSSupport + m_APIs: 10000000 + m_Automatic: 1 + - m_BuildTarget: AppleTVSupport + m_APIs: 10000000 + m_Automatic: 1 + - m_BuildTarget: WebGLSupport + m_APIs: 0b000000 + m_Automatic: 1 + m_BuildTargetVRSettings: + - m_BuildTarget: Standalone + m_Enabled: 0 + m_Devices: + - Oculus + - OpenVR + m_DefaultShaderChunkSizeInMB: 16 + m_DefaultShaderChunkCount: 0 + openGLRequireES31: 0 + openGLRequireES31AEP: 0 + openGLRequireES32: 0 + m_TemplateCustomTags: {} + mobileMTRendering: + Android: 1 + iPhone: 1 + tvOS: 1 + m_BuildTargetGroupLightmapEncodingQuality: + - m_BuildTarget: Android + m_EncodingQuality: 1 + - m_BuildTarget: iPhone + m_EncodingQuality: 1 + - m_BuildTarget: tvOS + m_EncodingQuality: 1 + m_BuildTargetGroupHDRCubemapEncodingQuality: + - m_BuildTarget: Android + m_EncodingQuality: 1 + - m_BuildTarget: iPhone + m_EncodingQuality: 1 + - m_BuildTarget: tvOS + m_EncodingQuality: 1 + m_BuildTargetGroupLightmapSettings: [] + m_BuildTargetGroupLoadStoreDebugModeSettings: [] + m_BuildTargetNormalMapEncoding: + - m_BuildTarget: Android + m_Encoding: 1 + - m_BuildTarget: iPhone + m_Encoding: 1 + - m_BuildTarget: tvOS + m_Encoding: 1 + m_BuildTargetDefaultTextureCompressionFormat: + - m_BuildTarget: Android + m_Format: 3 + playModeTestRunnerEnabled: 0 + runPlayModeTestAsEditModeTest: 0 + actionOnDotNetUnhandledException: 1 + enableInternalProfiler: 0 + logObjCUncaughtExceptions: 1 + enableCrashReportAPI: 0 + cameraUsageDescription: + locationUsageDescription: + microphoneUsageDescription: + bluetoothUsageDescription: + macOSTargetOSVersion: 10.13.0 + switchNMETAOverride: + switchNetLibKey: + switchSocketMemoryPoolSize: 6144 + switchSocketAllocatorPoolSize: 128 + switchSocketConcurrencyLimit: 14 + switchScreenResolutionBehavior: 2 + switchUseCPUProfiler: 0 + switchUseGOLDLinker: 0 + switchLTOSetting: 0 + switchApplicationID: 0x01004b9000490000 + switchNSODependencies: + switchCompilerFlags: + switchTitleNames_0: + switchTitleNames_1: + switchTitleNames_2: + switchTitleNames_3: + switchTitleNames_4: + switchTitleNames_5: + switchTitleNames_6: + switchTitleNames_7: + switchTitleNames_8: + switchTitleNames_9: + switchTitleNames_10: + switchTitleNames_11: + switchTitleNames_12: + switchTitleNames_13: + switchTitleNames_14: + switchTitleNames_15: + switchPublisherNames_0: + switchPublisherNames_1: + switchPublisherNames_2: + switchPublisherNames_3: + switchPublisherNames_4: + switchPublisherNames_5: + switchPublisherNames_6: + switchPublisherNames_7: + switchPublisherNames_8: + switchPublisherNames_9: + switchPublisherNames_10: + switchPublisherNames_11: + switchPublisherNames_12: + switchPublisherNames_13: + switchPublisherNames_14: + switchPublisherNames_15: + switchIcons_0: {fileID: 0} + switchIcons_1: {fileID: 0} + switchIcons_2: {fileID: 0} + switchIcons_3: {fileID: 0} + switchIcons_4: {fileID: 0} + switchIcons_5: {fileID: 0} + switchIcons_6: {fileID: 0} + switchIcons_7: {fileID: 0} + switchIcons_8: {fileID: 0} + switchIcons_9: {fileID: 0} + switchIcons_10: {fileID: 0} + switchIcons_11: {fileID: 0} + switchIcons_12: {fileID: 0} + switchIcons_13: {fileID: 0} + switchIcons_14: {fileID: 0} + switchIcons_15: {fileID: 0} + switchSmallIcons_0: {fileID: 0} + switchSmallIcons_1: {fileID: 0} + switchSmallIcons_2: {fileID: 0} + switchSmallIcons_3: {fileID: 0} + switchSmallIcons_4: {fileID: 0} + switchSmallIcons_5: {fileID: 0} + switchSmallIcons_6: {fileID: 0} + switchSmallIcons_7: {fileID: 0} + switchSmallIcons_8: {fileID: 0} + switchSmallIcons_9: {fileID: 0} + switchSmallIcons_10: {fileID: 0} + switchSmallIcons_11: {fileID: 0} + switchSmallIcons_12: {fileID: 0} + switchSmallIcons_13: {fileID: 0} + switchSmallIcons_14: {fileID: 0} + switchSmallIcons_15: {fileID: 0} + switchManualHTML: + switchAccessibleURLs: + switchLegalInformation: + switchMainThreadStackSize: 1048576 + switchPresenceGroupId: + switchLogoHandling: 0 + switchReleaseVersion: 0 + switchDisplayVersion: 1.0.0 + switchStartupUserAccount: 0 + switchSupportedLanguagesMask: 0 + switchLogoType: 0 + switchApplicationErrorCodeCategory: + switchUserAccountSaveDataSize: 0 + switchUserAccountSaveDataJournalSize: 0 + switchApplicationAttribute: 0 + switchCardSpecSize: -1 + switchCardSpecClock: -1 + switchRatingsMask: 0 + switchRatingsInt_0: 0 + switchRatingsInt_1: 0 + switchRatingsInt_2: 0 + switchRatingsInt_3: 0 + switchRatingsInt_4: 0 + switchRatingsInt_5: 0 + switchRatingsInt_6: 0 + switchRatingsInt_7: 0 + switchRatingsInt_8: 0 + switchRatingsInt_9: 0 + switchRatingsInt_10: 0 + switchRatingsInt_11: 0 + switchRatingsInt_12: 0 + switchLocalCommunicationIds_0: + switchLocalCommunicationIds_1: + switchLocalCommunicationIds_2: + switchLocalCommunicationIds_3: + switchLocalCommunicationIds_4: + switchLocalCommunicationIds_5: + switchLocalCommunicationIds_6: + switchLocalCommunicationIds_7: + switchParentalControl: 0 + switchAllowsScreenshot: 1 + switchAllowsVideoCapturing: 1 + switchAllowsRuntimeAddOnContentInstall: 0 + switchDataLossConfirmation: 0 + switchUserAccountLockEnabled: 0 + switchSystemResourceMemory: 16777216 + switchSupportedNpadStyles: 22 + switchNativeFsCacheSize: 32 + switchIsHoldTypeHorizontal: 0 + switchSupportedNpadCount: 8 + switchEnableTouchScreen: 1 + switchSocketConfigEnabled: 0 + switchTcpInitialSendBufferSize: 32 + switchTcpInitialReceiveBufferSize: 64 + switchTcpAutoSendBufferSizeMax: 256 + switchTcpAutoReceiveBufferSizeMax: 256 + switchUdpSendBufferSize: 9 + switchUdpReceiveBufferSize: 42 + switchSocketBufferEfficiency: 4 + switchSocketInitializeEnabled: 1 + switchNetworkInterfaceManagerInitializeEnabled: 1 + switchPlayerConnectionEnabled: 1 + switchUseNewStyleFilepaths: 1 + switchUseLegacyFmodPriorities: 0 + switchUseMicroSleepForYield: 1 + switchEnableRamDiskSupport: 0 + switchMicroSleepForYieldTime: 25 + switchRamDiskSpaceSize: 12 + ps4NPAgeRating: 12 + ps4NPTitleSecret: + ps4NPTrophyPackPath: + ps4ParentalLevel: 11 + ps4ContentID: ED1633-NPXX51362_00-0000000000000000 + ps4Category: 0 + ps4MasterVersion: 01.00 + ps4AppVersion: 01.00 + ps4AppType: 0 + ps4ParamSfxPath: + ps4VideoOutPixelFormat: 0 + ps4VideoOutInitialWidth: 1920 + ps4VideoOutBaseModeInitialWidth: 1920 + ps4VideoOutReprojectionRate: 60 + ps4PronunciationXMLPath: + ps4PronunciationSIGPath: + ps4BackgroundImagePath: + ps4StartupImagePath: + ps4StartupImagesFolder: + ps4IconImagesFolder: + ps4SaveDataImagePath: + ps4SdkOverride: + ps4BGMPath: + ps4ShareFilePath: + ps4ShareOverlayImagePath: + ps4PrivacyGuardImagePath: + ps4ExtraSceSysFile: + ps4NPtitleDatPath: + ps4RemotePlayKeyAssignment: -1 + ps4RemotePlayKeyMappingDir: + ps4PlayTogetherPlayerCount: 0 + ps4EnterButtonAssignment: 1 + ps4ApplicationParam1: 0 + ps4ApplicationParam2: 0 + ps4ApplicationParam3: 0 + ps4ApplicationParam4: 0 + ps4DownloadDataSize: 0 + ps4GarlicHeapSize: 2048 + ps4ProGarlicHeapSize: 2560 + playerPrefsMaxSize: 32768 + ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ + ps4pnSessions: 1 + ps4pnPresence: 1 + ps4pnFriends: 1 + ps4pnGameCustomData: 1 + playerPrefsSupport: 0 + enableApplicationExit: 0 + resetTempFolder: 1 + restrictedAudioUsageRights: 0 + ps4UseResolutionFallback: 0 + ps4ReprojectionSupport: 0 + ps4UseAudio3dBackend: 0 + ps4UseLowGarlicFragmentationMode: 1 + ps4SocialScreenEnabled: 0 + ps4ScriptOptimizationLevel: 0 + ps4Audio3dVirtualSpeakerCount: 14 + ps4attribCpuUsage: 0 + ps4PatchPkgPath: + ps4PatchLatestPkgPath: + ps4PatchChangeinfoPath: + ps4PatchDayOne: 0 + ps4attribUserManagement: 0 + ps4attribMoveSupport: 0 + ps4attrib3DSupport: 0 + ps4attribShareSupport: 0 + ps4attribExclusiveVR: 0 + ps4disableAutoHideSplash: 0 + ps4videoRecordingFeaturesUsed: 0 + ps4contentSearchFeaturesUsed: 0 + ps4CompatibilityPS5: 0 + ps4AllowPS5Detection: 0 + ps4GPU800MHz: 1 + ps4attribEyeToEyeDistanceSettingVR: 0 + ps4IncludedModules: [] + ps4attribVROutputEnabled: 0 + monoEnv: + splashScreenBackgroundSourceLandscape: {fileID: 0} + splashScreenBackgroundSourcePortrait: {fileID: 0} + blurSplashScreenBackground: 1 + spritePackerPolicy: + webGLMemorySize: 16 + webGLExceptionSupport: 1 + webGLNameFilesAsHashes: 0 + webGLShowDiagnostics: 0 + webGLDataCaching: 1 + webGLDebugSymbols: 0 + webGLEmscriptenArgs: + webGLModulesDirectory: + webGLTemplate: APPLICATION:Default + webGLAnalyzeBuildSize: 0 + webGLUseEmbeddedResources: 0 + webGLCompressionFormat: 1 + webGLWasmArithmeticExceptions: 0 + webGLLinkerTarget: 1 + webGLThreadsSupport: 0 + webGLDecompressionFallback: 0 + webGLInitialMemorySize: 32 + webGLMaximumMemorySize: 2048 + webGLMemoryGrowthMode: 2 + webGLMemoryLinearGrowthStep: 16 + webGLMemoryGeometricGrowthStep: 0.2 + webGLMemoryGeometricGrowthCap: 96 + webGLPowerPreference: 2 + scriptingDefineSymbols: {} + additionalCompilerArguments: {} + platformArchitecture: {} + scriptingBackend: {} + il2cppCompilerConfiguration: {} + il2cppCodeGeneration: {} + managedStrippingLevel: + EmbeddedLinux: 1 + GameCoreScarlett: 1 + GameCoreXboxOne: 1 + Nintendo Switch: 1 + PS4: 1 + PS5: 1 + QNX: 1 + Stadia: 1 + VisionOS: 1 + WebGL: 1 + Windows Store Apps: 1 + XboxOne: 1 + iPhone: 1 + tvOS: 1 + incrementalIl2cppBuild: {} + suppressCommonWarnings: 1 + allowUnsafeCode: 0 + useDeterministicCompilation: 1 + additionalIl2CppArgs: + scriptingRuntimeVersion: 1 + gcIncremental: 1 + gcWBarrierValidation: 0 + apiCompatibilityLevelPerPlatform: {} + m_RenderingPath: 1 + m_MobileRenderingPath: 1 + metroPackageName: xNode + metroPackageVersion: + metroCertificatePath: + metroCertificatePassword: + metroCertificateSubject: + metroCertificateIssuer: + metroCertificateNotAfter: 0000000000000000 + metroApplicationDescription: xNode + wsaImages: {} + metroTileShortName: + metroTileShowName: 0 + metroMediumTileShowName: 0 + metroLargeTileShowName: 0 + metroWideTileShowName: 0 + metroSupportStreamingInstall: 0 + metroLastRequiredScene: 0 + metroDefaultTileSize: 1 + metroTileForegroundText: 2 + metroTileBackgroundColor: {r: 0.13333334, g: 0.17254902, b: 0.21568628, a: 0} + metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628, a: 1} + metroSplashScreenUseBackgroundColor: 0 + platformCapabilities: {} + metroTargetDeviceFamilies: {} + metroFTAName: + metroFTAFileTypes: [] + metroProtocolName: + vcxProjDefaultLanguage: + XboxOneProductId: + XboxOneUpdateKey: + XboxOneSandboxId: + XboxOneContentId: + XboxOneTitleId: + XboxOneSCId: + XboxOneGameOsOverridePath: + XboxOnePackagingOverridePath: + XboxOneAppManifestOverridePath: + XboxOneVersion: 1.0.0.0 + XboxOnePackageEncryption: 0 + XboxOnePackageUpdateGranularity: 2 + XboxOneDescription: + XboxOneLanguage: + - enus + XboxOneCapability: [] + XboxOneGameRating: {} + XboxOneIsContentPackage: 0 + XboxOneEnhancedXboxCompatibilityMode: 0 + XboxOneEnableGPUVariability: 1 + XboxOneSockets: {} + XboxOneSplashScreen: {fileID: 0} + XboxOneAllowedProductIds: [] + XboxOnePersistentLocalStorageSize: 0 + XboxOneXTitleMemory: 8 + XboxOneOverrideIdentityName: + XboxOneOverrideIdentityPublisher: + vrEditorSettings: {} + cloudServicesEnabled: + UNet: 1 + luminIcon: + m_Name: + m_ModelFolderPath: + m_PortalFolderPath: + luminCert: + m_CertPath: + m_SignPackage: 1 + luminIsChannelApp: 0 + luminVersion: + m_VersionCode: 1 + m_VersionName: + hmiPlayerDataPath: + hmiForceSRGBBlit: 1 + embeddedLinuxEnableGamepadInput: 1 + hmiLogStartupTiming: 0 + hmiCpuConfiguration: + apiCompatibilityLevel: 6 + activeInputHandler: 0 + windowsGamepadBackendHint: 0 + cloudProjectId: + framebufferDepthMemorylessMode: 0 + qualitySettingsNames: [] + projectName: + organizationId: + cloudEnabled: 0 + legacyClampBlendShapeWeights: 0 + hmiLoadingImage: {fileID: 0} + platformRequiresReadableAssets: 0 + virtualTexturingSupportEnabled: 0 + insecureHttpOption: 0 diff --git a/xNode/ProjectSettings/ProjectVersion.txt b/xNode/ProjectSettings/ProjectVersion.txt new file mode 100644 index 0000000..0a60761 --- /dev/null +++ b/xNode/ProjectSettings/ProjectVersion.txt @@ -0,0 +1,2 @@ +m_EditorVersion: 2022.3.5f1 +m_EditorVersionWithRevision: 2022.3.5f1 (9674261d40ee) diff --git a/xNode/ProjectSettings/QualitySettings.asset b/xNode/ProjectSettings/QualitySettings.asset new file mode 100644 index 0000000..7b7658d --- /dev/null +++ b/xNode/ProjectSettings/QualitySettings.asset @@ -0,0 +1,232 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!47 &1 +QualitySettings: + m_ObjectHideFlags: 0 + serializedVersion: 5 + m_CurrentQuality: 5 + m_QualitySettings: + - serializedVersion: 2 + name: Very Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 15 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 1 + textureQuality: 1 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.3 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 4 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.4 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 16 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Medium + pixelLightCount: 1 + shadows: 1 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 1 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 0.7 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 64 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: High + pixelLightCount: 2 + shadows: 2 + shadowResolution: 1 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 40 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 1 + antiAliasing: 0 + softParticles: 0 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 1 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 256 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Very High + pixelLightCount: 3 + shadows: 2 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 70 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 2 + antiAliasing: 2 + softParticles: 1 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 1.5 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 1024 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Ultra + pixelLightCount: 4 + shadows: 2 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 4 + shadowDistance: 150 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 2 + antiAliasing: 2 + softParticles: 1 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 2 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 4096 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + m_PerPlatformDefaultQuality: + Android: 2 + Lumin: 5 + Nintendo 3DS: 5 + Nintendo Switch: 5 + PS4: 5 + PSP2: 2 + Stadia: 5 + Standalone: 5 + WebGL: 3 + Windows Store Apps: 5 + XboxOne: 5 + iPhone: 2 + tvOS: 2 diff --git a/xNode/ProjectSettings/TagManager.asset b/xNode/ProjectSettings/TagManager.asset new file mode 100644 index 0000000..1c92a78 --- /dev/null +++ b/xNode/ProjectSettings/TagManager.asset @@ -0,0 +1,43 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!78 &1 +TagManager: + serializedVersion: 2 + tags: [] + layers: + - Default + - TransparentFX + - Ignore Raycast + - + - Water + - UI + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + m_SortingLayers: + - name: Default + uniqueID: 0 + locked: 0 diff --git a/xNode/ProjectSettings/TimeManager.asset b/xNode/ProjectSettings/TimeManager.asset new file mode 100644 index 0000000..558a017 --- /dev/null +++ b/xNode/ProjectSettings/TimeManager.asset @@ -0,0 +1,9 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!5 &1 +TimeManager: + m_ObjectHideFlags: 0 + Fixed Timestep: 0.02 + Maximum Allowed Timestep: 0.33333334 + m_TimeScale: 1 + Maximum Particle Timestep: 0.03 diff --git a/xNode/ProjectSettings/UnityConnectSettings.asset b/xNode/ProjectSettings/UnityConnectSettings.asset new file mode 100644 index 0000000..a88bee0 --- /dev/null +++ b/xNode/ProjectSettings/UnityConnectSettings.asset @@ -0,0 +1,36 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!310 &1 +UnityConnectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 1 + m_Enabled: 0 + m_TestMode: 0 + m_EventOldUrl: https://api.uca.cloud.unity3d.com/v1/events + m_EventUrl: https://cdp.cloud.unity3d.com/v1/events + m_ConfigUrl: https://config.uca.cloud.unity3d.com + m_DashboardUrl: https://dashboard.unity3d.com + m_TestInitMode: 0 + CrashReportingSettings: + m_EventUrl: https://perf-events.cloud.unity3d.com + m_Enabled: 0 + m_LogBufferSize: 10 + m_CaptureEditorExceptions: 1 + UnityPurchasingSettings: + m_Enabled: 0 + m_TestMode: 0 + UnityAnalyticsSettings: + m_Enabled: 0 + m_TestMode: 0 + m_InitializeOnStartup: 1 + m_PackageRequiringCoreStatsPresent: 0 + UnityAdsSettings: + m_Enabled: 0 + m_InitializeOnStartup: 1 + m_TestMode: 0 + m_IosGameId: + m_AndroidGameId: + m_GameIds: {} + m_GameId: + PerformanceReportingSettings: + m_Enabled: 0 diff --git a/xNode/ProjectSettings/VFXManager.asset b/xNode/ProjectSettings/VFXManager.asset new file mode 100644 index 0000000..3a95c98 --- /dev/null +++ b/xNode/ProjectSettings/VFXManager.asset @@ -0,0 +1,12 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!937362698 &1 +VFXManager: + m_ObjectHideFlags: 0 + m_IndirectShader: {fileID: 0} + m_CopyBufferShader: {fileID: 0} + m_SortShader: {fileID: 0} + m_StripUpdateShader: {fileID: 0} + m_RenderPipeSettingsPath: + m_FixedTimeStep: 0.016666668 + m_MaxDeltaTime: 0.05 diff --git a/xNode/ProjectSettings/VersionControlSettings.asset b/xNode/ProjectSettings/VersionControlSettings.asset new file mode 100644 index 0000000..dca2881 --- /dev/null +++ b/xNode/ProjectSettings/VersionControlSettings.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!890905787 &1 +VersionControlSettings: + m_ObjectHideFlags: 0 + m_Mode: Visible Meta Files + m_CollabEditorSettings: + inProgressEnabled: 1 diff --git a/xNode/ProjectSettings/XRSettings.asset b/xNode/ProjectSettings/XRSettings.asset new file mode 100644 index 0000000..482590c --- /dev/null +++ b/xNode/ProjectSettings/XRSettings.asset @@ -0,0 +1,10 @@ +{ + "m_SettingKeys": [ + "VR Device Disabled", + "VR Device User Alert" + ], + "m_SettingValues": [ + "False", + "False" + ] +} \ No newline at end of file