diff --git a/.github/workflows/linux_workflow.yml b/.github/workflows/linux_workflow.yml index 733bbc66c..66fa7617e 100644 --- a/.github/workflows/linux_workflow.yml +++ b/.github/workflows/linux_workflow.yml @@ -17,28 +17,40 @@ jobs: echo "path of the credentials resource $GITHUB_WORKSPACE/ibm-credentials.txt" export IBM_CREDENTIALS_FILE="$GITHUB_WORKSPACE/ibm-credentials.env" + # Fonts + - name: Install fonts + run: | + echo -n "Installing core fonts" + echo "ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true" | sudo debconf-set-selections + echo "ttf-mscorefonts-installer msttcorefonts/present-mscorefonts-eula note" | sudo debconf-set-selections + sudo apt install ttf-mscorefonts-installer + sudo fc-cache -f + fc-match Arial + # Cache - name: Caching - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: Library - key: Library-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} + key: Library-linux-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} restore-keys: | - Library- + Library-linux # Test stage - name: Unity Test runner (edit and play mode) - uses: game-ci/unity-test-runner@v2.0.0-alpha-7 + uses: game-ci/unity-test-runner@v2.0.3 env: UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} with: githubToken: ${{ secrets.GITHUB_TOKEN }} - unityVersion: 2020.3.13f1 - + unityVersion: 2021.3.8f1 + build: name: Build Unity runs-on: ubuntu-latest needs: test + outputs: + buildVersion: ${{ steps.buildStep.outputs.buildVersion }} steps: # Activation stage - name: Checkout repository @@ -52,19 +64,30 @@ jobs: ls -la echo "path of the credentials resource $GITHUB_WORKSPACE/ibm-credentials.txt" export IBM_CREDENTIALS_FILE="$GITHUB_WORKSPACE/ibm-credentials.env" + export TARGET_PLATFORM="Android" + + # Fonts + - name: Install fonts + run: | + echo -n "Installing core fonts" + echo "ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true" | sudo debconf-set-selections + echo "ttf-mscorefonts-installer msttcorefonts/present-mscorefonts-eula note" | sudo debconf-set-selections + sudo apt install ttf-mscorefonts-installer + sudo fc-cache -f + fc-match Arial # Cache - name: Caching - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: Library - key: Library-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} + key: Library-linux-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} restore-keys: | - Library- + Library-linux # Build stage - name: Unity builder - uses: game-ci/unity-builder@v2 + uses: game-ci/unity-builder@v2.1.1 id: buildStep env: UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} @@ -72,7 +95,7 @@ jobs: UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} with: targetPlatform: Android - unityVersion: 2020.3.13f1 + unityVersion: 2021.3.8f1 versioning: Semantic # dirty build needed to include generated Watson credentials allowDirtyBuild: true @@ -80,7 +103,28 @@ jobs: - name: Upload build artifacts uses: actions/upload-artifact@v2 with: - name: Build + name: Android path: build - retention-days: 90 + retention-days: 3 if-no-files-found: error + +# Deploy stage + prerelease-notification: + name: Prerelease Slack notification + runs-on: ubuntu-latest + needs: build + if: github.ref == 'refs/heads/develop' && !github.event.pull_request + env: + SLACK_URL: ${{ secrets.SLACK_URL }} + COMMIT_MESSAGE: ${{ github.event.head_commit.message }} + APP_VERSION: ${{ needs.build.outputs.buildVersion }} + TARGET_PLATFORM: ${{ runner.os }} + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Post notification + run: | + echo $APP_VERSION + sudo apt-get update && sudo apt-get -y install curl + chmod +x ./ci/notify-preview.sh && ./ci/notify-preview.sh diff --git a/.github/workflows/unity_activation_windows.yml b/.github/workflows/unity_activation_windows.yml index 4f0a95431..61e0a9d44 100644 --- a/.github/workflows/unity_activation_windows.yml +++ b/.github/workflows/unity_activation_windows.yml @@ -14,11 +14,11 @@ jobs: - name: Setup Unity uses: kuler90/setup-unity@v1.0.8 with: - unity-version: 2020.3.13f1 + unity-version: 2021.3.8f1 # Request manual activation file - name: Request manual activation file - run: ci\get_windows_activation_file.bat + run: .\ci\get_windows_activation_file.bat # Upload artifact (Unity_v20XX.X.XXXX.alf) - name: Expose as artifact uses: actions/upload-artifact@v2 diff --git a/.github/workflows/windows_workflow.yml b/.github/workflows/windows_workflow.yml index 45d9c044a..9600ad344 100644 --- a/.github/workflows/windows_workflow.yml +++ b/.github/workflows/windows_workflow.yml @@ -30,6 +30,7 @@ jobs: echo -n "$env:ASSISTANTKEYS" > $env:GITHUB_WORKSPACE/ibm-credentials.env echo "path of the credentials resource $env:GITHUB_WORKSPACE/Assets/Resources/ibm-credentials.txt" $env:IBM_CREDENTIALS_FILE="$env:GITHUB_WORKSPACE/ibm-credentials.env" + $env:TARGET_PLATFORM="Hololens" # Cache - name: Caching @@ -47,7 +48,7 @@ jobs: # Build stage - name: Unity builder - uses: game-ci/unity-builder@v2.0.1 + uses: game-ci/unity-builder@v2.1.1 id: buildStep env: UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} @@ -151,6 +152,7 @@ jobs: SLACK_URL: ${{ secrets.SLACK_URL }} COMMIT_MESSAGE: ${{ github.event.head_commit.message }} APP_VERSION: ${{ needs.build_unity.outputs.buildVersion }} + TARGET_PLATFORM: ${{ runner.os }} steps: - name: Checkout repository uses: actions/checkout@v2 diff --git a/.gitignore b/.gitignore index dd425275c..da27e0a9b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ /[Bb]uild/ /[Bb]uilds/ /[Ll]ogs/ +/[Uu]ser[Ss]ettings/ /[Mm]emoryCaptures/ UWP/ QCAR/ @@ -35,7 +36,6 @@ QCAR/ .vs/ .vscode/ -Assets/TextMesh Pro* # Gradle cache directory .gradle/ diff --git a/Assets/AddressableAssetsData/AddressableAssetSettings.asset b/Assets/AddressableAssetsData/AddressableAssetSettings.asset index 1b0de928a..3efa9c643 100644 --- a/Assets/AddressableAssetsData/AddressableAssetSettings.asset +++ b/Assets/AddressableAssetsData/AddressableAssetSettings.asset @@ -13,18 +13,32 @@ MonoBehaviour: m_Name: AddressableAssetSettings m_EditorClassIdentifier: m_DefaultGroup: bec1afb347441f242b5ca379ab102994 + m_CachedHash: + serializedVersion: 2 + Hash: 00000000000000000000000000000000 m_OptimizeCatalogSize: 0 m_BuildRemoteCatalog: 0 m_BundleLocalCatalog: 0 + m_CatalogRequestsTimeout: 0 m_DisableCatalogUpdateOnStart: 0 m_IgnoreUnsupportedFilesInBuild: 0 m_UniqueBundleIds: 0 + m_NonRecursiveBuilding: 1 + m_CCDEnabled: 0 m_maxConcurrentWebRequests: 500 m_ContiguousBundles: 0 + m_StripUnityVersionFromBundleBuild: 0 + m_DisableVisibleSubAssetRepresentations: 0 + m_ShaderBundleNaming: 0 + m_ShaderBundleCustomNaming: + m_MonoScriptBundleNaming: 0 + m_MonoScriptBundleCustomNaming: m_RemoteCatalogBuildPath: m_Id: m_RemoteCatalogLoadPath: m_Id: + m_ContentStateBuildPath: + m_BuildAddressablesWithPlayerBuild: 2 m_overridePlayerVersion: m_GroupAssets: - {fileID: 11400000, guid: a5b5fc9452f7c4f41a0c000b52bdd45e, type: 2} diff --git a/Assets/AddressableAssetsData/Android/addressables_content_state.bin b/Assets/AddressableAssetsData/Android/addressables_content_state.bin index bc66b12c3..4adea71ec 100644 Binary files a/Assets/AddressableAssetsData/Android/addressables_content_state.bin and b/Assets/AddressableAssetsData/Android/addressables_content_state.bin differ diff --git a/Assets/AddressableAssetsData/AssetGroups/Glyphs.asset b/Assets/AddressableAssetsData/AssetGroups/Glyphs.asset index 2d435c1cc..96ba21810 100644 --- a/Assets/AddressableAssetsData/AssetGroups/Glyphs.asset +++ b/Assets/AddressableAssetsData/AssetGroups/Glyphs.asset @@ -21,234 +21,118 @@ MonoBehaviour: m_Address: Glyphs/Allow m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 1304825756969130, guid: 390ddb1a66da6c9409f36a16b0d75468, - type: 3} - m_TargetAsset: {fileID: 1304825756969130, guid: 390ddb1a66da6c9409f36a16b0d75468, - type: 3} - m_GUID: a904bb583f6cde548b28f46fa2794792 m_Address: Glyphs/Assemble m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 3576418608928814886, guid: a904bb583f6cde548b28f46fa2794792, - type: 3} - m_TargetAsset: {fileID: 3576418608928814886, guid: a904bb583f6cde548b28f46fa2794792, - type: 3} - m_GUID: 0d15aa289366edb46b85fa3eea4f97a0 m_Address: Glyphs/CloseBox m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 4506147086824284070, guid: 0d15aa289366edb46b85fa3eea4f97a0, - type: 3} - m_TargetAsset: {fileID: 4506147086824284070, guid: 0d15aa289366edb46b85fa3eea4f97a0, - type: 3} - m_GUID: e0d3f7f55e25f864284b3a3bf5dfb5e7 m_Address: Glyphs/Cut m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 3194395810828297597, guid: e0d3f7f55e25f864284b3a3bf5dfb5e7, - type: 3} - m_TargetAsset: {fileID: 3194395810828297597, guid: e0d3f7f55e25f864284b3a3bf5dfb5e7, - type: 3} - m_GUID: 65f307c69fdbd2448b0c2c91ff78a1f4 m_Address: Glyphs/Deny m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 1972968427663652, guid: 65f307c69fdbd2448b0c2c91ff78a1f4, - type: 3} - m_TargetAsset: {fileID: 1972968427663652, guid: 65f307c69fdbd2448b0c2c91ff78a1f4, - type: 3} - m_GUID: 10327f0f88088ce468bbdf274b5a3c89 m_Address: Glyphs/Disassemble m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 4537887508427888315, guid: 10327f0f88088ce468bbdf274b5a3c89, - type: 3} - m_TargetAsset: {fileID: 4537887508427888315, guid: 10327f0f88088ce468bbdf274b5a3c89, - type: 3} - m_GUID: 3e728cb44ea41e44e9e2b27e1a1c0c30 m_Address: Glyphs/Drill m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 7245924175676296436, guid: 3e728cb44ea41e44e9e2b27e1a1c0c30, - type: 3} - m_TargetAsset: {fileID: 7245924175676296436, guid: 3e728cb44ea41e44e9e2b27e1a1c0c30, - type: 3} - m_GUID: 2f584310852efaa43a4b5aead3e893ef m_Address: Glyphs/GlyphListItem m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 4872990317705957809, guid: 2f584310852efaa43a4b5aead3e893ef, - type: 3} - m_TargetAsset: {fileID: 4872990317705957809, guid: 2f584310852efaa43a4b5aead3e893ef, - type: 3} - m_GUID: 585afb2c3b18205459fb68f86c552e43 m_Address: Glyphs/Highlight m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 1978661282617106, guid: 585afb2c3b18205459fb68f86c552e43, - type: 3} - m_TargetAsset: {fileID: 1978661282617106, guid: 585afb2c3b18205459fb68f86c552e43, - type: 3} - m_GUID: 9b2a9b4fc29c0864f98f21e334fb1ba8 m_Address: Glyphs/Inspect m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 7659458282009190870, guid: 9b2a9b4fc29c0864f98f21e334fb1ba8, - type: 3} - m_TargetAsset: {fileID: 7659458282009190870, guid: 9b2a9b4fc29c0864f98f21e334fb1ba8, - type: 3} - m_GUID: c13d4025e43d9d5439abbd613c768355 m_Address: Glyphs/Lift m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 5544241550518555407, guid: c13d4025e43d9d5439abbd613c768355, - type: 3} - m_TargetAsset: {fileID: 5544241550518555407, guid: c13d4025e43d9d5439abbd613c768355, - type: 3} - m_GUID: 601951ae38c8d154d9dc33d7cfcb6960 m_Address: Glyphs/Locate m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 7968610991374755154, guid: 601951ae38c8d154d9dc33d7cfcb6960, - type: 3} - m_TargetAsset: {fileID: 7968610991374755154, guid: 601951ae38c8d154d9dc33d7cfcb6960, - type: 3} - m_GUID: c22a1e60998217846891d86ad6cb04bd m_Address: Glyphs/Lower m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 347776697429262117, guid: c22a1e60998217846891d86ad6cb04bd, - type: 3} - m_TargetAsset: {fileID: 347776697429262117, guid: c22a1e60998217846891d86ad6cb04bd, - type: 3} - m_GUID: bb0d02f6241dbc7468efb750b436c358 m_Address: Glyphs/Lubricate m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 4059356328935049877, guid: bb0d02f6241dbc7468efb750b436c358, - type: 3} - m_TargetAsset: {fileID: 4059356328935049877, guid: bb0d02f6241dbc7468efb750b436c358, - type: 3} - m_GUID: 06a924b8c82689b4b98c570566bf2310 m_Address: Glyphs/Measure m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 1057627277752086267, guid: 06a924b8c82689b4b98c570566bf2310, - type: 3} - m_TargetAsset: {fileID: 1057627277752086267, guid: 06a924b8c82689b4b98c570566bf2310, - type: 3} - m_GUID: dbf5935faea783f43a5771d799cb1b9c m_Address: Glyphs/OpenBox m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 958834117857690979, guid: dbf5935faea783f43a5771d799cb1b9c, - type: 3} - m_TargetAsset: {fileID: 958834117857690979, guid: dbf5935faea783f43a5771d799cb1b9c, - type: 3} - m_GUID: af7017d74390e6e479c0c4635fef6586 m_Address: Glyphs/Pack m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 3175210850286594304, guid: af7017d74390e6e479c0c4635fef6586, - type: 3} - m_TargetAsset: {fileID: 3175210850286594304, guid: af7017d74390e6e479c0c4635fef6586, - type: 3} - m_GUID: 7ec0aa5f38a21c645b2935abea1fe59d m_Address: Glyphs/Paint m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 9029676622764544912, guid: 7ec0aa5f38a21c645b2935abea1fe59d, - type: 3} - m_TargetAsset: {fileID: 9029676622764544912, guid: 7ec0aa5f38a21c645b2935abea1fe59d, - type: 3} - m_GUID: 7d192435d07559d4da48f8a18025422f m_Address: Glyphs/Pick m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 158599119166758454, guid: 7d192435d07559d4da48f8a18025422f, - type: 3} - m_TargetAsset: {fileID: 158599119166758454, guid: 7d192435d07559d4da48f8a18025422f, - type: 3} - m_GUID: 1dde8c2ebd877ec409316612103caf75 m_Address: Glyphs/Place m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 3016307943603889182, guid: 1dde8c2ebd877ec409316612103caf75, - type: 3} - m_TargetAsset: {fileID: 3016307943603889182, guid: 1dde8c2ebd877ec409316612103caf75, - type: 3} - m_GUID: 45cb0b28857f7d6469284a87cc0de91f m_Address: Glyphs/Plug m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 2680635587285739900, guid: 45cb0b28857f7d6469284a87cc0de91f, - type: 3} - m_TargetAsset: {fileID: 2680635587285739900, guid: 45cb0b28857f7d6469284a87cc0de91f, - type: 3} - m_GUID: 903391808b3036f4f9862cb2979dc004 m_Address: Glyphs/Point m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 6850339645459306925, guid: 903391808b3036f4f9862cb2979dc004, - type: 3} - m_TargetAsset: {fileID: 6850339645459306925, guid: 903391808b3036f4f9862cb2979dc004, - type: 3} - m_GUID: e11bdbbae7073a640b10c1d5f0c33659 m_Address: Glyphs/Rotate m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 7315173733626673392, guid: e11bdbbae7073a640b10c1d5f0c33659, - type: 3} - m_TargetAsset: {fileID: 7315173733626673392, guid: e11bdbbae7073a640b10c1d5f0c33659, - type: 3} - m_GUID: c02f9bb665515c0419dd65ccd87346de m_Address: Glyphs/Screw m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 137609056719891418, guid: c02f9bb665515c0419dd65ccd87346de, - type: 3} - m_TargetAsset: {fileID: 137609056719891418, guid: c02f9bb665515c0419dd65ccd87346de, - type: 3} - m_GUID: af696c411ebac5349acf29edb0718ca4 m_Address: Glyphs/StandHere m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 5573534784247367279, guid: af696c411ebac5349acf29edb0718ca4, - type: 3} - m_TargetAsset: {fileID: 5573534784247367279, guid: af696c411ebac5349acf29edb0718ca4, - type: 3} - m_GUID: 3b11ad4136b44404f960632ea591fe8a m_Address: Glyphs/Unfasten m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 6047936985187562710, guid: 3b11ad4136b44404f960632ea591fe8a, - type: 3} - m_TargetAsset: {fileID: 6047936985187562710, guid: 3b11ad4136b44404f960632ea591fe8a, - type: 3} - m_GUID: dd56bab376d94ad4e98ee41583eac2d9 m_Address: Glyphs/Unpack m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 6525011647562524553, guid: dd56bab376d94ad4e98ee41583eac2d9, - type: 3} - m_TargetAsset: {fileID: 6525011647562524553, guid: dd56bab376d94ad4e98ee41583eac2d9, - type: 3} - m_GUID: bfc3139ec6be30d4a99383a37daf43ad m_Address: Glyphs/Unplug m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 4947167224918011342, guid: bfc3139ec6be30d4a99383a37daf43ad, - type: 3} - m_TargetAsset: {fileID: 4947167224918011342, guid: bfc3139ec6be30d4a99383a37daf43ad, - type: 3} - m_GUID: ba9b389b4ea219545aea8d84c0ab908a m_Address: Glyphs/Unscrew m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 7020582290389023418, guid: ba9b389b4ea219545aea8d84c0ab908a, - type: 3} - m_TargetAsset: {fileID: 7020582290389023418, guid: ba9b389b4ea219545aea8d84c0ab908a, - type: 3} m_ReadOnly: 0 m_Settings: {fileID: 11400000, guid: 6567f5df32509cd439818836d4d2201c, type: 2} m_SchemaSet: diff --git a/Assets/AddressableAssetsData/AssetGroups/Other.asset b/Assets/AddressableAssetsData/AssetGroups/Other.asset index 24f951b84..460aac7b8 100644 --- a/Assets/AddressableAssetsData/AssetGroups/Other.asset +++ b/Assets/AddressableAssetsData/AssetGroups/Other.asset @@ -21,106 +21,74 @@ MonoBehaviour: m_Address: AudioPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 2fc91a2ab4c130040b799bc439ca08f6 m_Address: PluginControllerPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 7f7a08ef861ac874eb2ac9315bcd0483 m_Address: SymbolPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 33ee35f2b6514524b86ef8c94b325e7d m_Address: LabelPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 6678a5e936d1b1e4783a9c78eec8a607 m_Address: GhosttrackPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: e43e37bc8d5683e4293ff132194926b5 m_Address: GhosttrackPrefabFemale m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 60b76012d454e7f4b8a4d0f1c28f5647 m_Address: VideoPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 7ce33acc0202cfc4c8d14cff2629a2f0 m_Address: DetectPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: d2d97c882f583094f9b9e614d80aa75a m_Address: ImageMarkerPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: e211e2fdf4bb16b46b691fc3a5f45964 m_Address: ImagePrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 676f25c39d6a6cf47a4258cef374ec0a m_Address: pickandplaceprefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: b7052b57f3db77841bbce81c5aeab579 m_Address: DrawingPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: f870f2213cfdb9440b8e7c800b719cb1 m_Address: AmbientLight m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: e8878ce4fc521ab498627b4f4b1dfde8 m_Address: Sun m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 886d836dc11629a429138ccc2f21188f m_Address: SensorContainerPrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: 668f4151a0fb9ff4ba11716f682d6cc6 m_Address: ValuePrefab m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 0} - m_TargetAsset: {fileID: 0} - m_GUID: d0464d2576401014d92b0ede9b680bc0 m_Address: PlayerTaskStation m_ReadOnly: 0 m_SerializedLabels: [] - m_MainAsset: {fileID: 2232750753583396478, guid: d0464d2576401014d92b0ede9b680bc0, - type: 3} - m_TargetAsset: {fileID: 2232750753583396478, guid: d0464d2576401014d92b0ede9b680bc0, - type: 3} + - m_GUID: 177bff737c69d564ebb225d7fe7fc402 + m_Address: WEKITCalibrationMarker + m_ReadOnly: 0 + m_SerializedLabels: [] m_ReadOnly: 0 m_Settings: {fileID: 11400000, guid: 6567f5df32509cd439818836d4d2201c, type: 2} m_SchemaSet: diff --git a/Assets/Common/Icons.meta b/Assets/Common/Icons.meta new file mode 100644 index 000000000..ef22c49b6 --- /dev/null +++ b/Assets/Common/Icons.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6907c1cb917d04a8f9c6ce4fe3c7c3df +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Common/Icons/UWP.meta b/Assets/Common/Icons/UWP.meta new file mode 100644 index 000000000..69ce51e1e --- /dev/null +++ b/Assets/Common/Icons/UWP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 61e781d199f6efd4cb2d7f936c96e642 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Default.ruleset b/Assets/Default.ruleset index 8d8f4502a..c9a4a299d 100644 --- a/Assets/Default.ruleset +++ b/Assets/Default.ruleset @@ -1,13 +1,21 @@  - + + + + + + + + + \ No newline at end of file diff --git a/Assets/IBMWatsonSDK/IBMSdkCore/ThirdParty/Jwt/src/JWT/obj.meta b/Assets/Editor/Instant Screenshot.meta similarity index 77% rename from Assets/IBMWatsonSDK/IBMSdkCore/ThirdParty/Jwt/src/JWT/obj.meta rename to Assets/Editor/Instant Screenshot.meta index 3c328aa1b..fd459131d 100644 --- a/Assets/IBMWatsonSDK/IBMSdkCore/ThirdParty/Jwt/src/JWT/obj.meta +++ b/Assets/Editor/Instant Screenshot.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 60170f00905324f1f9a5dbde500abda0 +guid: 713508f21a0773b4d91235a6c5bce99c folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs b/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs new file mode 100644 index 000000000..b7730138f --- /dev/null +++ b/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs @@ -0,0 +1,337 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using MirageXR; +using UnityEditor; +using UnityEngine; + +[ExecuteInEditMode] +public class Screenshot : EditorWindow +{ + + private struct Screen + { + public Vector2Int resolution; + public DeviceFormat format; + } + + private readonly List _sizes = new List + { + new Screen + { + resolution = new Vector2Int(1242, 2688), //6.5 inch + format = DeviceFormat.Phone, + }, + new Screen + { + resolution = new Vector2Int(1242, 2208), //5.5 inch + format = DeviceFormat.Phone, + }, + new Screen + { + resolution = new Vector2Int(2732, 2048), //12.9 inch + format = DeviceFormat.Tablet, + }, + }; + + private string _path = string.Empty; + private Camera _camera; + private ViewCamera _viewCamera; + + [MenuItem("Tools/Instant Screenshot")] + public static void ShowWindow() + { + var editorWindow = GetWindow(typeof(Screenshot)); + editorWindow.autoRepaintOnSceneChange = true; + editorWindow.Show(); + editorWindow.titleContent = new GUIContent("Screenshot"); + } + + private void OnGUI() + { + GUILayout.Label("Save Path", EditorStyles.boldLabel); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.TextField(_path, GUILayout.ExpandWidth(false)); + if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false))) + { + _path = EditorUtility.SaveFolderPanel("Path to Save Images", _path, Application.dataPath); + } + + EditorGUILayout.EndHorizontal(); + EditorGUILayout.HelpBox("Choose the folder in which to save the screenshots ", MessageType.None); + EditorGUILayout.Space(); + + if (GUILayout.Button("Take Screenshot", GUILayout.MaxWidth(200), GUILayout.MinHeight(60))) + { + if (_path == string.Empty) + { + _path = EditorUtility.SaveFolderPanel("Path to Save Images", _path, Application.dataPath); + } + + TakeScreenShots(_sizes); + } + + EditorGUILayout.Space(); + EditorGUILayout.BeginHorizontal(); + + if (GUILayout.Button("Open Folder", GUILayout.MaxWidth(200), GUILayout.MinHeight(60))) + { + Application.OpenURL($"file://{_path}"); + } + + EditorGUILayout.EndHorizontal(); + EditorGUILayout.HelpBox("In case of any error, make sure you have Unity Pro as the plugin requires Unity Pro to work.", MessageType.Info); + } + + private async void TakeScreenShots(IEnumerable screens) + { + try + { + _viewCamera = RootView_v2.Instance.viewCamera; + _camera = RootView_v2.Instance.viewCamera.GetComponent(); + } + catch (Exception e) + { + Debug.LogError(e); + return; + } + + var oldSize = GetResolution(); + var oldFormat = _viewCamera.format; + + foreach (var screen in screens) + { + await ApplyScreen(screen); + + var path = Path.Combine(_path, $"screen_{screen.resolution.x}x{screen.resolution.y}"); + Directory.CreateDirectory(path); + var filename = Path.Combine(path, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.png"); + CaptureScreenshot(_camera, screen.resolution.x, screen.resolution.y, filename); + } + + await ApplyScreen(new Screen { resolution = oldSize, format = oldFormat }); + } + + private async Task ApplyScreen(Screen screen) + { + await SetResolution(screen.resolution); + await _viewCamera.SetupFormat(screen.format); + + } + + private static async Task SetResolution(Vector2Int size) + { + var window = (EditorWindow)Resources.FindObjectsOfTypeAll(typeof(EditorWindow)).FirstOrDefault(t => t.GetType().FullName == "UnityEditor.GameView"); + if (window == null) + { + return; + } + + var type = window.GetType(); + + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | + BindingFlags.Static | BindingFlags.Instance | + BindingFlags.DeclaredOnly; + + var methods = type.GetMethods(bindingFlags); + var onLostFocus = methods.FirstOrDefault(t => t.Name == "OnLostFocus"); + var onResized = methods.FirstOrDefault(t => t.Name == "OnResized"); + + var gameViewSizeProperty = GetAllProperties(type).FirstOrDefault(t => t.PropertyType.FullName == "UnityEditor.GameViewSize"); + if (TryGetPropertyValue(window, gameViewSizeProperty, out var gameViewSize)) + { + var properties = GetAllProperties(gameViewSize.GetType()).ToArray(); + var widthProperty = properties.FirstOrDefault(t => t.Name == "width"); + var heightProperty = properties.FirstOrDefault(t => t.Name == "height"); + + TrySetPropertyValue(gameViewSize, widthProperty, size.x); + TrySetPropertyValue(gameViewSize, heightProperty, size.y); + + TryCallMethod(window, onLostFocus); + TryCallMethod(window, onResized); + } + + window.Repaint(); + + await Task.Delay(500); + } + + private static Vector2Int GetResolution() + { + var window = (EditorWindow)Resources.FindObjectsOfTypeAll(typeof(EditorWindow)).FirstOrDefault(t => t.GetType().FullName == "UnityEditor.GameView"); + if (window == null) return Vector2Int.zero; + + var type = window.GetType(); + + var gameViewSizeProperty = GetAllProperties(type).FirstOrDefault(t => t.PropertyType.FullName == "UnityEditor.GameViewSize"); + if (TryGetPropertyValue(window, gameViewSizeProperty, out var gameViewSize)) + { + var properties = GetAllProperties(gameViewSize.GetType()).ToArray(); + var widthProperty = properties.FirstOrDefault(t => t.Name == "width"); + var heightProperty = properties.FirstOrDefault(t => t.Name == "height"); + + TryGetPropertyValue(gameViewSize, widthProperty, out var width); + TryGetPropertyValue(gameViewSize, heightProperty, out var height); + + return new Vector2Int(width, height); + } + + return Vector2Int.zero; + } + + private static void CaptureScreenshot(Camera cam, int width, int height, string filePath) + { + var bakCamTargetTexture = cam.targetTexture; + var bakCamClearFlags = cam.clearFlags; + var bakRenderTextureActive = RenderTexture.active; + + var texTransparent = new Texture2D(width, height, TextureFormat.ARGB32, false); + var renderTexture = RenderTexture.GetTemporary(width, height, 24, RenderTextureFormat.ARGB32); + var grabArea = new Rect(0, 0, width, height); + + RenderTexture.active = renderTexture; + cam.targetTexture = renderTexture; + cam.clearFlags = CameraClearFlags.SolidColor; + + cam.backgroundColor = Color.clear; + cam.Render(); + texTransparent.ReadPixels(grabArea, 0, 0); + texTransparent.Apply(); + + var pngShot = texTransparent.EncodeToPNG(); + File.WriteAllBytes(filePath, pngShot); + + cam.clearFlags = bakCamClearFlags; + cam.targetTexture = bakCamTargetTexture; + RenderTexture.active = bakRenderTextureActive; + RenderTexture.ReleaseTemporary(renderTexture); + + Destroy(texTransparent); + } + + #region Help functions + + private static IEnumerable GetAllFields(Type type) + { + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | + BindingFlags.Static | BindingFlags.Instance | + BindingFlags.DeclaredOnly; + + return type == null ? Enumerable.Empty() : type.GetFields(bindingFlags).Concat(GetAllFields(type.BaseType)); + } + + private static IEnumerable GetAllProperties(Type type) + { + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | + BindingFlags.Static | BindingFlags.Instance | + BindingFlags.DeclaredOnly; + + return type == null ? Enumerable.Empty() : type.GetProperties(bindingFlags).Concat(GetAllProperties(type.BaseType)); + } + + private static IEnumerable GetAllMethods(Type type) + { + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | + BindingFlags.Static | BindingFlags.Instance | + BindingFlags.DeclaredOnly; + + return type == null ? Enumerable.Empty() : type.GetMethods(bindingFlags).Concat(GetAllMethods(type.BaseType)); + } + + private static FieldInfo GetFieldFromTypeByName(Type type, string fieldName) + { + return GetAllFields(type).FirstOrDefault(t => t.Name == fieldName); + } + + private static Dictionary> GetAllTypesAndPropertiesNamesFromBaseType() where T : class + { + var dictionary = new Dictionary>(); + var types = GetAllSubclassesOfType(); + foreach (var type in types) + { + var names = GetAllProperties(type).Select(t => t.Name). + Concat(GetAllMethods(type).Select(t => t.Name)); + + dictionary.Add(type.FullName, new HashSet(names)); + } + + return dictionary; + } + + private static IEnumerable GetAllSubclassesOfType() where T : class + { + return typeof(T).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(T))); + } + + private static bool TryGetFieldValue(object instance, FieldInfo fieldInfo, out T value) + { + try + { + value = (T)fieldInfo.GetValue(instance); + return true; + } + catch (Exception) + { + value = default; + return false; + } + } + + private static bool TrySetFieldValue(object instance, FieldInfo fieldInfo, object value) + { + try + { + fieldInfo.SetValue(instance, value); + return true; + } + catch (Exception) + { + return false; + } + } + + private static bool TryGetPropertyValue(object instance, PropertyInfo propertyInfo, out T value) + { + try + { + value = (T)propertyInfo.GetValue(instance); + return true; + } + catch (Exception) + { + value = default; + return false; + } + } + + private static bool TrySetPropertyValue(object instance, PropertyInfo propertyInfo, object value) + { + try + { + propertyInfo.SetValue(instance, value); + return true; + } + catch (Exception) + { + return false; + } + } + + private static bool TryCallMethod(object instance, MethodInfo methodInfo, params object[] values) + { + try + { + methodInfo.Invoke(instance, values); + return true; + } + catch (Exception) + { + return false; + } + } + #endregion +} \ No newline at end of file diff --git a/Assets/MirageXR/Player/Resources/Prefabs/Calibration/CalibrationLoadingEvent.cs.meta b/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs.meta similarity index 83% rename from Assets/MirageXR/Player/Resources/Prefabs/Calibration/CalibrationLoadingEvent.cs.meta rename to Assets/Editor/Instant Screenshot/ScreenshotTaker.cs.meta index 41c42ce7c..cb4f3e200 100644 --- a/Assets/MirageXR/Player/Resources/Prefabs/Calibration/CalibrationLoadingEvent.cs.meta +++ b/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: fd3d45b60a4350541a05687beae52aeb +guid: 1f43438d3f4cd402f8f372cbb8930f66 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/Editor/Vuforia/ImageTargetTextures/MirageXRTargets/target_scaled.jpg.meta b/Assets/Editor/Vuforia/ImageTargetTextures/MirageXRTargets/target_scaled.jpg.meta index 94fbd1f6b..a05840e3c 100644 --- a/Assets/Editor/Vuforia/ImageTargetTextures/MirageXRTargets/target_scaled.jpg.meta +++ b/Assets/Editor/Vuforia/ImageTargetTextures/MirageXRTargets/target_scaled.jpg.meta @@ -20,10 +20,11 @@ TextureImporter: externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 - isReadable: 0 + isReadable: 1 streamingMipmaps: 0 streamingMipmapsPriority: 0 vTOnly: 0 + ignoreMasterTextureLimit: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 @@ -160,6 +161,7 @@ TextureImporter: edges: [] weights: [] secondaryTextures: [] + nameFileIdTable: {} spritePackingTag: pSDRemoveMatte: 0 pSDShowRemoveMatteOption: 0 diff --git a/Assets/Editor/Vuforia/ImageTargetTextures/WEKITCalibration/WEKITCalibrationTool_scaled.jpg.meta b/Assets/Editor/Vuforia/ImageTargetTextures/WEKITCalibration/WEKITCalibrationTool_scaled.jpg.meta index ba1adf5fc..b9bafc554 100644 --- a/Assets/Editor/Vuforia/ImageTargetTextures/WEKITCalibration/WEKITCalibrationTool_scaled.jpg.meta +++ b/Assets/Editor/Vuforia/ImageTargetTextures/WEKITCalibration/WEKITCalibrationTool_scaled.jpg.meta @@ -27,6 +27,7 @@ TextureImporter: streamingMipmaps: 0 streamingMipmapsPriority: 0 vTOnly: 0 + ignoreMasterTextureLimit: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 @@ -151,6 +152,7 @@ TextureImporter: edges: [] weights: [] secondaryTextures: [] + nameFileIdTable: {} spritePackingTag: pSDRemoveMatte: 0 pSDShowRemoveMatteOption: 0 diff --git a/Assets/MRTK/Shaders/MRTK.Shaders.sentinel b/Assets/MRTK/Shaders/MRTK.Shaders.sentinel index 03714d5f1..c7d29ad30 100644 --- a/Assets/MRTK/Shaders/MRTK.Shaders.sentinel +++ b/Assets/MRTK/Shaders/MRTK.Shaders.sentinel @@ -1 +1 @@ -ver: 1 \ No newline at end of file +ver: 2 \ No newline at end of file diff --git a/Assets/MRTK/Shaders/MixedRealityStandard.shader b/Assets/MRTK/Shaders/MixedRealityStandard.shader index 7de7dbaaa..06f2cc48f 100644 --- a/Assets/MRTK/Shaders/MixedRealityStandard.shader +++ b/Assets/MRTK/Shaders/MixedRealityStandard.shader @@ -184,8 +184,6 @@ Shader "Mixed Reality Toolkit/Standard" #pragma shader_feature _ENVIRONMENT_COLORING #pragma shader_feature _IGNORE_Z_SCALE - #define IF(a, b, c) lerp(b, c, step((fixed) (a), 0.0)); - #include "UnityCG.cginc" #include "UnityUI.cginc" #include "UnityStandardConfig.cginc" @@ -279,7 +277,7 @@ Shader "Mixed Reality Toolkit/Standard" UNITY_VERTEX_INPUT_INSTANCE_ID }; - struct v2f + struct v2f { float4 position : SV_POSITION; #if defined(_BORDER_LIGHT) @@ -456,7 +454,7 @@ Shader "Mixed Reality Toolkit/Standard" #if defined(_ROUND_CORNERS) #if defined(_INDEPENDENT_CORNERS) - float4 _RoundCornersRadius; + float4 _RoundCornersRadius; #else fixed _RoundCornerRadius; #endif @@ -473,7 +471,7 @@ Shader "Mixed Reality Toolkit/Standard" #endif #if defined(_ROUND_CORNERS) || defined(_BORDER_LIGHT) - fixed _EdgeSmoothingValue; + float _EdgeSmoothingValue; #endif #if defined(_INNER_GLOW) @@ -530,7 +528,7 @@ Shader "Mixed Reality Toolkit/Standard" { float proximityLightDistance = dot(proximityLight.xyz - worldPosition, worldNormal); #if defined(_PROXIMITY_LIGHT_TWO_SIDED) - worldNormal = IF(proximityLightDistance < 0.0, -worldNormal, worldNormal); + worldNormal = proximityLightDistance < 0.0 ? -worldNormal : worldNormal; proximityLightDistance = abs(proximityLightDistance); #endif float normalizedProximityLightDistance = saturate(proximityLightDistance * proximityLightParams.y); @@ -556,12 +554,12 @@ Shader "Mixed Reality Toolkit/Standard" return length(max(abs(position) - cornerCircleDistance, 0.0)) - cornerCircleRadius; } - inline fixed RoundCornersSmooth(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) + inline float RoundCornersSmooth(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) { return smoothstep(1.0, 0.0, PointVsRoundedBox(position, cornerCircleDistance, cornerCircleRadius) / _EdgeSmoothingValue); } - inline fixed RoundCorners(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) + inline float RoundCorners(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) { #if defined(_TRANSPARENT) return RoundCornersSmooth(position, cornerCircleDistance, cornerCircleRadius); @@ -668,7 +666,7 @@ Shader "Mixed Reality Toolkit/Standard" #if defined(_BORDER_LIGHT) || defined(_ROUND_CORNERS) o.uv.xy = TRANSFORM_TEX(v.uv, _MainTex); - + float minScale = min(min(o.scale.x, o.scale.y), o.scale.z); #if defined(_BORDER_LIGHT) @@ -723,8 +721,8 @@ Shader "Mixed Reality Toolkit/Standard" #if defined(_BORDER_LIGHT) float scaleRatio = min(o.scale.x, o.scale.y) / max(o.scale.x, o.scale.y); - o.uv.z = IF(o.scale.x > o.scale.y, 1.0 - (borderWidth * scaleRatio), 1.0 - borderWidth); - o.uv.w = IF(o.scale.x > o.scale.y, 1.0 - borderWidth, 1.0 - (borderWidth * scaleRatio)); + o.uv.z = o.scale.x > o.scale.y ? 1.0 - (borderWidth * scaleRatio) : 1.0 - borderWidth; + o.uv.w = o.scale.x > o.scale.y ? 1.0 - borderWidth : 1.0 - (borderWidth * scaleRatio); #endif #elif defined(_UV) o.uv = TRANSFORM_TEX(v.uv, _MainTex); @@ -774,7 +772,7 @@ Shader "Mixed Reality Toolkit/Standard" return o; } - fixed4 frag(v2f i, fixed facing : VFACE) : SV_Target + fixed4 frag(v2f i) : SV_Target { UNITY_SETUP_INSTANCE_ID(i); @@ -798,8 +796,8 @@ Shader "Mixed Reality Toolkit/Standard" fixed4 albedo = fixed4(1.0, 1.0, 1.0, 1.0); #else #if defined(_TRIPLANAR_MAPPING) - fixed4 albedo = tex2D(_MainTex, uvX) * triplanarBlend.x + - tex2D(_MainTex, uvY) * triplanarBlend.y + + fixed4 albedo = tex2D(_MainTex, uvX) * triplanarBlend.x + + tex2D(_MainTex, uvY) * triplanarBlend.y + tex2D(_MainTex, uvZ) * triplanarBlend.z; #else #if defined(_USE_SSAA) @@ -860,7 +858,7 @@ Shader "Mixed Reality Toolkit/Standard" #endif #if defined(_CLIPPING_BORDER) fixed3 primitiveBorderColor = lerp(_ClippingBorderColor, fixed3(0.0, 0.0, 0.0), primitiveDistance / _ClippingBorderWidth); - albedo.rgb += primitiveBorderColor * IF((primitiveDistance < _ClippingBorderWidth), 1.0, 0.0); + albedo.rgb += primitiveBorderColor * (primitiveDistance < _ClippingBorderWidth ? 1.0 : 0.0); #endif #endif @@ -955,10 +953,10 @@ Shader "Mixed Reality Toolkit/Standard" worldNormal.x = dot(i.tangentX, tangentNormal); worldNormal.y = dot(i.tangentY, tangentNormal); worldNormal.z = dot(i.tangentZ, tangentNormal); - worldNormal = normalize(worldNormal) * facing; + worldNormal = normalize(worldNormal); #endif #else - worldNormal = normalize(i.worldNormal) * facing; + worldNormal = normalize(i.worldNormal); #endif #endif @@ -1013,13 +1011,13 @@ Shader "Mixed Reality Toolkit/Standard" #if defined(_BORDER_LIGHT) fixed borderValue; #if defined(_ROUND_CORNERS) - fixed borderMargin = _RoundCornerMargin + _BorderWidth * 0.5; + fixed borderMargin = _RoundCornerMargin + _BorderWidth * 0.5; cornerCircleRadius = saturate(max(currentCornerRadius - borderMargin, 0.01)) * i.scale.z; cornerCircleDistance = halfScale - (borderMargin * i.scale.z) - cornerCircleRadius; - borderValue = 1.0 - RoundCornersSmooth(roundCornerPosition, cornerCircleDistance, cornerCircleRadius); + borderValue = 1.0 - RoundCornersSmooth(roundCornerPosition, cornerCircleDistance, cornerCircleRadius); #else borderValue = max(smoothstep(i.uv.z - _EdgeSmoothingValue, i.uv.z + _EdgeSmoothingValue, distanceToEdge.x), smoothstep(i.uv.w - _EdgeSmoothingValue, i.uv.w + _EdgeSmoothingValue, distanceToEdge.y)); @@ -1152,7 +1150,7 @@ Shader "Mixed Reality Toolkit/Standard" // Environment coloring. #if defined(_ENVIRONMENT_COLORING) fixed3 environmentColor = incident.x * incident.x * _EnvironmentColorX + - incident.y * incident.y * _EnvironmentColorY + + incident.y * incident.y * _EnvironmentColorY + incident.z * incident.z * _EnvironmentColorZ; output.rgb += environmentColor * max(0.0, dot(incident, worldNormal) + _EnvironmentColorThreshold) * _EnvironmentColorIntensity; @@ -1255,7 +1253,7 @@ Shader "Mixed Reality Toolkit/Standard" ENDCG } } - + Fallback "Hidden/InternalErrorShader" CustomEditor "Microsoft.MixedReality.Toolkit.Editor.MixedRealityStandardShaderGUI" } diff --git a/Assets/MRTK/Shaders/MixedRealityTextMeshPro.shader b/Assets/MRTK/Shaders/MixedRealityTextMeshPro.shader index 529f2c433..baedb1158 100644 --- a/Assets/MRTK/Shaders/MixedRealityTextMeshPro.shader +++ b/Assets/MRTK/Shaders/MixedRealityTextMeshPro.shader @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. +// TextMesh Pro copyright © 2021 Unity Technologies ApS +// Licensed under the Unity Companion License for Unity-dependent projects--see http://www.unity3d.com/legal/licenses/Unity_Companion_License. +// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions. // NOTE: MRTK Shaders are versioned via the MRTK.Shaders.sentinel file. // When making changes to any shader's source file, the value in the sentinel _must_ be incremented. diff --git a/Assets/MRTK/Shaders/MixedRealityTextMeshProSprite.shader b/Assets/MRTK/Shaders/MixedRealityTextMeshProSprite.shader new file mode 100644 index 000000000..42a66f81d --- /dev/null +++ b/Assets/MRTK/Shaders/MixedRealityTextMeshProSprite.shader @@ -0,0 +1,184 @@ +// TextMesh Pro copyright © 2021 Unity Technologies ApS +// Licensed under the Unity Companion License for Unity-dependent projects--see http://www.unity3d.com/legal/licenses/Unity_Companion_License. +// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions. + +// NOTE: MRTK Shaders are versioned via the MRTK.Shaders.sentinel file. +// When making changes to any shader's source file, the value in the sentinel _must_ be incremented. + +// Text Mesh Pro Sprite shader with MRTK Additions + +// MRTK Additions +// - Single Pass Instanced Stereo Rendering Support +// - Support for Clipping Primitives (Plane, Sphere, Box) +// - Added to MRTK namespace + +Shader "Mixed Reality Toolkit/TextMeshProSprite" { + +Properties { + _MainTex ("Sprite Texture", 2D) = "white" {} + _Color ("Tint", Color) = (1,1,1,1) + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _CullMode ("Cull Mode", Float) = 0 + _ColorMask ("Color Mask", Float) = 15 + _ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767) + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 +} + +SubShader { + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + "PreviewType"="Plane" + "CanUseSpriteAtlas"="True" + } + + Stencil { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull [_CullMode] + Lighting Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Blend SrcAlpha OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + + #pragma multi_compile __ UNITY_UI_CLIP_RECT + #pragma multi_compile __ UNITY_UI_ALPHACLIP + + #pragma multi_compile __ _CLIPPING_PLANE _CLIPPING_SPHERE _CLIPPING_BOX + + #include "UnityCG.cginc" + #include "UnityUI.cginc" + #include "MixedRealityShaderUtils.cginc" + +#if defined(_CLIPPING_PLANE) || defined(_CLIPPING_SPHERE) || defined(_CLIPPING_BOX) + #define _CLIPPING_PRIMITIVE +#else + #undef _CLIPPING_PRIMITIVE +#endif + +#if defined(_CLIPPING_PLANE) + fixed _ClipPlaneSide; + float4 _ClipPlane; +#endif + +#if defined(_CLIPPING_SPHERE) + fixed _ClipSphereSide; + float4x4 _ClipSphereInverseTransform; +#endif + +#if defined(_CLIPPING_BOX) + fixed _ClipBoxSide; + float4x4 _ClipBoxInverseTransform; +#endif + + uniform float _VertexOffsetX; + uniform float _VertexOffsetY; + + struct appdata_t { + + float4 vertex : POSITION; + float4 color : COLOR; + float2 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct v2f { + + float4 vertex : SV_POSITION; + fixed4 color : COLOR; + half2 texcoord : TEXCOORD0; + float3 worldPosition : TEXCOORD1; + + UNITY_VERTEX_INPUT_INSTANCE_ID + UNITY_VERTEX_OUTPUT_STEREO + }; + + fixed4 _Color; + fixed4 _TextureSampleAdd; + float4 _ClipRect; + + v2f vert(appdata_t IN) + { + v2f OUT; + + UNITY_SETUP_INSTANCE_ID(IN); + UNITY_TRANSFER_INSTANCE_ID(IN, OUT); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT); + + OUT.worldPosition = IN.vertex; + OUT.vertex = UnityObjectToClipPos(OUT.worldPosition); + + OUT.texcoord = IN.texcoord; + + float4 vertin = IN.vertex; + vertin.x += _VertexOffsetX; + vertin.y += _VertexOffsetY; + float4 vPosition = UnityObjectToClipPos(vertin); + +#ifdef UNITY_HALF_TEXEL_OFFSET + OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1); +#endif + + OUT.color = IN.color * _Color; +#if defined(_CLIPPING_PRIMITIVE) + OUT.worldPosition = mul(unity_ObjectToWorld, vertin).xyz; +#endif + + return OUT; + } + + sampler2D _MainTex; + + fixed4 frag(v2f IN) : SV_Target + { + half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color; + +#if UNITY_UI_CLIP_RECT + color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect); +#endif + + // Primitive clipping. +#if defined(_CLIPPING_PRIMITIVE) + float primitiveDistance = 1.0; +#if defined(_CLIPPING_PLANE) + primitiveDistance = min(primitiveDistance, PointVsPlane(IN.worldPosition, _ClipPlane) * _ClipPlaneSide); +#endif +#if defined(_CLIPPING_SPHERE) + primitiveDistance = min(primitiveDistance, PointVsSphere(IN.worldPosition, _ClipSphereInverseTransform) * _ClipSphereSide); +#endif +#if defined(_CLIPPING_BOX) + primitiveDistance = min(primitiveDistance, PointVsBox(IN.worldPosition, _ClipBoxInverseTransform) * _ClipBoxSide); +#endif + color *= step(0.0, primitiveDistance); +#endif + +#ifdef UNITY_UI_ALPHACLIP + clip (color.a - 0.001); +#endif + + return color; + } + ENDCG + } + } +} \ No newline at end of file diff --git a/Assets/MirageXR/Common/Resources/Materials/MixedRealityStandard.shader.meta b/Assets/MRTK/Shaders/MixedRealityTextMeshProSprite.shader.meta similarity index 80% rename from Assets/MirageXR/Common/Resources/Materials/MixedRealityStandard.shader.meta rename to Assets/MRTK/Shaders/MixedRealityTextMeshProSprite.shader.meta index 050f23deb..b76d3b667 100644 --- a/Assets/MirageXR/Common/Resources/Materials/MixedRealityStandard.shader.meta +++ b/Assets/MRTK/Shaders/MixedRealityTextMeshProSprite.shader.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4bbfca341cb5a614a90737c004d0c6c4 +guid: f11fd341db238f342a8b36d23162d67a ShaderImporter: externalObjects: {} defaultTextures: [] diff --git a/Assets/MirageXR/Common/Resources/Materials/MixedRealityStandard.shader b/Assets/MirageXR/Common/Resources/Materials/MixedRealityStandard.shader deleted file mode 100644 index b01c4f0b6..000000000 --- a/Assets/MirageXR/Common/Resources/Materials/MixedRealityStandard.shader +++ /dev/null @@ -1,1219 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -Shader "Mixed Reality Toolkit/Standard" -{ - Properties - { - // Main maps. - _Color("Color", Color) = (1.0, 1.0, 1.0, 1.0) - _MainTex("Albedo", 2D) = "white" {} - [Enum(AlbedoAlphaMode)] _AlbedoAlphaMode("Albedo Alpha Mode", Float) = 0 // "Transparency" - [Toggle] _AlbedoAssignedAtRuntime("Albedo Assigned at Runtime", Float) = 0.0 - _Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5 - _Metallic("Metallic", Range(0.0, 1.0)) = 0.0 - _Smoothness("Smoothness", Range(0.0, 1.0)) = 0.5 - [Toggle(_CHANNEL_MAP)] _EnableChannelMap("Enable Channel Map", Float) = 0.0 - [NoScaleOffset] _ChannelMap("Channel Map", 2D) = "white" {} - [Toggle(_NORMAL_MAP)] _EnableNormalMap("Enable Normal Map", Float) = 0.0 - [NoScaleOffset] _NormalMap("Normal Map", 2D) = "bump" {} - _NormalMapScale("Scale", Float) = 1.0 - [Toggle(_EMISSION)] _EnableEmission("Enable Emission", Float) = 0.0 - [HDR]_EmissiveColor("Emissive Color", Color) = (0.0, 0.0, 0.0, 1.0) - [Toggle(_TRIPLANAR_MAPPING)] _EnableTriplanarMapping("Triplanar Mapping", Float) = 0.0 - [Toggle(_LOCAL_SPACE_TRIPLANAR_MAPPING)] _EnableLocalSpaceTriplanarMapping("Local Space", Float) = 0.0 - _TriplanarMappingBlendSharpness("Blend Sharpness", Range(1.0, 16.0)) = 4.0 - - // Rendering options. - [Toggle(_DIRECTIONAL_LIGHT)] _DirectionalLight("Directional Light", Float) = 1.0 - [Toggle(_SPECULAR_HIGHLIGHTS)] _SpecularHighlights("Specular Highlights", Float) = 1.0 - [Toggle(_SPHERICAL_HARMONICS)] _SphericalHarmonics("Spherical Harmonics", Float) = 0.0 - [Toggle(_REFLECTIONS)] _Reflections("Reflections", Float) = 0.0 - [Toggle(_REFRACTION)] _Refraction("Refraction", Float) = 0.0 - _RefractiveIndex("Refractive Index", Range(0.0, 3.0)) = 0.0 - [Toggle(_RIM_LIGHT)] _RimLight("Rim Light", Float) = 0.0 - _RimColor("Rim Color", Color) = (0.5, 0.5, 0.5, 1.0) - _RimPower("Rim Power", Range(0.0, 8.0)) = 0.25 - [Toggle(_VERTEX_COLORS)] _VertexColors("Vertex Colors", Float) = 0.0 - [Toggle(_VERTEX_EXTRUSION)] _VertexExtrusion("Vertex Extrusion", Float) = 0.0 - _VertexExtrusionValue("Vertex Extrusion Value", Float) = 0.0 - [Toggle(_VERTEX_EXTRUSION_SMOOTH_NORMALS)] _VertexExtrusionSmoothNormals("Vertex Extrusion Smooth Normals", Float) = 0.0 - _BlendedClippingWidth("Blended Clipping With", Range(0.0, 10.0)) = 1.0 - [Toggle(_CLIPPING_BORDER)] _ClippingBorder("Clipping Border", Float) = 0.0 - _ClippingBorderWidth("Clipping Border Width", Range(0.0, 1.0)) = 0.025 - _ClippingBorderColor("Clipping Border Color", Color) = (1.0, 0.2, 0.0, 1.0) - [Toggle(_NEAR_PLANE_FADE)] _NearPlaneFade("Near Plane Fade", Float) = 0.0 - [Toggle(_NEAR_LIGHT_FADE)] _NearLightFade("Near Light Fade", Float) = 0.0 - _FadeBeginDistance("Fade Begin Distance", Range(0.0, 10.0)) = 0.85 - _FadeCompleteDistance("Fade Complete Distance", Range(0.0, 10.0)) = 0.5 - _FadeMinValue("Fade Min Value", Range(0.0, 1.0)) = 0.0 - - // Fluent options. - [Toggle(_HOVER_LIGHT)] _HoverLight("Hover Light", Float) = 1.0 - [Toggle(_HOVER_COLOR_OVERRIDE)] _EnableHoverColorOverride("Hover Color Override", Float) = 0.0 - _HoverColorOverride("Hover Color Override", Color) = (1.0, 1.0, 1.0, 1.0) - [Toggle(_PROXIMITY_LIGHT)] _ProximityLight("Proximity Light", Float) = 0.0 - [Toggle(_PROXIMITY_LIGHT_COLOR_OVERRIDE)] _EnableProximityLightColorOverride("Proximity Light Color Override", Float) = 0.0 - [HDR]_ProximityLightCenterColorOverride("Proximity Light Center Color Override", Color) = (1.0, 0.0, 0.0, 0.0) - [HDR]_ProximityLightMiddleColorOverride("Proximity Light Middle Color Override", Color) = (0.0, 1.0, 0.0, 0.5) - [HDR]_ProximityLightOuterColorOverride("Proximity Light Outer Color Override", Color) = (0.0, 0.0, 1.0, 1.0) - [Toggle(_PROXIMITY_LIGHT_SUBTRACTIVE)] _ProximityLightSubtractive("Proximity Light Subtractive", Float) = 0.0 - [Toggle(_PROXIMITY_LIGHT_TWO_SIDED)] _ProximityLightTwoSided("Proximity Light Two Sided", Float) = 0.0 - _FluentLightIntensity("Fluent Light Intensity", Range(0.0, 1.0)) = 1.0 - [Toggle(_ROUND_CORNERS)] _RoundCorners("Round Corners", Float) = 0.0 - _RoundCornerRadius("Round Corner Radius", Range(0.0, 0.5)) = 0.25 - _RoundCornerMargin("Round Corner Margin", Range(0.0, 0.5)) = 0.01 - [Toggle(_INDEPENDENT_CORNERS)] _IndependentCorners("Independent Corners", Float) = 0.0 - _RoundCornersRadius("Round Corners Radius", Vector) = (0.5 ,0.5, 0.5, 0.5) - [Toggle(_BORDER_LIGHT)] _BorderLight("Border Light", Float) = 0.0 - [Toggle(_BORDER_LIGHT_USES_HOVER_COLOR)] _BorderLightUsesHoverColor("Border Light Uses Hover Color", Float) = 0.0 - [Toggle(_BORDER_LIGHT_REPLACES_ALBEDO)] _BorderLightReplacesAlbedo("Border Light Replaces Albedo", Float) = 0.0 - [Toggle(_BORDER_LIGHT_OPAQUE)] _BorderLightOpaque("Border Light Opaque", Float) = 0.0 - _BorderWidth("Border Width", Range(0.0, 1.0)) = 0.1 - _BorderMinValue("Border Min Value", Range(0.0, 1.0)) = 0.1 - _EdgeSmoothingValue("Edge Smoothing Value", Range(0.0, 0.2)) = 0.002 - _BorderLightOpaqueAlpha("Border Light Opaque Alpha", Range(0.0, 1.0)) = 1.0 - [Toggle(_INNER_GLOW)] _InnerGlow("Inner Glow", Float) = 0.0 - _InnerGlowColor("Inner Glow Color (RGB) and Intensity (A)", Color) = (1.0, 1.0, 1.0, 0.75) - _InnerGlowPower("Inner Glow Power", Range(2.0, 32.0)) = 4.0 - [Toggle(_IRIDESCENCE)] _Iridescence("Iridescence", Float) = 0.0 - [NoScaleOffset] _IridescentSpectrumMap("Iridescent Spectrum Map", 2D) = "white" {} - _IridescenceIntensity("Iridescence Intensity", Range(0.0, 1.0)) = 0.5 - _IridescenceThreshold("Iridescence Threshold", Range(0.0, 1.0)) = 0.05 - _IridescenceAngle("Iridescence Angle", Range(-0.78, 0.78)) = -0.78 - [Toggle(_ENVIRONMENT_COLORING)] _EnvironmentColoring("Environment Coloring", Float) = 0.0 - _EnvironmentColorThreshold("Environment Color Threshold", Range(0.0, 3.0)) = 1.5 - _EnvironmentColorIntensity("Environment Color Intensity", Range(0.0, 1.0)) = 0.5 - _EnvironmentColorX("Environment Color X (RGB)", Color) = (1.0, 0.0, 0.0, 1.0) - _EnvironmentColorY("Environment Color Y (RGB)", Color) = (0.0, 1.0, 0.0, 1.0) - _EnvironmentColorZ("Environment Color Z (RGB)", Color) = (0.0, 0.0, 1.0, 1.0) - - // Advanced options. - [Enum(RenderingMode)] _Mode("Rendering Mode", Float) = 0 // "Opaque" - [Enum(CustomRenderingMode)] _CustomMode("Mode", Float) = 0 // "Opaque" - [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend("Source Blend", Float) = 1 // "One" - [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("Destination Blend", Float) = 0 // "Zero" - [Enum(UnityEngine.Rendering.BlendOp)] _BlendOp("Blend Operation", Float) = 0 // "Add" - [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("Depth Test", Float) = 4 // "LessEqual" - [Enum(DepthWrite)] _ZWrite("Depth Write", Float) = 1 // "On" - _ZOffsetFactor("Depth Offset Factor", Float) = 0 // "Zero" - _ZOffsetUnits("Depth Offset Units", Float) = 0 // "Zero" - [Enum(UnityEngine.Rendering.ColorWriteMask)] _ColorWriteMask("Color Write Mask", Float) = 15 // "All" - [Enum(UnityEngine.Rendering.CullMode)] _CullMode("Cull Mode", Float) = 2 // "Back" - _RenderQueueOverride("Render Queue Override", Range(-1.0, 5000)) = -1 - [Toggle(_INSTANCED_COLOR)] _InstancedColor("Instanced Color", Float) = 0.0 - [Toggle(_IGNORE_Z_SCALE)] _IgnoreZScale("Ignore Z Scale", Float) = 0.0 - [Toggle(_STENCIL)] _Stencil("Enable Stencil Testing", Float) = 0.0 - _StencilReference("Stencil Reference", Range(0, 255)) = 0 - [Enum(UnityEngine.Rendering.CompareFunction)]_StencilComparison("Stencil Comparison", Int) = 0 - [Enum(UnityEngine.Rendering.StencilOp)]_StencilOperation("Stencil Operation", Int) = 0 - } - - SubShader - { - Pass - { - Name "Main" - Tags{ "RenderType" = "Opaque" "LightMode" = "ForwardBase" } - LOD 100 - Blend[_SrcBlend][_DstBlend] - BlendOp[_BlendOp] - ZTest[_ZTest] - ZWrite[_ZWrite] - Cull[_CullMode] - Offset[_ZOffsetFactor],[_ZOffsetUnits] - ColorMask[_ColorWriteMask] - - Stencil - { - Ref[_StencilReference] - Comp[_StencilComparison] - Pass[_StencilOperation] - } - - CGPROGRAM - - #pragma vertex vert - #pragma fragment frag - - #pragma multi_compile_instancing - #pragma multi_compile _ LIGHTMAP_ON - #pragma multi_compile _ _HOVER_LIGHT_MEDIUM _HOVER_LIGHT_HIGH - #pragma multi_compile _ _CLIPPING_PLANE _CLIPPING_SPHERE _CLIPPING_BOX - - #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON - #pragma shader_feature _DISABLE_ALBEDO_MAP - #pragma shader_feature _ _METALLIC_TEXTURE_ALBEDO_CHANNEL_A _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A - #pragma shader_feature _CHANNEL_MAP - #pragma shader_feature _NORMAL_MAP - #pragma shader_feature _EMISSION - #pragma shader_feature _TRIPLANAR_MAPPING - #pragma shader_feature _LOCAL_SPACE_TRIPLANAR_MAPPING - #pragma shader_feature _DIRECTIONAL_LIGHT - #pragma shader_feature _SPECULAR_HIGHLIGHTS - #pragma shader_feature _SPHERICAL_HARMONICS - #pragma shader_feature _REFLECTIONS - #pragma shader_feature _REFRACTION - #pragma shader_feature _RIM_LIGHT - #pragma shader_feature _VERTEX_COLORS - #pragma shader_feature _VERTEX_EXTRUSION - #pragma shader_feature _VERTEX_EXTRUSION_SMOOTH_NORMALS - #pragma shader_feature _CLIPPING_BORDER - #pragma shader_feature _NEAR_PLANE_FADE - #pragma shader_feature _NEAR_LIGHT_FADE - #pragma shader_feature _HOVER_LIGHT - #pragma shader_feature _HOVER_COLOR_OVERRIDE - #pragma shader_feature _PROXIMITY_LIGHT - #pragma shader_feature _PROXIMITY_LIGHT_COLOR_OVERRIDE - #pragma shader_feature _PROXIMITY_LIGHT_SUBTRACTIVE - #pragma shader_feature _PROXIMITY_LIGHT_TWO_SIDED - #pragma shader_feature _ROUND_CORNERS - #pragma shader_feature _INDEPENDENT_CORNERS - #pragma shader_feature _BORDER_LIGHT - #pragma shader_feature _BORDER_LIGHT_USES_HOVER_COLOR - #pragma shader_feature _BORDER_LIGHT_REPLACES_ALBEDO - #pragma shader_feature _BORDER_LIGHT_OPAQUE - #pragma shader_feature _INNER_GLOW - #pragma shader_feature _IRIDESCENCE - #pragma shader_feature _ENVIRONMENT_COLORING - #pragma shader_feature _INSTANCED_COLOR - #pragma shader_feature _IGNORE_Z_SCALE - - #define IF(a, b, c) lerp(b, c, step((fixed) (a), 0.0)); - - #include "UnityCG.cginc" - #include "UnityStandardConfig.cginc" - #include "UnityStandardUtils.cginc" - #include "Assets/MRTK/Shaders/MixedRealityShaderUtils.cginc" - - // This define will get commented in by the UpgradeShaderForLightweightRenderPipeline method. - //#define _LIGHTWEIGHT_RENDER_PIPELINE - -#if defined(_TRIPLANAR_MAPPING) || defined(_DIRECTIONAL_LIGHT) || defined(_SPHERICAL_HARMONICS) || defined(_REFLECTIONS) || defined(_RIM_LIGHT) || defined(_PROXIMITY_LIGHT) || defined(_ENVIRONMENT_COLORING) - #define _NORMAL -#else - #undef _NORMAL -#endif - -#if defined(_CLIPPING_PLANE) || defined(_CLIPPING_SPHERE) || defined(_CLIPPING_BOX) - #define _CLIPPING_PRIMITIVE -#else - #undef _CLIPPING_PRIMITIVE -#endif - -#if defined(_NORMAL) || defined(_CLIPPING_PRIMITIVE) || defined(_NEAR_PLANE_FADE) || defined(_HOVER_LIGHT) || defined(_PROXIMITY_LIGHT) - #define _WORLD_POSITION -#else - #undef _WORLD_POSITION -#endif - -#if defined(_ALPHATEST_ON) || defined(_CLIPPING_PRIMITIVE) || defined(_ROUND_CORNERS) - #define _ALPHA_CLIP -#else - #undef _ALPHA_CLIP -#endif - -#if defined(_ALPHABLEND_ON) - #define _TRANSPARENT - #undef _ALPHA_CLIP -#else - #undef _TRANSPARENT -#endif - -#if defined(_VERTEX_EXTRUSION) || defined(_ROUND_CORNERS) || defined(_BORDER_LIGHT) - #define _SCALE -#else - #undef _SCALE -#endif - -#if defined(_DIRECTIONAL_LIGHT) || defined(_RIM_LIGHT) - #define _FRESNEL -#else - #undef _FRESNEL -#endif - -#if defined(_ROUND_CORNERS) || defined(_BORDER_LIGHT) || defined(_INNER_GLOW) - #define _DISTANCE_TO_EDGE -#else - #undef _DISTANCE_TO_EDGE -#endif - -#if !defined(_DISABLE_ALBEDO_MAP) || defined(_TRIPLANAR_MAPPING) || defined(_CHANNEL_MAP) || defined(_NORMAL_MAP) || defined(_DISTANCE_TO_EDGE) || defined(_IRIDESCENCE) - #define _UV -#else - #undef _UV -#endif - - struct appdata_t - { - float4 vertex : POSITION; - // The default UV channel used for texturing. - float2 uv : TEXCOORD0; -#if defined(LIGHTMAP_ON) - // Reserved for Unity's light map UVs. - float2 uv1 : TEXCOORD1; -#endif - // Used for smooth normal data (or UGUI scaling data). - float4 uv2 : TEXCOORD2; - // Used for UGUI scaling data. - float2 uv3 : TEXCOORD3; -#if defined(_VERTEX_COLORS) - fixed4 color : COLOR0; -#endif - fixed3 normal : NORMAL; -#if defined(_NORMAL_MAP) - fixed4 tangent : TANGENT; -#endif - UNITY_VERTEX_INPUT_INSTANCE_ID - }; - - struct v2f - { - float4 position : SV_POSITION; -#if defined(_BORDER_LIGHT) - float4 uv : TEXCOORD0; -#elif defined(_UV) - float2 uv : TEXCOORD0; -#endif -#if defined(LIGHTMAP_ON) - float2 lightMapUV : TEXCOORD1; -#endif -#if defined(_VERTEX_COLORS) - fixed4 color : COLOR0; -#endif -#if defined(_SPHERICAL_HARMONICS) - fixed3 ambient : COLOR1; -#endif -#if defined(_IRIDESCENCE) - fixed3 iridescentColor : COLOR2; -#endif -#if defined(_WORLD_POSITION) -#if defined(_NEAR_PLANE_FADE) - float4 worldPosition : TEXCOORD2; -#else - float3 worldPosition : TEXCOORD2; -#endif -#endif -#if defined(_SCALE) - float3 scale : TEXCOORD3; -#endif -#if defined(_NORMAL) -#if defined(_TRIPLANAR_MAPPING) - fixed3 worldNormal : COLOR3; - fixed3 triplanarNormal : COLOR4; - float3 triplanarPosition : TEXCOORD6; -#elif defined(_NORMAL_MAP) - fixed3 tangentX : COLOR3; - fixed3 tangentY : COLOR4; - fixed3 tangentZ : COLOR5; -#else - fixed3 worldNormal : COLOR3; -#endif -#endif - UNITY_VERTEX_OUTPUT_STEREO -#if defined(_INSTANCED_COLOR) - UNITY_VERTEX_INPUT_INSTANCE_ID -#endif - }; - -#if defined(_INSTANCED_COLOR) - UNITY_INSTANCING_BUFFER_START(Props) - UNITY_DEFINE_INSTANCED_PROP(float4, _Color) - UNITY_INSTANCING_BUFFER_END(Props) -#else - fixed4 _Color; -#endif - sampler2D _MainTex; - fixed4 _MainTex_ST; - -#if defined(_ALPHA_CLIP) - fixed _Cutoff; -#endif - - fixed _Metallic; - fixed _Smoothness; - -#if defined(_CHANNEL_MAP) - sampler2D _ChannelMap; -#endif - -#if defined(_NORMAL_MAP) - sampler2D _NormalMap; - float _NormalMapScale; -#endif - -#if defined(_EMISSION) - fixed4 _EmissiveColor; -#endif - -#if defined(_TRIPLANAR_MAPPING) - float _TriplanarMappingBlendSharpness; -#endif - -#if defined(_DIRECTIONAL_LIGHT) -#if defined(_LIGHTWEIGHT_RENDER_PIPELINE) - CBUFFER_START(_LightBuffer) - float4 _MainLightPosition; - half4 _MainLightColor; - CBUFFER_END -#else - fixed4 _LightColor0; -#endif -#endif - -#if defined(_REFRACTION) - fixed _RefractiveIndex; -#endif - -#if defined(_RIM_LIGHT) - fixed3 _RimColor; - fixed _RimPower; -#endif - -#if defined(_VERTEX_EXTRUSION) - float _VertexExtrusionValue; -#endif - -#if defined(_CLIPPING_PLANE) - fixed _ClipPlaneSide; - float4 _ClipPlane; -#endif - -#if defined(_CLIPPING_SPHERE) - fixed _ClipSphereSide; - float4 _ClipSphere; -#endif - -#if defined(_CLIPPING_BOX) - fixed _ClipBoxSide; - float4 _ClipBoxSize; - float4x4 _ClipBoxInverseTransform; -#endif - -#if defined(_CLIPPING_PRIMITIVE) - float _BlendedClippingWidth; -#endif - -#if defined(_CLIPPING_BORDER) - fixed _ClippingBorderWidth; - fixed3 _ClippingBorderColor; -#endif - -#if defined(_NEAR_PLANE_FADE) - float _FadeBeginDistance; - float _FadeCompleteDistance; - fixed _FadeMinValue; -#endif - -#if defined(_HOVER_LIGHT) || defined(_NEAR_LIGHT_FADE) -#if defined(_HOVER_LIGHT_HIGH) -#define HOVER_LIGHT_COUNT 10 -#elif defined(_HOVER_LIGHT_MEDIUM) -#define HOVER_LIGHT_COUNT 4 -#else -#define HOVER_LIGHT_COUNT 2 -#endif -#define HOVER_LIGHT_DATA_SIZE 2 - float4 _HoverLightData[HOVER_LIGHT_COUNT * HOVER_LIGHT_DATA_SIZE]; -#if defined(_HOVER_COLOR_OVERRIDE) - fixed3 _HoverColorOverride; -#endif -#endif - -#if defined(_PROXIMITY_LIGHT) || defined(_NEAR_LIGHT_FADE) -#define PROXIMITY_LIGHT_COUNT 2 -#define PROXIMITY_LIGHT_DATA_SIZE 6 - float4 _ProximityLightData[PROXIMITY_LIGHT_COUNT * PROXIMITY_LIGHT_DATA_SIZE]; -#if defined(_PROXIMITY_LIGHT_COLOR_OVERRIDE) - float4 _ProximityLightCenterColorOverride; - float4 _ProximityLightMiddleColorOverride; - float4 _ProximityLightOuterColorOverride; -#endif -#endif - -#if defined(_HOVER_LIGHT) || defined(_PROXIMITY_LIGHT) || defined(_BORDER_LIGHT) - fixed _FluentLightIntensity; -#endif - -#if defined(_ROUND_CORNERS) -#if defined(_INDEPENDENT_CORNERS) - float4 _RoundCornersRadius; -#else - fixed _RoundCornerRadius; -#endif - fixed _RoundCornerMargin; -#endif - -#if defined(_BORDER_LIGHT) - fixed _BorderWidth; - fixed _BorderMinValue; -#endif - -#if defined(_BORDER_LIGHT_OPAQUE) - fixed _BorderLightOpaqueAlpha; -#endif - -#if defined(_ROUND_CORNERS) || defined(_BORDER_LIGHT) - fixed _EdgeSmoothingValue; -#endif - -#if defined(_INNER_GLOW) - fixed4 _InnerGlowColor; - fixed _InnerGlowPower; -#endif - -#if defined(_IRIDESCENCE) - sampler2D _IridescentSpectrumMap; - fixed _IridescenceIntensity; - fixed _IridescenceThreshold; - fixed _IridescenceAngle; -#endif - -#if defined(_ENVIRONMENT_COLORING) - fixed _EnvironmentColorThreshold; - fixed _EnvironmentColorIntensity; - fixed3 _EnvironmentColorX; - fixed3 _EnvironmentColorY; - fixed3 _EnvironmentColorZ; -#endif - -#if defined(_DIRECTIONAL_LIGHT) - static const fixed _MinMetallicLightContribution = 0.7; - static const fixed _IblContribution = 0.1; -#endif - -#if defined(_SPECULAR_HIGHLIGHTS) - static const float _Shininess = 800.0; -#endif - -#if defined(_FRESNEL) - static const float _FresnelPower = 8.0; -#endif - -#if defined(_NEAR_LIGHT_FADE) - static const float _MaxNearLightDistance = 10.0; - - inline float NearLightDistance(float4 light, float3 worldPosition) - { - return distance(worldPosition, light.xyz) + ((1.0 - light.w) * _MaxNearLightDistance); - } -#endif - -#if defined(_HOVER_LIGHT) - inline float HoverLight(float4 hoverLight, float inverseRadius, float3 worldPosition) - { - return (1.0 - saturate(length(hoverLight.xyz - worldPosition) * inverseRadius)) * hoverLight.w; - } -#endif - -#if defined(_PROXIMITY_LIGHT) - inline float ProximityLight(float4 proximityLight, float4 proximityLightParams, float4 proximityLightPulseParams, float3 worldPosition, float3 worldNormal, out fixed colorValue) - { - float proximityLightDistance = dot(proximityLight.xyz - worldPosition, worldNormal); -#if defined(_PROXIMITY_LIGHT_TWO_SIDED) - worldNormal = IF(proximityLightDistance < 0.0, -worldNormal, worldNormal); - proximityLightDistance = abs(proximityLightDistance); -#endif - float normalizedProximityLightDistance = saturate(proximityLightDistance * proximityLightParams.y); - float3 projectedProximityLight = proximityLight.xyz - (worldNormal * abs(proximityLightDistance)); - float projectedProximityLightDistance = length(projectedProximityLight - worldPosition); - float attenuation = (1.0 - normalizedProximityLightDistance) * proximityLight.w; - colorValue = saturate(projectedProximityLightDistance * proximityLightParams.z); - float pulse = step(proximityLightPulseParams.x, projectedProximityLightDistance) * proximityLightPulseParams.y; - - return smoothstep(1.0, 0.0, projectedProximityLightDistance / (proximityLightParams.x * max(pow(normalizedProximityLightDistance, 0.25), proximityLightParams.w))) * pulse * attenuation; - } - - inline fixed3 MixProximityLightColor(fixed4 centerColor, fixed4 middleColor, fixed4 outerColor, fixed t) - { - fixed3 color = lerp(centerColor.rgb, middleColor.rgb, smoothstep(centerColor.a, middleColor.a, t)); - return lerp(color, outerColor, smoothstep(middleColor.a, outerColor.a, t)); - } -#endif - -#if defined(_ROUND_CORNERS) - inline float PointVsRoundedBox(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) - { - return length(max(abs(position) - cornerCircleDistance, 0.0)) - cornerCircleRadius; - } - - inline fixed RoundCornersSmooth(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) - { - return smoothstep(1.0, 0.0, PointVsRoundedBox(position, cornerCircleDistance, cornerCircleRadius) / _EdgeSmoothingValue); - } - - inline fixed RoundCorners(float2 position, float2 cornerCircleDistance, float cornerCircleRadius) - { -#if defined(_TRANSPARENT) - return RoundCornersSmooth(position, cornerCircleDistance, cornerCircleRadius); -#else - return (PointVsRoundedBox(position, cornerCircleDistance, cornerCircleRadius) < 0.0); -#endif - } -#endif - -#if defined(_IRIDESCENCE) - fixed3 Iridescence(float tangentDotIncident, sampler2D spectrumMap, float threshold, float2 uv, float angle, float intensity) - { - float k = tangentDotIncident * 0.5 + 0.5; - float4 left = tex2D(spectrumMap, float2(lerp(0.0, 1.0 - threshold, k), 0.5), float2(0.0, 0.0), float2(0.0, 0.0)); - float4 right = tex2D(spectrumMap, float2(lerp(threshold, 1.0, k), 0.5), float2(0.0, 0.0), float2(0.0, 0.0)); - - float2 XY = uv - float2(0.5, 0.5); - float s = (cos(angle) * XY.x - sin(angle) * XY.y) / cos(angle); - return (left.rgb + s * (right.rgb - left.rgb)) * intensity; - } -#endif - - v2f vert(appdata_t v) - { - v2f o; - UNITY_SETUP_INSTANCE_ID(v); - UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); -#if defined(_INSTANCED_COLOR) - UNITY_TRANSFER_INSTANCE_ID(v, o); -#endif - float4 vertexPosition = v.vertex; - -#if defined(_WORLD_POSITION) || defined(_VERTEX_EXTRUSION) - float3 worldVertexPosition = mul(unity_ObjectToWorld, vertexPosition).xyz; -#endif - -#if defined(_SCALE) - o.scale.x = length(mul(unity_ObjectToWorld, float4(1.0, 0.0, 0.0, 0.0))); - o.scale.y = length(mul(unity_ObjectToWorld, float4(0.0, 1.0, 0.0, 0.0))); -#if defined(_IGNORE_Z_SCALE) - o.scale.z = o.scale.x; -#else - o.scale.z = length(mul(unity_ObjectToWorld, float4(0.0, 0.0, 1.0, 0.0))); -#endif -#if !defined(_VERTEX_EXTRUSION_SMOOTH_NORMALS) - // uv3.y will contain a negative value when rendered by a UGUI and ScaleMeshEffect. - if (v.uv3.y < 0.0) - { - o.scale.x *= v.uv2.x; - o.scale.y *= v.uv2.y; - o.scale.z *= v.uv3.x; - } -#endif -#endif - - fixed3 localNormal = v.normal; - -#if defined(_NORMAL) || defined(_VERTEX_EXTRUSION) - fixed3 worldNormal = UnityObjectToWorldNormal(localNormal); -#endif - -#if defined(_VERTEX_EXTRUSION) -#if defined(_VERTEX_EXTRUSION_SMOOTH_NORMALS) - worldVertexPosition += UnityObjectToWorldNormal(v.uv2 * o.scale) * _VertexExtrusionValue; -#else - worldVertexPosition += worldNormal * _VertexExtrusionValue; -#endif - vertexPosition = mul(unity_WorldToObject, float4(worldVertexPosition, 1.0)); -#endif - - o.position = UnityObjectToClipPos(vertexPosition); - -#if defined(_WORLD_POSITION) - o.worldPosition.xyz = worldVertexPosition; -#endif - -#if defined(_NEAR_PLANE_FADE) - float rangeInverse = 1.0 / (_FadeBeginDistance - _FadeCompleteDistance); -#if defined(_NEAR_LIGHT_FADE) - float fadeDistance = _MaxNearLightDistance; - - [unroll] - for (int hoverLightIndex = 0; hoverLightIndex < HOVER_LIGHT_COUNT; ++hoverLightIndex) - { - int dataIndex = hoverLightIndex * HOVER_LIGHT_DATA_SIZE; - fadeDistance = min(fadeDistance, NearLightDistance(_HoverLightData[dataIndex], o.worldPosition)); - } - - [unroll] - for (int proximityLightIndex = 0; proximityLightIndex < PROXIMITY_LIGHT_COUNT; ++proximityLightIndex) - { - int dataIndex = proximityLightIndex * PROXIMITY_LIGHT_DATA_SIZE; - fadeDistance = min(fadeDistance, NearLightDistance(_ProximityLightData[dataIndex], o.worldPosition)); - } -#else - float fadeDistance = -UnityObjectToViewPos(vertexPosition).z; -#endif - o.worldPosition.w = max(saturate(mad(fadeDistance, rangeInverse, -_FadeCompleteDistance * rangeInverse)), _FadeMinValue); -#endif - -#if defined(_BORDER_LIGHT) || defined(_ROUND_CORNERS) - o.uv.xy = TRANSFORM_TEX(v.uv, _MainTex); - - float minScale = min(min(o.scale.x, o.scale.y), o.scale.z); - -#if defined(_BORDER_LIGHT) - float maxScale = max(max(o.scale.x, o.scale.y), o.scale.z); - float minOverMiddleScale = minScale / (o.scale.x + o.scale.y + o.scale.z - minScale - maxScale); - - float areaYZ = o.scale.y * o.scale.z; - float areaXZ = o.scale.z * o.scale.x; - float areaXY = o.scale.x * o.scale.y; - - float borderWidth = _BorderWidth; -#endif - - if (abs(localNormal.x) == 1.0) // Y,Z plane. - { - o.scale.x = o.scale.z; - o.scale.y = o.scale.y; - -#if defined(_BORDER_LIGHT) - if (areaYZ > areaXZ && areaYZ > areaXY) - { - borderWidth *= minOverMiddleScale; - } -#endif - } - else if (abs(localNormal.y) == 1.0) // X,Z plane. - { - o.scale.x = o.scale.x; - o.scale.y = o.scale.z; - -#if defined(_BORDER_LIGHT) - if (areaXZ > areaXY && areaXZ > areaYZ) - { - borderWidth *= minOverMiddleScale; - } -#endif - } - else // X,Y plane. - { - o.scale.x = o.scale.x; - o.scale.y = o.scale.y; - -#if defined(_BORDER_LIGHT) - if (areaXY > areaYZ && areaXY > areaXZ) - { - borderWidth *= minOverMiddleScale; - } -#endif - } - - o.scale.z = minScale; - -#if defined(_BORDER_LIGHT) - float scaleRatio = min(o.scale.x, o.scale.y) / max(o.scale.x, o.scale.y); - o.uv.z = IF(o.scale.x > o.scale.y, 1.0 - (borderWidth * scaleRatio), 1.0 - borderWidth); - o.uv.w = IF(o.scale.x > o.scale.y, 1.0 - borderWidth, 1.0 - (borderWidth * scaleRatio)); -#endif -#elif defined(_UV) - o.uv = TRANSFORM_TEX(v.uv, _MainTex); -#endif - -#if defined(LIGHTMAP_ON) - o.lightMapUV.xy = v.uv1.xy * unity_LightmapST.xy + unity_LightmapST.zw; -#endif - -#if defined(_VERTEX_COLORS) - o.color = v.color; -#endif - -#if defined(_SPHERICAL_HARMONICS) - o.ambient = ShadeSH9(float4(worldNormal, 1.0)); -#endif - -#if defined(_IRIDESCENCE) - float3 rightTangent = normalize(mul((float3x3)unity_ObjectToWorld, float3(1.0, 0.0, 0.0))); - float3 incidentWithCenter = normalize(mul(unity_ObjectToWorld, float4(0.0, 0.0, 0.0, 1.0)) - _WorldSpaceCameraPos); - float tangentDotIncident = dot(rightTangent, incidentWithCenter); - o.iridescentColor = Iridescence(tangentDotIncident, _IridescentSpectrumMap, _IridescenceThreshold, v.uv, _IridescenceAngle, _IridescenceIntensity); -#endif - -#if defined(_NORMAL) -#if defined(_TRIPLANAR_MAPPING) - o.worldNormal = worldNormal; -#if defined(_LOCAL_SPACE_TRIPLANAR_MAPPING) - o.triplanarNormal = localNormal; - o.triplanarPosition = vertexPosition; -#else - o.triplanarNormal = worldNormal; - o.triplanarPosition = o.worldPosition; -#endif -#elif defined(_NORMAL_MAP) - fixed3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz); - fixed tangentSign = v.tangent.w * unity_WorldTransformParams.w; - fixed3 worldBitangent = cross(worldNormal, worldTangent) * tangentSign; - o.tangentX = fixed3(worldTangent.x, worldBitangent.x, worldNormal.x); - o.tangentY = fixed3(worldTangent.y, worldBitangent.y, worldNormal.y); - o.tangentZ = fixed3(worldTangent.z, worldBitangent.z, worldNormal.z); -#else - o.worldNormal = worldNormal; -#endif -#endif - - return o; - } - - fixed4 frag(v2f i, fixed facing : VFACE) : SV_Target - { -#if defined(_INSTANCED_COLOR) - UNITY_SETUP_INSTANCE_ID(i); -#endif - -#if defined(_TRIPLANAR_MAPPING) - // Calculate triplanar uvs and apply texture scale and offset values like TRANSFORM_TEX. - fixed3 triplanarBlend = pow(abs(i.triplanarNormal), _TriplanarMappingBlendSharpness); - triplanarBlend /= dot(triplanarBlend, fixed3(1.0, 1.0, 1.0)); - float2 uvX = i.triplanarPosition.zy * _MainTex_ST.xy + _MainTex_ST.zw; - float2 uvY = i.triplanarPosition.xz * _MainTex_ST.xy + _MainTex_ST.zw; - float2 uvZ = i.triplanarPosition.xy * _MainTex_ST.xy + _MainTex_ST.zw; - - // Ternary operator is 2 instructions faster than sign() when we don't care about zero returning a zero sign. - float3 axisSign = i.triplanarNormal < 0 ? -1 : 1; - uvX.x *= axisSign.x; - uvY.x *= axisSign.y; - uvZ.x *= -axisSign.z; -#endif - - // Texturing. -#if defined(_DISABLE_ALBEDO_MAP) - fixed4 albedo = fixed4(1.0, 1.0, 1.0, 1.0); -#else -#if defined(_TRIPLANAR_MAPPING) - fixed4 albedo = tex2D(_MainTex, uvX) * triplanarBlend.x + - tex2D(_MainTex, uvY) * triplanarBlend.y + - tex2D(_MainTex, uvZ) * triplanarBlend.z; -#else - fixed4 albedo = tex2D(_MainTex, i.uv); -#endif -#endif - -#ifdef LIGHTMAP_ON - albedo.rgb *= DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, i.lightMapUV)); -#endif - -#if defined(_CHANNEL_MAP) - fixed4 channel = tex2D(_ChannelMap, i.uv); - _Metallic = channel.r; - albedo.rgb *= channel.g; - _Smoothness = channel.a; -#else -#if defined(_METALLIC_TEXTURE_ALBEDO_CHANNEL_A) - _Metallic = albedo.a; - albedo.a = 1.0; -#elif defined(_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A) - _Smoothness = albedo.a; - albedo.a = 1.0; -#endif -#endif - - // Primitive clipping. -#if defined(_CLIPPING_PRIMITIVE) - float primitiveDistance = 1.0; -#if defined(_CLIPPING_PLANE) - primitiveDistance = min(primitiveDistance, PointVsPlane(i.worldPosition.xyz, _ClipPlane) * _ClipPlaneSide); -#endif -#if defined(_CLIPPING_SPHERE) - primitiveDistance = min(primitiveDistance, PointVsSphere(i.worldPosition.xyz, _ClipSphere) * _ClipSphereSide); -#endif -#if defined(_CLIPPING_BOX) - primitiveDistance = min(primitiveDistance, PointVsBox(i.worldPosition.xyz, _ClipBoxSize.xyz, _ClipBoxInverseTransform) * _ClipBoxSide); -#endif -#if defined(_CLIPPING_BORDER) - fixed3 primitiveBorderColor = lerp(_ClippingBorderColor, fixed3(0.0, 0.0, 0.0), primitiveDistance / _ClippingBorderWidth); - albedo.rgb += primitiveBorderColor * IF((primitiveDistance < _ClippingBorderWidth), 1.0, 0.0); -#endif -#endif - -#if defined(_DISTANCE_TO_EDGE) - fixed2 distanceToEdge; - distanceToEdge.x = abs(i.uv.x - 0.5) * 2.0; - distanceToEdge.y = abs(i.uv.y - 0.5) * 2.0; -#endif - - // Rounded corner clipping. -#if defined(_ROUND_CORNERS) - float2 halfScale = i.scale.xy * 0.5; - float2 roundCornerPosition = distanceToEdge * halfScale; - - fixed currentCornerRadius; - -#if defined(_INDEPENDENT_CORNERS) - - _RoundCornersRadius = clamp(_RoundCornersRadius, 0, 0.5); - - if (i.uv.x < 0.5) - { - if (i.uv.y > 0.5) - { - currentCornerRadius = _RoundCornersRadius.x; - } - else - { - currentCornerRadius = _RoundCornersRadius.w; - } - } - else - { - if (i.uv.y > 0.5) - { - currentCornerRadius = _RoundCornersRadius.y; - } - else - { - currentCornerRadius = _RoundCornersRadius.z; - } - } -#else - currentCornerRadius = _RoundCornerRadius; -#endif - - float cornerCircleRadius = saturate(max(currentCornerRadius - _RoundCornerMargin, 0.01)) * i.scale.z; - - float2 cornerCircleDistance = halfScale - (_RoundCornerMargin * i.scale.z) - cornerCircleRadius; - - float roundCornerClip = RoundCorners(roundCornerPosition, cornerCircleDistance, cornerCircleRadius); -#endif - -#if defined(_INSTANCED_COLOR) - albedo *= UNITY_ACCESS_INSTANCED_PROP(Props, _Color); -#else - albedo *= _Color; -#endif - -#if defined(_VERTEX_COLORS) - albedo *= i.color; -#endif - -#if defined(_IRIDESCENCE) - albedo.rgb += i.iridescentColor; -#endif - - // Normal calculation. -#if defined(_NORMAL) - fixed3 worldViewDir = normalize(UnityWorldSpaceViewDir(i.worldPosition.xyz)); -#if defined(_REFLECTIONS) || defined(_ENVIRONMENT_COLORING) - fixed3 incident = -worldViewDir; -#endif - fixed3 worldNormal; - -#if defined(_NORMAL_MAP) -#if defined(_TRIPLANAR_MAPPING) - fixed3 tangentNormalX = UnpackScaleNormal(tex2D(_NormalMap, uvX), _NormalMapScale); - fixed3 tangentNormalY = UnpackScaleNormal(tex2D(_NormalMap, uvY), _NormalMapScale); - fixed3 tangentNormalZ = UnpackScaleNormal(tex2D(_NormalMap, uvZ), _NormalMapScale); - tangentNormalX.x *= axisSign.x; - tangentNormalY.x *= axisSign.y; - tangentNormalZ.x *= -axisSign.z; - - // Swizzle world normals to match tangent space and apply Whiteout normal blend. - tangentNormalX = fixed3(tangentNormalX.xy + i.worldNormal.zy, tangentNormalX.z * i.worldNormal.x); - tangentNormalY = fixed3(tangentNormalY.xy + i.worldNormal.xz, tangentNormalY.z * i.worldNormal.y); - tangentNormalZ = fixed3(tangentNormalZ.xy + i.worldNormal.xy, tangentNormalZ.z * i.worldNormal.z); - - // Swizzle tangent normals to match world normal and blend together. - worldNormal = normalize(tangentNormalX.zyx * triplanarBlend.x + - tangentNormalY.xzy * triplanarBlend.y + - tangentNormalZ.xyz * triplanarBlend.z); -#else - fixed3 tangentNormal = UnpackScaleNormal(tex2D(_NormalMap, i.uv), _NormalMapScale); - worldNormal.x = dot(i.tangentX, tangentNormal); - worldNormal.y = dot(i.tangentY, tangentNormal); - worldNormal.z = dot(i.tangentZ, tangentNormal); - worldNormal = normalize(worldNormal) * facing; -#endif -#else - worldNormal = normalize(i.worldNormal) * facing; -#endif -#endif - - fixed pointToLight = 1.0; - fixed3 fluentLightColor = fixed3(0.0, 0.0, 0.0); - - // Hover light. -#if defined(_HOVER_LIGHT) - pointToLight = 0.0; - - [unroll] - for (int hoverLightIndex = 0; hoverLightIndex < HOVER_LIGHT_COUNT; ++hoverLightIndex) - { - int dataIndex = hoverLightIndex * HOVER_LIGHT_DATA_SIZE; - fixed hoverValue = HoverLight(_HoverLightData[dataIndex], _HoverLightData[dataIndex + 1].w, i.worldPosition.xyz); - pointToLight += hoverValue; -#if !defined(_HOVER_COLOR_OVERRIDE) - fluentLightColor += lerp(fixed3(0.0, 0.0, 0.0), _HoverLightData[dataIndex + 1].rgb, hoverValue); -#endif - } -#if defined(_HOVER_COLOR_OVERRIDE) - fluentLightColor = _HoverColorOverride.rgb * pointToLight; -#endif -#endif - - // Proximity light. -#if defined(_PROXIMITY_LIGHT) -#if !defined(_HOVER_LIGHT) - pointToLight = 0.0; -#endif - [unroll] - for (int proximityLightIndex = 0; proximityLightIndex < PROXIMITY_LIGHT_COUNT; ++proximityLightIndex) - { - int dataIndex = proximityLightIndex * PROXIMITY_LIGHT_DATA_SIZE; - fixed colorValue; - fixed proximityValue = ProximityLight(_ProximityLightData[dataIndex], _ProximityLightData[dataIndex + 1], _ProximityLightData[dataIndex + 2], i.worldPosition.xyz, worldNormal, colorValue); - pointToLight += proximityValue; -#if defined(_PROXIMITY_LIGHT_COLOR_OVERRIDE) - fixed3 proximityColor = MixProximityLightColor(_ProximityLightCenterColorOverride, _ProximityLightMiddleColorOverride, _ProximityLightOuterColorOverride, colorValue); -#else - fixed3 proximityColor = MixProximityLightColor(_ProximityLightData[dataIndex + 3], _ProximityLightData[dataIndex + 4], _ProximityLightData[dataIndex + 5], colorValue); -#endif -#if defined(_PROXIMITY_LIGHT_SUBTRACTIVE) - fluentLightColor -= lerp(fixed3(0.0, 0.0, 0.0), proximityColor, proximityValue); -#else - fluentLightColor += lerp(fixed3(0.0, 0.0, 0.0), proximityColor, proximityValue); -#endif - } -#endif - - // Border light. -#if defined(_BORDER_LIGHT) - fixed borderValue; -#if defined(_ROUND_CORNERS) - fixed borderMargin = _RoundCornerMargin + _BorderWidth * 0.5; - - cornerCircleRadius = saturate(max(currentCornerRadius - borderMargin, 0.01)) * i.scale.z; - - cornerCircleDistance = halfScale - (borderMargin * i.scale.z) - cornerCircleRadius; - - borderValue = 1.0 - RoundCornersSmooth(roundCornerPosition, cornerCircleDistance, cornerCircleRadius); -#else - borderValue = max(smoothstep(i.uv.z - _EdgeSmoothingValue, i.uv.z + _EdgeSmoothingValue, distanceToEdge.x), - smoothstep(i.uv.w - _EdgeSmoothingValue, i.uv.w + _EdgeSmoothingValue, distanceToEdge.y)); -#endif -#if defined(_HOVER_LIGHT) && defined(_BORDER_LIGHT_USES_HOVER_COLOR) && defined(_HOVER_COLOR_OVERRIDE) - fixed3 borderColor = _HoverColorOverride.rgb; -#else - fixed3 borderColor = fixed3(1.0, 1.0, 1.0); -#endif - fixed3 borderContribution = borderColor * borderValue * _BorderMinValue * _FluentLightIntensity; -#if defined(_BORDER_LIGHT_REPLACES_ALBEDO) - albedo.rgb = lerp(albedo.rgb, borderContribution, borderValue); -#else - albedo.rgb += borderContribution; -#endif -#if defined(_HOVER_LIGHT) || defined(_PROXIMITY_LIGHT) - albedo.rgb += (fluentLightColor * borderValue * pointToLight * _FluentLightIntensity) * 2.0; -#endif -#if defined(_BORDER_LIGHT_OPAQUE) - albedo.a = max(albedo.a, borderValue * _BorderLightOpaqueAlpha); -#endif -#endif - -#if defined(_ROUND_CORNERS) - albedo *= roundCornerClip; - pointToLight *= roundCornerClip; -#endif - -#if defined(_ALPHA_CLIP) -#if !defined(_ALPHATEST_ON) - _Cutoff = 0.5; -#endif -#if defined(_CLIPPING_PRIMITIVE) - albedo *= (primitiveDistance > 0.0); -#endif - clip(albedo.a - _Cutoff); - albedo.a = 1.0; -#endif - - // Blinn phong lighting. -#if defined(_DIRECTIONAL_LIGHT) -#if defined(_LIGHTWEIGHT_RENDER_PIPELINE) - float4 directionalLightDirection = _MainLightPosition; -#else - float4 directionalLightDirection = _WorldSpaceLightPos0; -#endif - fixed diffuse = max(0.0, dot(worldNormal, directionalLightDirection)); -#if defined(_SPECULAR_HIGHLIGHTS) - fixed halfVector = max(0.0, dot(worldNormal, normalize(directionalLightDirection + worldViewDir))); - fixed specular = saturate(pow(halfVector, _Shininess * pow(_Smoothness, 4.0)) * (_Smoothness * 2.0) * _Metallic); -#else - fixed specular = 0.0; -#endif -#endif - - // Image based lighting (attempt to mimic the Standard shader). -#if defined(_REFLECTIONS) - fixed3 worldReflection = reflect(incident, worldNormal); - fixed4 iblData = UNITY_SAMPLE_TEXCUBE_LOD(unity_SpecCube0, worldReflection, (1.0 - _Smoothness) * UNITY_SPECCUBE_LOD_STEPS); - fixed3 ibl = DecodeHDR(iblData, unity_SpecCube0_HDR); -#if defined(_REFRACTION) - fixed4 refractColor = UNITY_SAMPLE_TEXCUBE(unity_SpecCube0, refract(incident, worldNormal, _RefractiveIndex)); - ibl *= DecodeHDR(refractColor, unity_SpecCube0_HDR); -#endif -#else - fixed3 ibl = unity_IndirectSpecColor.rgb; -#endif - - // Fresnel lighting. -#if defined(_FRESNEL) - fixed fresnel = 1.0 - saturate(abs(dot(worldViewDir, worldNormal))); -#if defined(_RIM_LIGHT) - fixed3 fresnelColor = _RimColor * pow(fresnel, _RimPower); -#else - fixed3 fresnelColor = unity_IndirectSpecColor.rgb * (pow(fresnel, _FresnelPower) * max(_Smoothness, 0.5)); -#endif -#endif - // Final lighting mix. - fixed4 output = albedo; -#if defined(_SPHERICAL_HARMONICS) - fixed3 ambient = i.ambient; -#else - fixed3 ambient = glstate_lightmodel_ambient + fixed3(0.25, 0.25, 0.25); -#endif - fixed minProperty = min(_Smoothness, _Metallic); -#if defined(_DIRECTIONAL_LIGHT) - fixed oneMinusMetallic = (1.0 - _Metallic); - output.rgb = lerp(output.rgb, ibl, minProperty); -#if defined(_LIGHTWEIGHT_RENDER_PIPELINE) - fixed3 directionalLightColor = _MainLightColor.rgb; -#else - fixed3 directionalLightColor = _LightColor0.rgb; -#endif - output.rgb *= lerp((ambient + directionalLightColor * diffuse + directionalLightColor * specular) * max(oneMinusMetallic, _MinMetallicLightContribution), albedo, minProperty); - output.rgb += (directionalLightColor * albedo * specular) + (directionalLightColor * specular * _Smoothness); - output.rgb += ibl * oneMinusMetallic * _IblContribution; -#elif defined(_REFLECTIONS) - output.rgb = lerp(output.rgb, ibl, minProperty); - output.rgb *= lerp(ambient, albedo, minProperty); -#elif defined(_SPHERICAL_HARMONICS) - output.rgb *= ambient; -#endif - -#if defined(_FRESNEL) -#if defined(_RIM_LIGHT) || !defined(_REFLECTIONS) - output.rgb += fresnelColor; -#else - output.rgb += fresnelColor * (1.0 - minProperty); -#endif -#endif - -#if defined(_EMISSION) -#if defined(_CHANNEL_MAP) - output.rgb += _EmissiveColor * channel.b; -#else - output.rgb += _EmissiveColor; -#endif -#endif - - // Inner glow. -#if defined(_INNER_GLOW) - fixed2 uvGlow = pow(distanceToEdge * _InnerGlowColor.a, _InnerGlowPower); - output.rgb += lerp(fixed3(0.0, 0.0, 0.0), _InnerGlowColor.rgb, uvGlow.x + uvGlow.y); -#endif - - // Environment coloring. -#if defined(_ENVIRONMENT_COLORING) - fixed3 environmentColor = incident.x * incident.x * _EnvironmentColorX + - incident.y * incident.y * _EnvironmentColorY + - incident.z * incident.z * _EnvironmentColorZ; - output.rgb += environmentColor * max(0.0, dot(incident, worldNormal) + _EnvironmentColorThreshold) * _EnvironmentColorIntensity; - -#endif - -#if defined(_NEAR_PLANE_FADE) - output *= i.worldPosition.w; -#endif - - // Hover and proximity lighting should occur after near plane fading. -#if defined(_HOVER_LIGHT) || defined(_PROXIMITY_LIGHT) - output.rgb += fluentLightColor * _FluentLightIntensity * pointToLight; -#endif - - // Perform non-alpha clipped primitive clipping on the final output. -#if defined(_CLIPPING_PRIMITIVE) && !defined(_ALPHA_CLIP) - output *= saturate(primitiveDistance * (1.0f / _BlendedClippingWidth)); -#endif - return output; - } - - ENDCG - } - - // Extracts information for lightmapping, GI (emission, albedo, ...) - // This pass it not used during regular rendering. - Pass - { - Name "Meta" - Tags { "LightMode" = "Meta" } - - CGPROGRAM - - #pragma vertex vert - #pragma fragment frag - - #pragma shader_feature EDITOR_VISUALIZATION - #pragma shader_feature _EMISSION - #pragma shader_feature _CHANNEL_MAP - - #include "UnityCG.cginc" - #include "UnityMetaPass.cginc" - - // This define will get commented in by the UpgradeShaderForLightweightRenderPipeline method. - //#define _LIGHTWEIGHT_RENDER_PIPELINE - - struct v2f - { - float4 vertex : SV_POSITION; - float2 uv : TEXCOORD0; - }; - - float4 _MainTex_ST; - - v2f vert(appdata_full v) - { - v2f o; - o.vertex = UnityMetaVertexPosition(v.vertex, v.texcoord1.xy, v.texcoord2.xy, unity_LightmapST, unity_DynamicLightmapST); - o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); - - return o; - } - - sampler2D _MainTex; - sampler2D _ChannelMap; - - fixed4 _Color; - fixed4 _EmissiveColor; - -#if defined(_LIGHTWEIGHT_RENDER_PIPELINE) - CBUFFER_START(_LightBuffer) - float4 _MainLightPosition; - half4 _MainLightColor; - CBUFFER_END -#else - fixed4 _LightColor0; -#endif - - half4 frag(v2f i) : SV_Target - { - UnityMetaInput output; - UNITY_INITIALIZE_OUTPUT(UnityMetaInput, output); - - output.Albedo = tex2D(_MainTex, i.uv) * _Color; -#if defined(_EMISSION) -#if defined(_CHANNEL_MAP) - output.Emission += tex2D(_ChannelMap, i.uv).b * _EmissiveColor; -#else - output.Emission += _EmissiveColor; -#endif -#endif -#if defined(_LIGHTWEIGHT_RENDER_PIPELINE) - output.SpecularColor = _MainLightColor.rgb; -#else - output.SpecularColor = _LightColor0.rgb; -#endif - - return UnityMetaFragment(output); - } - ENDCG - } - } - - Fallback "Hidden/InternalErrorShader" - CustomEditor "Microsoft.MixedReality.Toolkit.Editor.MixedRealityStandardShaderGUI" -} diff --git a/Assets/MirageXR/Common/Resources/Materials/myHolographicButtonContentCageProximity.mat b/Assets/MirageXR/Common/Resources/Materials/myHolographicButtonContentCageProximity.mat index b1a3c638d..98bd065a1 100644 --- a/Assets/MirageXR/Common/Resources/Materials/myHolographicButtonContentCageProximity.mat +++ b/Assets/MirageXR/Common/Resources/Materials/myHolographicButtonContentCageProximity.mat @@ -2,16 +2,25 @@ %TAG !u! tag:unity3d.com,2011: --- !u!21 &2100000 Material: - serializedVersion: 6 + serializedVersion: 8 m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_Name: myHolographicButtonContentCageProximity m_Shader: {fileID: 4800000, guid: 5bdea20278144b11916d77503ba1467a, type: 3} - m_ShaderKeywords: _ALPHABLEND_ON _BORDER_LIGHT _BORDER_LIGHT_USES_HOVER_COLOR _DISABLE_ALBEDO_MAP - _HOVER_LIGHT _METALLIC_TEXTURE_ALBEDO_CHANNEL_A _NEAR_LIGHT_FADE _NEAR_PLANE_FADE - _PROXIMITY_LIGHT _PROXIMITY_LIGHT_TWO_SIDED + m_ValidKeywords: + - _ALPHABLEND_ON + - _BORDER_LIGHT + - _BORDER_LIGHT_USES_HOVER_COLOR + - _DISABLE_ALBEDO_MAP + - _HOVER_LIGHT + - _METALLIC_TEXTURE_ALBEDO_CHANNEL_A + - _NEAR_LIGHT_FADE + - _NEAR_PLANE_FADE + - _PROXIMITY_LIGHT + - _PROXIMITY_LIGHT_TWO_SIDED + m_InvalidKeywords: [] m_LightmapFlags: 4 m_EnableInstancingVariants: 1 m_DoubleSidedGI: 0 @@ -74,6 +83,7 @@ Material: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} + m_Ints: [] m_Floats: - _AlbedoAlphaMode: 1 - _AlbedoAlphaSmoothness: 0 @@ -113,6 +123,7 @@ Material: - _EnableLocalSpaceTriplanarMapping: 0 - _EnableNormalMap: 0 - _EnableProximityLightColorOverride: 0 + - _EnableSSAA: 0 - _EnableTriplanarMapping: 0 - _EnvironmentColorIntensity: 0.5 - _EnvironmentColorThreshold: 1.5 @@ -136,7 +147,8 @@ Material: - _IridescenceIntensity: 0.5 - _IridescenceThreshold: 0.05 - _Metallic: 0 - - _Mode: 4 + - _MipmapBias: -2 + - _Mode: 5 - _NearLightFade: 1 - _NearPlaneFade: 1 - _NormalMapScale: 1 @@ -172,7 +184,7 @@ Material: - _ZOffsetFactor: 0 - _ZOffsetUnits: 0 - _ZTest: 4 - - _ZWrite: 0 + - _ZWrite: 1 m_Colors: - _ClipPlane: {r: 0, g: 1, b: 0, a: 0} - _ClippingBorderColor: {r: 1, g: 0.2, b: 0, a: 1} @@ -192,3 +204,4 @@ Material: - _ProximityLightOuterColorOverride: {r: 0, g: 0, b: 1, a: 1} - _RimColor: {r: 1, g: 1, b: 1, a: 0.497} - _RoundCornersRadius: {r: 0.5, g: 0.5, b: 0.5, a: 0.5} + m_BuildTextureStacks: [] diff --git a/Assets/MirageXR/Common/Resources/Materials/myMRTK_PressableInteractablesButtonBox.mat b/Assets/MirageXR/Common/Resources/Materials/myMRTK_PressableInteractablesButtonBox.mat index 22e07388e..e0813fa4a 100644 --- a/Assets/MirageXR/Common/Resources/Materials/myMRTK_PressableInteractablesButtonBox.mat +++ b/Assets/MirageXR/Common/Resources/Materials/myMRTK_PressableInteractablesButtonBox.mat @@ -2,16 +2,26 @@ %TAG !u! tag:unity3d.com,2011: --- !u!21 &2100000 Material: - serializedVersion: 6 + serializedVersion: 8 m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_Name: myMRTK_PressableInteractablesButtonBox m_Shader: {fileID: 4800000, guid: 5bdea20278144b11916d77503ba1467a, type: 3} - m_ShaderKeywords: USE_GLOBAL_LEFT_INDEX_ON USE_GLOBAL_RIGHT_INDEX_ON _ALPHABLEND_ON - _BLOB_ENABLE_2__ON _BLOB_ENABLE__ON _BORDER_LIGHT _DISABLE_ALBEDO_MAP _ENABLE_FADE__ON - _NEAR_LIGHT_FADE _NEAR_PLANE_FADE _SMOOTH_ACTIVE_FACE__ON + m_ValidKeywords: + - _ALPHABLEND_ON + - _BORDER_LIGHT + - _DISABLE_ALBEDO_MAP + - _NEAR_LIGHT_FADE + - _NEAR_PLANE_FADE + m_InvalidKeywords: + - USE_GLOBAL_LEFT_INDEX_ON + - USE_GLOBAL_RIGHT_INDEX_ON + - _BLOB_ENABLE_2__ON + - _BLOB_ENABLE__ON + - _ENABLE_FADE__ON + - _SMOOTH_ACTIVE_FACE__ON m_LightmapFlags: 4 m_EnableInstancingVariants: 1 m_DoubleSidedGI: 0 @@ -38,6 +48,7 @@ Material: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} + m_Ints: [] m_Floats: - _AlbedoAlphaMode: 0 - _AlbedoAssignedAtRuntime: 0 @@ -68,6 +79,7 @@ Material: - _EnableLocalSpaceTriplanarMapping: 0 - _EnableNormalMap: 0 - _EnableProximityLightColorOverride: 0 + - _EnableSSAA: 0 - _EnableTriplanarMapping: 0 - _EnvironmentColorIntensity: 0.5 - _EnvironmentColorThreshold: 1.5 @@ -87,7 +99,8 @@ Material: - _IridescenceIntensity: 0.5 - _IridescenceThreshold: 0.05 - _Metallic: 0 - - _Mode: 4 + - _MipmapBias: -2 + - _Mode: 5 - _NearLightFade: 1 - _NearPlaneFade: 1 - _NormalMapScale: 1 @@ -119,7 +132,7 @@ Material: - _ZOffsetFactor: 0 - _ZOffsetUnits: 0 - _ZTest: 4 - - _ZWrite: 0 + - _ZWrite: 1 m_Colors: - _ClippingBorderColor: {r: 1, g: 0.2, b: 0, a: 1} - _Color: {r: 0.1254902, g: 0.1254902, b: 0.1254902, a: 0} @@ -134,3 +147,4 @@ Material: - _ProximityLightOuterColorOverride: {r: 0, g: 0, b: 1, a: 1} - _RimColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} - _RoundCornersRadius: {r: 0.5, g: 0.5, b: 0.5, a: 0.5} + m_BuildTextureStacks: [] diff --git a/Assets/MirageXR/Common/Resources/SplashScreen/splash2.png b/Assets/MirageXR/Common/Resources/SplashScreen/splash2.png index 342ab6d3e..2cbb8bcee 100644 Binary files a/Assets/MirageXR/Common/Resources/SplashScreen/splash2.png and b/Assets/MirageXR/Common/Resources/SplashScreen/splash2.png differ diff --git a/Assets/MirageXR/Common/Resources/SplashScreen/splash_background.png b/Assets/MirageXR/Common/Resources/SplashScreen/splash_background.png deleted file mode 100644 index 84494457f..000000000 Binary files a/Assets/MirageXR/Common/Resources/SplashScreen/splash_background.png and /dev/null differ diff --git a/Assets/MirageXR/Common/ExperienceAPI.meta b/Assets/MirageXR/Common/Resources_moved.meta similarity index 77% rename from Assets/MirageXR/Common/ExperienceAPI.meta rename to Assets/MirageXR/Common/Resources_moved.meta index 0e285bb8d..7e1f0a1e7 100644 --- a/Assets/MirageXR/Common/ExperienceAPI.meta +++ b/Assets/MirageXR/Common/Resources_moved.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6a911ac88fb3b4edd8be4a81d1ec3078 +guid: 92f1ae8d9c392af428e6517a90503ed5 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/MirageXR/Recorder.meta b/Assets/MirageXR/Common/Resources_moved/Prefabs.meta similarity index 77% rename from Assets/MirageXR/Recorder.meta rename to Assets/MirageXR/Common/Resources_moved/Prefabs.meta index 9ee7ff13d..d5c6eba14 100644 --- a/Assets/MirageXR/Recorder.meta +++ b/Assets/MirageXR/Common/Resources_moved/Prefabs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 590f8e40592ea9348a6db02070978ff7 +guid: 0750de3d494fca44da3c63b7613a717b folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/MirageXR/Common/Resources/Prefabs/WEKITCalibrationMarker.prefab b/Assets/MirageXR/Common/Resources_moved/Prefabs/WEKITCalibrationMarker.prefab similarity index 86% rename from Assets/MirageXR/Common/Resources/Prefabs/WEKITCalibrationMarker.prefab rename to Assets/MirageXR/Common/Resources_moved/Prefabs/WEKITCalibrationMarker.prefab index 9d0282928..8ffc38214 100644 --- a/Assets/MirageXR/Common/Resources/Prefabs/WEKITCalibrationMarker.prefab +++ b/Assets/MirageXR/Common/Resources_moved/Prefabs/WEKITCalibrationMarker.prefab @@ -9,12 +9,13 @@ GameObject: serializedVersion: 6 m_Component: - component: {fileID: 4999640239509956} + - component: {fileID: 114319897983807614} - component: {fileID: 114557464381435048} - component: {fileID: 114264436370149114} - component: {fileID: 114411897829192900} - component: {fileID: 23604243217046940} - component: {fileID: 33609130599881980} - - component: {fileID: 114319897983807614} + - component: {fileID: 1229822959470238459} m_Layer: 0 m_Name: WEKITCalibrationMarker m_TagString: CalibrationTarget @@ -32,12 +33,28 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: - {fileID: 4001133710822054} - {fileID: 2040808958413678622} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &114319897983807614 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1284601556465576} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 3659dc8861ebb79468a05b9375b82158, type: 3} + m_Name: + m_EditorClassIdentifier: + _calibrationAnimation: {fileID: 8688722655886690522} + _imageTargetBehaviour: {fileID: 114557464381435048} + _trackableEventHandler: {fileID: 114264436370149114} --- !u!114 &114557464381435048 MonoBehaviour: m_ObjectHideFlags: 0 @@ -70,7 +87,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 5a917f0af64a6423093132dab321c15f, type: 3} m_Name: m_EditorClassIdentifier: - StatusFilter: 2 + StatusFilter: 0 OnTargetFound: m_PersistentCalls: m_Calls: [] @@ -99,11 +116,13 @@ MeshRenderer: m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 - m_DynamicOccludee: 1 + m_DynamicOccludee: 0 + m_StaticShadowCaster: 0 m_MotionVectors: 1 m_LightProbeUsage: 0 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 + m_RayTraceProcedural: 0 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: @@ -128,6 +147,7 @@ MeshRenderer: m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 + m_AdditionalVertexStreams: {fileID: 0} --- !u!33 &33609130599881980 MeshFilter: m_ObjectHideFlags: 0 @@ -136,19 +156,19 @@ MeshFilter: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1284601556465576} m_Mesh: {fileID: 0} ---- !u!114 &114319897983807614 -MonoBehaviour: +--- !u!65 &1229822959470238459 +BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1284601556465576} + m_Material: {fileID: 0} + m_IsTrigger: 0 m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 3659dc8861ebb79468a05b9375b82158, type: 3} - m_Name: - m_EditorClassIdentifier: - CalibrationModel: {fileID: 1664564138516345508} + serializedVersion: 2 + m_Size: {x: 0.2, y: 0.02, z: 0.2} + m_Center: {x: 0, y: 0, z: 0} --- !u!1 &1884879084585258 GameObject: m_ObjectHideFlags: 0 @@ -175,6 +195,7 @@ Transform: m_LocalRotation: {x: 0.7071068, y: -0, z: -0, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.75, y: 0.75000036, z: 0.75000036} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 4999640239509956} m_RootOrder: 0 @@ -186,6 +207,11 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 4999640239509956} m_Modifications: + - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, + type: 3} + propertyPath: m_RootOrder + value: 1 + objectReference: {fileID: 0} - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} propertyPath: m_LocalPosition.x @@ -199,7 +225,12 @@ PrefabInstance: - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} propertyPath: m_LocalPosition.z - value: -0.0056000003 + value: -0.01 + objectReference: {fileID: 0} + - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, + type: 3} + propertyPath: m_LocalRotation.w + value: 0 objectReference: {fileID: 0} - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} @@ -216,16 +247,6 @@ PrefabInstance: propertyPath: m_LocalRotation.z value: 0 objectReference: {fileID: 0} - - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, - type: 3} - propertyPath: m_LocalRotation.w - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, - type: 3} - propertyPath: m_RootOrder - value: 1 - objectReference: {fileID: 0} - target: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} propertyPath: m_LocalEulerAnglesHint.x @@ -244,7 +265,12 @@ PrefabInstance: - target: {fileID: 1963626833195538831, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} propertyPath: m_Name - value: calibrationModel + value: calibrationAnimation + objectReference: {fileID: 0} + - target: {fileID: 1963626833195538831, guid: 2263cc554d5ba99408035a5c398bdc2b, + type: 3} + propertyPath: m_IsActive + value: 1 objectReference: {fileID: 0} - target: {fileID: 5041373017815340818, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} @@ -253,15 +279,21 @@ PrefabInstance: objectReference: {fileID: 114319897983807614} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} ---- !u!1 &1664564138516345508 stripped -GameObject: - m_CorrespondingSourceObject: {fileID: 1963626833195538831, guid: 2263cc554d5ba99408035a5c398bdc2b, - type: 3} - m_PrefabInstance: {fileID: 889896817235684139} - m_PrefabAsset: {fileID: 0} --- !u!4 &2040808958413678622 stripped Transform: m_CorrespondingSourceObject: {fileID: 1156269104705553205, guid: 2263cc554d5ba99408035a5c398bdc2b, type: 3} m_PrefabInstance: {fileID: 889896817235684139} m_PrefabAsset: {fileID: 0} +--- !u!114 &8688722655886690522 stripped +MonoBehaviour: + m_CorrespondingSourceObject: {fileID: 8416391285486035953, guid: 2263cc554d5ba99408035a5c398bdc2b, + type: 3} + m_PrefabInstance: {fileID: 889896817235684139} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 122a62088c187a34685d2c9e4197fb0b, type: 3} + m_Name: + m_EditorClassIdentifier: diff --git a/Assets/MirageXR/Common/Resources/Prefabs/WEKITCalibrationMarker.prefab.meta b/Assets/MirageXR/Common/Resources_moved/Prefabs/WEKITCalibrationMarker.prefab.meta similarity index 100% rename from Assets/MirageXR/Common/Resources/Prefabs/WEKITCalibrationMarker.prefab.meta rename to Assets/MirageXR/Common/Resources_moved/Prefabs/WEKITCalibrationMarker.prefab.meta diff --git a/Assets/MirageXR/Common/Scenes/Start.unity b/Assets/MirageXR/Common/Scenes/Start.unity index 8e6a7a048..32ed9a6f2 100644 --- a/Assets/MirageXR/Common/Scenes/Start.unity +++ b/Assets/MirageXR/Common/Scenes/Start.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0.37311953, g: 0.38074014, b: 0.3587274, a: 1} + m_IndirectSpecularColor: {r: 0.3708985, g: 0.3783704, b: 0.35722548, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -151,6 +151,7 @@ Transform: m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1694069695} m_RootOrder: 0 @@ -194,6 +195,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1263153152} m_RootOrder: 4 @@ -236,9 +238,9 @@ Transform: m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: - {fileID: 2036437840} - - {fileID: 1006685207} m_Father: {fileID: 1694069695} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} @@ -270,6 +272,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1694069695} m_RootOrder: 1 @@ -421,82 +424,42 @@ Transform: m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -598.7456, y: -309.94717, z: 182.66833} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1263153152} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!1 &507532542 -GameObject: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - serializedVersion: 6 - m_Component: - - component: {fileID: 507532543} - - component: {fileID: 507532544} - m_Layer: 0 - m_Name: RendererCheck - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!4 &507532543 -Transform: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 507532542} - m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} - m_LocalPosition: {x: 0, y: 0, z: 0} - m_LocalScale: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1006685207} - m_RootOrder: 1 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!23 &507532544 -MeshRenderer: +--- !u!21 &398264897 +Material: + serializedVersion: 8 m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 507532542} - m_Enabled: 1 - m_CastShadows: 1 - m_ReceiveShadows: 1 - m_DynamicOccludee: 1 - m_MotionVectors: 1 - m_LightProbeUsage: 1 - m_ReflectionProbeUsage: 1 - m_RayTracingMode: 2 - m_RayTraceProcedural: 0 - m_RenderingLayerMask: 1 - m_RendererPriority: 0 - m_Materials: - - {fileID: 0} - m_StaticBatchInfo: - firstSubMesh: 0 - subMeshCount: 0 - m_StaticBatchRoot: {fileID: 0} - m_ProbeAnchor: {fileID: 0} - m_LightProbeVolumeOverride: {fileID: 0} - m_ScaleInLightmap: 1 - m_ReceiveGI: 1 - m_PreserveUVs: 0 - m_IgnoreNormalsForChartDetection: 0 - m_ImportantGI: 0 - m_StitchLightmapSeams: 0 - m_SelectedEditorRenderState: 3 - m_MinimumChartSize: 4 - m_AutoUVMaxDistance: 0.5 - m_AutoUVMaxAngle: 89 - m_LightmapParameters: {fileID: 0} - m_SortingLayerID: 0 - m_SortingLayer: 0 - m_SortingOrder: 0 - m_AdditionalVertexStreams: {fileID: 0} + m_Name: 'targetMaterial + + -1292' + m_Shader: {fileID: 10752, guid: 0000000000000000f000000000000000, type: 0} + m_ValidKeywords: [] + m_InvalidKeywords: [] + m_LightmapFlags: 5 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _MainTex: + m_Texture: {fileID: 2800000, guid: 02ca749bb835418ebe6506fa988f7211, type: 3} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Ints: [] + m_Floats: [] + m_Colors: + - _Color: {r: 0.82089555, g: 0.82089555, b: 0.82089555, a: 1} + m_BuildTextureStacks: [] --- !u!1 &517222967 GameObject: m_ObjectHideFlags: 0 @@ -524,6 +487,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1263153152} m_RootOrder: 5 @@ -560,7 +524,11 @@ MonoBehaviour: scale: 0 duration: 0 guide: 0 - mobilePopup: {fileID: 3804566942710620872, guid: ef93854362c847ec840d4c40eebc7d00, + _helpSelectionPopup: {fileID: 5322029663912086542, guid: ce6c1efdd8b1ca34aab20e8018664f11, + type: 3} + _helpPopup: {fileID: 147589561333268519, guid: f40ed35d415dbbd4f95c68ed95fdaadc, + type: 3} + _mobilePopup: {fileID: 3804566942710620872, guid: ef93854362c847ec840d4c40eebc7d00, type: 3} --- !u!1 &545706608 GameObject: @@ -589,6 +557,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1263153152} m_RootOrder: 3 @@ -610,35 +579,6 @@ MonoBehaviour: type: 3} _prefabPointCloud: {fileID: 1854016325464908, guid: ce965175197f501409225de2ce2fd634, type: 3} ---- !u!21 &631359219 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: '--- EMPTY ---Material - - 67826' - m_Shader: {fileID: 10752, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: - m_LightmapFlags: 5 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _MainTex: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: [] - m_Colors: - - _Color: {r: 0.82089555, g: 0.82089555, b: 0.82089555, a: 1} - m_BuildTextureStacks: [] --- !u!4 &636839176 stripped Transform: m_CorrespondingSourceObject: {fileID: 6061520891645277162, guid: b20febc21a242b143aa20ea181ba5e8e, @@ -684,40 +624,11 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 0} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!1 &721333826 -GameObject: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - serializedVersion: 6 - m_Component: - - component: {fileID: 721333827} - m_Layer: 0 - m_Name: Origin - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!4 &721333827 -Transform: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 721333826} - m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} - m_LocalPosition: {x: 0, y: 0, z: 0} - m_LocalScale: {x: 0.254, y: 0.254, z: 0.254} - m_Children: [] - m_Father: {fileID: 1006685207} - m_RootOrder: 0 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &802172366 GameObject: m_ObjectHideFlags: 0 @@ -745,6 +656,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 1263153152} m_RootOrder: 2 @@ -802,6 +714,7 @@ Transform: m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 967372975} m_RootOrder: 0 @@ -841,6 +754,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 7a21b486d0bb44444b1418aaa38b44de, type: 3} m_Name: m_EditorClassIdentifier: + m_SendPointerHoverToParent: 1 m_HorizontalAxis: Horizontal m_VerticalAxis: Vertical m_SubmitButton: Submit @@ -902,7 +816,7 @@ Camera: m_Depth: 0 m_CullingMask: serializedVersion: 2 - m_Bits: 4294967295 + m_Bits: 3221225471 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 @@ -957,6 +871,170 @@ MonoBehaviour: m_AutoFocus: 1 m_LightEstimation: 0 m_FacingDirection: 1 +--- !u!43 &857726593 +Mesh: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: ImageTargetMesh-379872 + serializedVersion: 10 + m_SubMeshes: + - serializedVersion: 2 + firstByte: 0 + indexCount: 6 + topology: 0 + baseVertex: 0 + firstVertex: 0 + vertexCount: 4 + localAABB: + m_Center: {x: 0, y: 0, z: 0} + m_Extent: {x: 0.1, y: 0, z: 0.1} + m_Shapes: + vertices: [] + shapes: [] + channels: [] + fullWeights: [] + m_BindPose: [] + m_BoneNameHashes: + m_RootBoneNameHash: 0 + m_BonesAABB: [] + m_VariableBoneCountWeights: + m_Data: + m_MeshCompression: 0 + m_IsReadable: 1 + m_KeepVertices: 1 + m_KeepIndices: 1 + m_IndexFormat: 0 + m_IndexBuffer: 000001000200020001000300 + m_VertexData: + serializedVersion: 3 + m_VertexCount: 4 + m_Channels: + - stream: 0 + offset: 0 + format: 0 + dimension: 3 + - stream: 0 + offset: 12 + format: 0 + dimension: 3 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 24 + format: 0 + dimension: 2 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + - stream: 0 + offset: 0 + format: 0 + dimension: 0 + m_DataSize: 128 + _typelessdata: cdccccbd00000000cdccccbd000000000000803f000000000000000000000000cdccccbd00000000cdcccc3d000000000000803f00000000000000000000803fcdcccc3d00000000cdccccbd000000000000803f000000000000803f00000000cdcccc3d00000000cdcccc3d000000000000803f000000000000803f0000803f + m_CompressedMesh: + m_Vertices: + m_NumItems: 0 + m_Range: 0 + m_Start: 0 + m_Data: + m_BitSize: 0 + m_UV: + m_NumItems: 0 + m_Range: 0 + m_Start: 0 + m_Data: + m_BitSize: 0 + m_Normals: + m_NumItems: 0 + m_Range: 0 + m_Start: 0 + m_Data: + m_BitSize: 0 + m_Tangents: + m_NumItems: 0 + m_Range: 0 + m_Start: 0 + m_Data: + m_BitSize: 0 + m_Weights: + m_NumItems: 0 + m_Data: + m_BitSize: 0 + m_NormalSigns: + m_NumItems: 0 + m_Data: + m_BitSize: 0 + m_TangentSigns: + m_NumItems: 0 + m_Data: + m_BitSize: 0 + m_FloatColors: + m_NumItems: 0 + m_Range: 0 + m_Start: 0 + m_Data: + m_BitSize: 0 + m_BoneIndices: + m_NumItems: 0 + m_Data: + m_BitSize: 0 + m_Triangles: + m_NumItems: 0 + m_Data: + m_BitSize: 0 + m_UVInfo: 0 + m_LocalAABB: + m_Center: {x: 0, y: 0, z: 0} + m_Extent: {x: 0.1, y: 0, z: 0.1} + m_MeshUsageFlags: 0 + m_BakedConvexCollisionMesh: + m_BakedTriangleCollisionMesh: + m_MeshMetrics[0]: 1 + m_MeshMetrics[1]: 1 + m_MeshOptimizationFlags: 1 + m_StreamData: + serializedVersion: 2 + offset: 0 + size: 0 + path: --- !u!1001 &967134324 PrefabInstance: m_ObjectHideFlags: 0 @@ -968,6 +1046,10 @@ PrefabInstance: propertyPath: m_Name value: WEKITCalibrationMarker objectReference: {fileID: 0} + - target: {fileID: 1284601556465576, guid: 177bff737c69d564ebb225d7fe7fc402, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} - target: {fileID: 4999640239509956, guid: 177bff737c69d564ebb225d7fe7fc402, type: 3} propertyPath: m_RootOrder value: 0 @@ -1016,12 +1098,17 @@ PrefabInstance: type: 3} propertyPath: m_Materials.Array.data[0] value: - objectReference: {fileID: 1475433919} + objectReference: {fileID: 398264897} - target: {fileID: 33609130599881980, guid: 177bff737c69d564ebb225d7fe7fc402, type: 3} propertyPath: m_Mesh value: - objectReference: {fileID: 2048530286} + objectReference: {fileID: 857726593} + - target: {fileID: 114264436370149114, guid: 177bff737c69d564ebb225d7fe7fc402, + type: 3} + propertyPath: StatusFilter + value: 0 + objectReference: {fileID: 0} - target: {fileID: 114557464381435048, guid: 177bff737c69d564ebb225d7fe7fc402, type: 3} propertyPath: mDataSetPath @@ -1032,6 +1119,11 @@ PrefabInstance: propertyPath: mTrackableName value: target objectReference: {fileID: 0} + - target: {fileID: 114557464381435048, guid: 177bff737c69d564ebb225d7fe7fc402, + type: 3} + propertyPath: mRuntimeTexture + value: + objectReference: {fileID: 2800000, guid: b463dcee3508044448742f24bf93043d, type: 3} - target: {fileID: 114557464381435048, guid: 177bff737c69d564ebb225d7fe7fc402, type: 3} propertyPath: mImageTargetType @@ -1092,6 +1184,11 @@ PrefabInstance: propertyPath: m_Volume value: 0.2 objectReference: {fileID: 0} + - target: {fileID: 2040808958413678622, guid: 177bff737c69d564ebb225d7fe7fc402, + type: 3} + propertyPath: m_LocalPosition.z + value: -0.01 + objectReference: {fileID: 0} - target: {fileID: 3151756932713657597, guid: 177bff737c69d564ebb225d7fe7fc402, type: 3} propertyPath: calibrationTool @@ -1125,6 +1222,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: - {fileID: 807537238} m_Father: {fileID: 0} @@ -1170,170 +1268,11 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!1 &1006685206 -GameObject: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - serializedVersion: 6 - m_Component: - - component: {fileID: 1006685207} - - component: {fileID: 1006685213} - - component: {fileID: 1006685212} - - component: {fileID: 1006685211} - - component: {fileID: 1006685210} - - component: {fileID: 1006685209} - - component: {fileID: 1006685208} - m_Layer: 0 - m_Name: WEKIT-Mark01 - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 0 ---- !u!4 &1006685207 -Transform: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} - m_LocalPosition: {x: 0, y: 0, z: 0} - m_LocalScale: {x: 1, y: 1, z: 1} - m_Children: - - {fileID: 721333827} - - {fileID: 507532543} - m_Father: {fileID: 101878640} - m_RootOrder: 1 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!114 &1006685208 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 1e7d692f8ba9e4b2b81f1aea733dfd04, type: 3} - m_Name: - m_EditorClassIdentifier: - IsWorking: 0 - IsLocated: 0 - IsDetected: 0 - IsActive: 0 - ExtendedTrackingActive: 1 - Type: 0 - Style: 0 - AttachedObject: {fileID: 0} - Radius: 1.5 - Tolerance: 0.01 ---- !u!33 &1006685209 -MeshFilter: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_Mesh: {fileID: 1900588746} ---- !u!23 &1006685210 -MeshRenderer: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_Enabled: 1 - m_CastShadows: 1 - m_ReceiveShadows: 1 - m_DynamicOccludee: 1 - m_MotionVectors: 1 - m_LightProbeUsage: 0 - m_ReflectionProbeUsage: 1 - m_RayTracingMode: 2 - m_RayTraceProcedural: 0 - m_RenderingLayerMask: 1 - m_RendererPriority: 0 - m_Materials: - - {fileID: 631359219} - m_StaticBatchInfo: - firstSubMesh: 0 - subMeshCount: 0 - m_StaticBatchRoot: {fileID: 0} - m_ProbeAnchor: {fileID: 0} - m_LightProbeVolumeOverride: {fileID: 0} - m_ScaleInLightmap: 1 - m_ReceiveGI: 1 - m_PreserveUVs: 0 - m_IgnoreNormalsForChartDetection: 0 - m_ImportantGI: 0 - m_StitchLightmapSeams: 0 - m_SelectedEditorRenderState: 3 - m_MinimumChartSize: 4 - m_AutoUVMaxDistance: 0.5 - m_AutoUVMaxAngle: 89 - m_LightmapParameters: {fileID: 0} - m_SortingLayerID: 0 - m_SortingLayer: 0 - m_SortingOrder: 0 - m_AdditionalVertexStreams: {fileID: 0} ---- !u!114 &1006685211 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: -1770992566, guid: bab6fa851cf5a1a4bba3cec5f191cb8e, type: 3} - m_Name: - m_EditorClassIdentifier: ---- !u!114 &1006685212 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 5a917f0af64a6423093132dab321c15f, type: 3} - m_Name: - m_EditorClassIdentifier: - StatusFilter: 2 - OnTargetFound: - m_PersistentCalls: - m_Calls: [] - OnTargetLost: - m_PersistentCalls: - m_Calls: [] ---- !u!114 &1006685213 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1006685206} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: -1631628248, guid: bab6fa851cf5a1a4bba3cec5f191cb8e, type: 3} - m_Name: - m_EditorClassIdentifier: - mTrackableName: WEKITCalibrationTool - mInitializedInEditor: 1 - mDataSetPath: Vuforia/WEKITCalibration.xml - mAspectRatio: 1 - mImageTargetType: 0 - mWidth: 0.15 - mHeight: 0.15 - mRuntimeTexture: {fileID: 0} --- !u!1 &1263153151 GameObject: m_ObjectHideFlags: 0 @@ -1361,6 +1300,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 599.0402, y: 309.4788, z: -180.98132} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: - {fileID: 317438514} - {fileID: 1980728072} @@ -1423,6 +1363,7 @@ Transform: m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 1.5} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 0} m_RootOrder: 5 @@ -1443,35 +1384,6 @@ MonoBehaviour: serializedVersion: 2 m_Bits: 2147483648 offset: 0.015 ---- !u!21 &1475433919 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: 'targetMaterial - - -10872' - m_Shader: {fileID: 10752, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: - m_LightmapFlags: 5 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _MainTex: - m_Texture: {fileID: 2800000, guid: 02ca749bb835418ebe6506fa988f7211, type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: [] - m_Colors: - - _Color: {r: 0.82089555, g: 0.82089555, b: 0.82089555, a: 1} - m_BuildTextureStacks: [] --- !u!1 &1694069694 GameObject: m_ObjectHideFlags: 0 @@ -1499,6 +1411,7 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: - {fileID: 206} - {fileID: 260875357} @@ -1558,174 +1471,11 @@ Transform: m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 0} m_RootOrder: 7 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!43 &1900588746 -Mesh: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: ImageTargetMesh67812 - serializedVersion: 10 - m_SubMeshes: - - serializedVersion: 2 - firstByte: 0 - indexCount: 6 - topology: 0 - baseVertex: 0 - firstVertex: 0 - vertexCount: 4 - localAABB: - m_Center: {x: 0, y: 0, z: 0} - m_Extent: {x: 0.075, y: 0, z: 0.075} - m_Shapes: - vertices: [] - shapes: [] - channels: [] - fullWeights: [] - m_BindPose: [] - m_BoneNameHashes: - m_RootBoneNameHash: 0 - m_BonesAABB: [] - m_VariableBoneCountWeights: - m_Data: - m_MeshCompression: 0 - m_IsReadable: 1 - m_KeepVertices: 1 - m_KeepIndices: 1 - m_IndexFormat: 0 - m_IndexBuffer: 000001000200020001000300 - m_VertexData: - serializedVersion: 3 - m_VertexCount: 4 - m_Channels: - - stream: 0 - offset: 0 - format: 0 - dimension: 3 - - stream: 0 - offset: 12 - format: 0 - dimension: 3 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 24 - format: 0 - dimension: 2 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - m_DataSize: 128 - _typelessdata: 9a9999bd000000009a9999bd000000000000803f0000000000000000000000009a9999bd000000009a99993d000000000000803f00000000000000000000803f9a99993d000000009a9999bd000000000000803f000000000000803f000000009a99993d000000009a99993d000000000000803f000000000000803f0000803f - m_CompressedMesh: - m_Vertices: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_UV: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_Normals: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_Tangents: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_Weights: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_NormalSigns: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_TangentSigns: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_FloatColors: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_BoneIndices: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_Triangles: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_UVInfo: 0 - m_LocalAABB: - m_Center: {x: 0, y: 0, z: 0} - m_Extent: {x: 0.075, y: 0, z: 0.075} - m_MeshUsageFlags: 0 - m_BakedConvexCollisionMesh: - m_BakedTriangleCollisionMesh: - m_MeshMetrics[0]: 1 - m_MeshMetrics[1]: 1 - m_MeshOptimizationFlags: 1 - m_StreamData: - serializedVersion: 2 - offset: 0 - size: 0 - path: --- !u!1001 &1901844725 PrefabInstance: m_ObjectHideFlags: 0 @@ -1813,170 +1563,6 @@ Transform: type: 3} m_PrefabInstance: {fileID: 967134324} m_PrefabAsset: {fileID: 0} ---- !u!43 &2048530286 -Mesh: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: ImageTargetMesh-29822 - serializedVersion: 10 - m_SubMeshes: - - serializedVersion: 2 - firstByte: 0 - indexCount: 6 - topology: 0 - baseVertex: 0 - firstVertex: 0 - vertexCount: 4 - localAABB: - m_Center: {x: 0, y: 0, z: 0} - m_Extent: {x: 0.1, y: 0, z: 0.1} - m_Shapes: - vertices: [] - shapes: [] - channels: [] - fullWeights: [] - m_BindPose: [] - m_BoneNameHashes: - m_RootBoneNameHash: 0 - m_BonesAABB: [] - m_VariableBoneCountWeights: - m_Data: - m_MeshCompression: 0 - m_IsReadable: 1 - m_KeepVertices: 1 - m_KeepIndices: 1 - m_IndexFormat: 0 - m_IndexBuffer: 000001000200020001000300 - m_VertexData: - serializedVersion: 3 - m_VertexCount: 4 - m_Channels: - - stream: 0 - offset: 0 - format: 0 - dimension: 3 - - stream: 0 - offset: 12 - format: 0 - dimension: 3 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 24 - format: 0 - dimension: 2 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - - stream: 0 - offset: 0 - format: 0 - dimension: 0 - m_DataSize: 128 - _typelessdata: cdccccbd00000000cdccccbd000000000000803f000000000000000000000000cdccccbd00000000cdcccc3d000000000000803f00000000000000000000803fcdcccc3d00000000cdccccbd000000000000803f000000000000803f00000000cdcccc3d00000000cdcccc3d000000000000803f000000000000803f0000803f - m_CompressedMesh: - m_Vertices: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_UV: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_Normals: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_Tangents: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_Weights: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_NormalSigns: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_TangentSigns: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_FloatColors: - m_NumItems: 0 - m_Range: 0 - m_Start: 0 - m_Data: - m_BitSize: 0 - m_BoneIndices: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_Triangles: - m_NumItems: 0 - m_Data: - m_BitSize: 0 - m_UVInfo: 0 - m_LocalAABB: - m_Center: {x: 0, y: 0, z: 0} - m_Extent: {x: 0.1, y: 0, z: 0.1} - m_MeshUsageFlags: 0 - m_BakedConvexCollisionMesh: - m_BakedTriangleCollisionMesh: - m_MeshMetrics[0]: 1 - m_MeshMetrics[1]: 1 - m_MeshOptimizationFlags: 1 - m_StreamData: - serializedVersion: 2 - offset: 0 - size: 0 - path: --- !u!1001 &1823839886190816814 PrefabInstance: m_ObjectHideFlags: 0 @@ -2113,15 +1699,5 @@ PrefabInstance: propertyPath: m_Name value: PlatformManager objectReference: {fileID: 0} - - target: {fileID: 8856608566303270429, guid: 380bb3c2508c4473aec1d2fcb48cce6f, - type: 3} - propertyPath: forceWorldSpaceUi - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8856608566303270429, guid: 380bb3c2508c4473aec1d2fcb48cce6f, - type: 3} - propertyPath: _worldSpaceObjects.Array.data[0].pathToLoad - value: - objectReference: {fileID: 1694069695} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: 380bb3c2508c4473aec1d2fcb48cce6f, type: 3} diff --git a/Assets/MirageXR/Common/Scenes/StartSettings.lighting b/Assets/MirageXR/Common/Scenes/StartSettings.lighting index 70fdc21cd..99197c138 100644 --- a/Assets/MirageXR/Common/Scenes/StartSettings.lighting +++ b/Assets/MirageXR/Common/Scenes/StartSettings.lighting @@ -7,7 +7,7 @@ LightingSettings: m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_Name: StartSettings - serializedVersion: 3 + serializedVersion: 4 m_GIWorkflowMode: 1 m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 @@ -20,7 +20,7 @@ LightingSettings: m_LightmapMaxSize: 1024 m_BakeResolution: 40 m_Padding: 2 - m_TextureCompression: 1 + m_LightmapCompression: 2 m_AO: 0 m_AOMaxDistance: 1 m_CompAOExponent: 1 @@ -61,3 +61,4 @@ LightingSettings: m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 + m_PVRTiledBaking: 0 diff --git a/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCard.cs b/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCard.cs index 1993c9571..0a2caf0c9 100644 --- a/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCard.cs +++ b/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCard.cs @@ -17,7 +17,7 @@ public class ActivityCard : MonoBehaviour // Instruction text. private Text _instruction; - + // Incompleted icon. private GameObject _incompletedIcon; @@ -141,7 +141,7 @@ public void SetupCard(Action action) // Then start filling crap in. _title.text = action.instruction.title; _instruction.text = action.instruction.description; - + _completedIcon.SetActive(action.isCompleted); _incompletedIcon.SetActive(!action.isCompleted); @@ -208,7 +208,7 @@ public void Next(string trigger) } break; } - } + } } public void NextTouch(string trigger) @@ -245,7 +245,7 @@ private void Previous(string trigger) public void ClickActionTouch() { - // Show next card when active card is clicked + // Show next card when active card is clicked if (IsActiveStep && ClickBehaviour == ClickBehaviours.Next) { EventManager.Next("touch"); diff --git a/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCardManager.cs b/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCardManager.cs index 66b1d60bd..019d15fd2 100644 --- a/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCardManager.cs +++ b/Assets/MirageXR/Common/Scripts/ActivityCard/ActivityCardManager.cs @@ -42,7 +42,7 @@ private void Reset() FinishFlag.SetActive(false); ReplayButton.SetActive(false); - + _timelineObjects.Clear(); _tasklistObjects.Clear(); OriginalActions.Clear(); @@ -84,16 +84,16 @@ private void Init() continue; } - var timelineItemPrefab = Resources.Load("Prefabs/TimelineItemPrefab");//TODO: change to addressables + var timelineItemPrefab = Resources.Load("Prefabs/TimelineItemPrefab"); // TODO: change to addressables var timelineObject = Instantiate(timelineItemPrefab, Vector3.zero, Quaternion.identity, TimeLine); - var timelineRectTransform = timelineObject.GetComponent(); + var timelineRectTransform = timelineObject.GetComponent(); timelineRectTransform.localPosition = Vector3.zero; timelineRectTransform.localEulerAngles = Vector3.zero; timelineRectTransform.localScale = Vector3.one; timelineObject.name = $"Step-{action.id}"; _timelineObjects.Add(timelineObject); - var taskStepPrefab = Resources.Load("Prefabs/UI/TaskStepPrefab"); //TODO: change to addressables + var taskStepPrefab = Resources.Load("Prefabs/UI/TaskStepPrefab"); // TODO: change to addressables var taskListObject = Instantiate(taskStepPrefab, Vector3.zero, Quaternion.identity, Tasklist); var taskListRectTransform = taskListObject.GetComponent(); taskListRectTransform.localPosition = Vector3.zero; @@ -129,7 +129,7 @@ public async void Next() actionObject.isCompleted = true; await RootObject.Instance.activityManager.DeactivateAction(actionObject.id); } - + /// /// Force activate previous action. /// @@ -139,7 +139,7 @@ public void Previous() } private void ShowCards() - { + { if (Actions.Count > 1) { NextCard.SetActive(true); diff --git a/Assets/MirageXR/Common/Scripts/ActivityCard/ActivitySelectionMenu.cs b/Assets/MirageXR/Common/Scripts/ActivityCard/ActivitySelectionMenu.cs index 515aa1660..f21d02562 100644 --- a/Assets/MirageXR/Common/Scripts/ActivityCard/ActivitySelectionMenu.cs +++ b/Assets/MirageXR/Common/Scripts/ActivityCard/ActivitySelectionMenu.cs @@ -26,7 +26,7 @@ private void Start() GetComponent().enabled = false; return; } - + EventManager.OnShowActivitySelectionMenu += ShowMenu; EventManager.OnHideActivitySelectionMenu += HideMenu; EventManager.OnEditorLoaded += HideMenu; @@ -94,7 +94,7 @@ public async void OpenRecorder() Loading.Instance.LoadingVisibility(true); await RootObject.Instance.editorSceneService.LoadEditorAsync(); - RootObject.Instance.activityManager.CreateNewActivity(); + await RootObject.Instance.activityManager.CreateNewActivity(); } } } \ No newline at end of file diff --git a/Assets/MirageXR/Common/Scripts/AmbientLighting.cs b/Assets/MirageXR/Common/Scripts/AmbientLighting.cs index 4835750c1..9e8533135 100644 --- a/Assets/MirageXR/Common/Scripts/AmbientLighting.cs +++ b/Assets/MirageXR/Common/Scripts/AmbientLighting.cs @@ -4,7 +4,7 @@ namespace MirageXR { public class AmbientLighting : MonoBehaviour { - private readonly int numberOfLights = 4; + private readonly int _numberOfLights = 4; private async void Start() { @@ -23,17 +23,17 @@ private async void Start() if (PlatformManager.Instance.WorldSpaceUi) sun.GetComponent().shadows = LightShadows.None; - // create 4 point lights - for (int i = 0; i < numberOfLights; i++) + // create 4 point lights + for (int i = 0; i < _numberOfLights; i++) + { + Vector3 startPosition = transform.position + transform.forward * Random.Range(-5, 5) + transform.right * Random.Range(-5, 5); + var ambientLightPrefab = await ReferenceLoader.GetAssetReferenceAsync("AmbientLight"); + if (ambientLightPrefab != null) { - Vector3 startPosition = transform.position + transform.forward * Random.Range(-5, 5) + transform.right * Random.Range(-5, 5); - var ambientLightPrefab = await ReferenceLoader.GetAssetReferenceAsync("AmbientLight"); - if(ambientLightPrefab != null) - { - Instantiate(ambientLightPrefab, startPosition, Quaternion.identity, transform); - } - + Instantiate(ambientLightPrefab, startPosition, Quaternion.identity, transform); } + + } } } diff --git a/Assets/MirageXR/Common/Scripts/AppSelection/AppSelection.cs b/Assets/MirageXR/Common/Scripts/AppSelection/AppSelection.cs index 7265dc677..b4ff38851 100644 --- a/Assets/MirageXR/Common/Scripts/AppSelection/AppSelection.cs +++ b/Assets/MirageXR/Common/Scripts/AppSelection/AppSelection.cs @@ -15,7 +15,7 @@ public class AppSelection : MonoBehaviour /// /// Start MirageXR Recorder /// - public void StartRecorder () + public void StartRecorder() { EventManager.Click(); SpatialMappingHelper.ActivateSpatialMapping(); @@ -26,7 +26,7 @@ public void StartRecorder () /// /// Start MirageXR Player /// - public void StartPlayer () + public void StartPlayer() { EventManager.Click(); SpatialMappingHelper.DeactivateSpatialMapping(); diff --git a/Assets/MirageXR/Common/Scripts/BoundingBoxGenerator.cs b/Assets/MirageXR/Common/Scripts/BoundingBoxGenerator.cs index 2d36c6f80..0f862ed73 100644 --- a/Assets/MirageXR/Common/Scripts/BoundingBoxGenerator.cs +++ b/Assets/MirageXR/Common/Scripts/BoundingBoxGenerator.cs @@ -26,6 +26,7 @@ public ScaleHandlesConfiguration CustomScaleHandlesConfiguration { get; set; } + public RotationHandlesConfiguration CustomRotationHandlesConfiguration { get; set; @@ -55,9 +56,14 @@ private void Start() /// /// /// - /// - public async Task AddBoundingBox(ToggleObject annotationToggleObject, BoundsCalculationMethod boundsCalculationMethod, bool hasConstraintManager = false, - bool addListeners = true, BoundingRotationType boundingRotationType = BoundingRotationType.ALL, bool AddManipulator = false) + /// Task object for asynchronous execution + public async Task AddBoundingBox( + ToggleObject annotationToggleObject, + BoundsCalculationMethod boundsCalculationMethod, + bool hasConstraintManager = false, + bool addListeners = true, + BoundingRotationType boundingRotationType = BoundingRotationType.ALL, + bool AddManipulator = false) { if (!hasConstraintManager && !GetComponent()) { @@ -87,9 +93,9 @@ public async Task AddBoundingBox(ToggleObject annotationToggleObject, BoundsCalc } var minMaxScaleConstraint = GetComponent(); - if(!minMaxScaleConstraint) + if (!minMaxScaleConstraint) { - minMaxScaleConstraint = gameObject.AddComponent(); //TODO: looks useless + minMaxScaleConstraint = gameObject.AddComponent(); // TODO: looks useless } if (boundsControl != null && boundingRotationType != BoundingRotationType.ALL) @@ -173,7 +179,7 @@ private IEnumerator ManipulationEvents(ToggleObject annotation) objectManipulator.TwoHandedManipulationType = Microsoft.MixedReality.Toolkit.Utilities.TransformFlags.Move; objectManipulator.OnManipulationEnded.AddListener(arg => SaveTransform(annotation)); - + EditModeState(RootObject.Instance.activityManager.EditModeActive); } diff --git a/Assets/MirageXR/Common/Scripts/CalibrationTool.cs b/Assets/MirageXR/Common/Scripts/CalibrationTool.cs index 9153dffa3..b86bbcb08 100644 --- a/Assets/MirageXR/Common/Scripts/CalibrationTool.cs +++ b/Assets/MirageXR/Common/Scripts/CalibrationTool.cs @@ -1,59 +1,151 @@ -using UnityEngine; +using System.Collections; +using UnityEngine; +using UnityEngine.Events; +using Vuforia; namespace MirageXR { public class CalibrationTool : MonoBehaviour { - [SerializeField] private GameObject CalibrationModel; + private static float ANIMATION_TIME = 5f; public static CalibrationTool Instance { get; private set; } - public void SetCalibrationModel(GameObject calibrationModel) + [SerializeField] private CalibrationAnimation _calibrationAnimation; + [SerializeField] private ImageTargetBehaviour _imageTargetBehaviour; + [SerializeField] private DefaultTrackableEventHandler _trackableEventHandler; + private UnityEvent _onTargetFound = new UnityEvent(); + private UnityEvent _onTargetLost = new UnityEvent(); + private UnityEvent _onCalibrationFinished = new UnityEvent(); + + public UnityEvent onTargetFound => _onTargetFound; + + public UnityEvent onTargetLost => _onTargetLost; + + public UnityEvent onCalibrationFinished => _onCalibrationFinished; + + public float animationTime => ANIMATION_TIME; + + public bool isEnabled { - CalibrationModel = calibrationModel; + get => _isEnabled; + set + { + _isEnabled = value; + SetEnabled(value); + } } + private bool _isEnabled; + private bool _isTargetFound; + private Coroutine _countdownToEnd; + public bool isNewPosition; + private void Awake() { if (Instance == null) + { Instance = this; + } else if (Instance != this) + { Destroy(gameObject); + } } - private void Start() { - Reset(); + _trackableEventHandler.OnTargetFound.AddListener(OnTargetFound); + _trackableEventHandler.OnTargetLost.AddListener(OnTargetLost); + isEnabled = false; } - public void SetPlayer() + private void SetEnabled(bool value) { - if (CalibrationModel) + if (value) { - CalibrationModel.SetActive(true); + Enable(); } + else + { + Disable(); + } + } + + private void OnTargetFound() + { + _isTargetFound = true; + _onTargetFound.Invoke(); + _calibrationAnimation.PlayAnimation(); + _countdownToEnd = StartCoroutine(WaitAndDo(ANIMATION_TIME, Calibrate)); } - public void Reset() + private void OnTargetLost() { - if (CalibrationModel) + _isTargetFound = false; + _onTargetLost.Invoke(); + _calibrationAnimation.StopAnimation(); + if (_countdownToEnd != null) { - CalibrationModel.SetActive(false); + StopCoroutine(_countdownToEnd); + _countdownToEnd = null; } } - /// - /// Calibrate workplace model anchors. - /// + private void Enable() + { + _isEnabled = true; + + if (_countdownToEnd != null) + { + StopCoroutine(_countdownToEnd); + _countdownToEnd = null; + } + + if (_imageTargetBehaviour != null && _calibrationAnimation != null) + { + _imageTargetBehaviour.enabled = true; + _calibrationAnimation.gameObject.SetActive(true); + } + } + + private void Disable() + { + _isTargetFound = false; + + if (_countdownToEnd != null) + { + StopCoroutine(_countdownToEnd); + _countdownToEnd = null; + } + + _calibrationAnimation.StopAnimation(); + _imageTargetBehaviour.enabled = false; + _calibrationAnimation.gameObject.SetActive(false); + } + public async void Calibrate() { - // Calibrate only if the marker is visible. - if (CalibrationModel.activeInHierarchy) + _calibrationAnimation.StopAnimation(); + if (_isTargetFound) + { + await RootObject.Instance.workplaceManager.CalibrateWorkplace(transform, isNewPosition); + _onCalibrationFinished.Invoke(); + } + + if (_countdownToEnd != null) { - EventManager.Click(); - await RootObject.Instance.workplaceManager.CalibrateWorkplace(transform); + StopCoroutine(_countdownToEnd); + _countdownToEnd = null; } + + isEnabled = false; + } + + private static IEnumerator WaitAndDo(float time, System.Action callback) + { + yield return new WaitForSeconds(time); + callback?.Invoke(); } } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/ActionDetailView.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/ActionDetailView.cs index 115d866d1..ffc6bdc0b 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/ActionDetailView.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/ActionDetailView.cs @@ -17,7 +17,7 @@ public class ActionDetailView : MonoBehaviour [SerializeField] private Transform poiPredicatesParent; [SerializeField] private GameObject poiPredicateItemPrefab; - private Action displayedAction; + private Action _displayedAction; private readonly List poiPredicateItems = new List(); private ActionEditor editor; @@ -26,11 +26,11 @@ public Action DisplayedAction { get { - return displayedAction; + return _displayedAction; } set { - displayedAction = value; + _displayedAction = value; UpdateUI(); } } @@ -89,7 +89,7 @@ public GameObject GetCurrentTaskStation() var place = GameObject.Find(actionId); if (place) { - var taskStation = place.transform.Find("default/PlayerTaskStation(Clone)"); //TODO: possible NRE + var taskStation = place.transform.Find("default/PlayerTaskStation(Clone)"); // TODO: possible NRE if (taskStation) return taskStation.gameObject; } @@ -101,10 +101,10 @@ public void UpdateUI() // If all action steps are deleted and only the last one exist, add it to displayedAction if (activityManager.ActionsOfTypeAction.Count == 1) { - displayedAction = activityManager.ActionsOfTypeAction[0]; + _displayedAction = activityManager.ActionsOfTypeAction[0]; } - if (displayedAction == null) + if (_displayedAction == null) { titleLabel.text = string.Empty; descriptionText.text = string.Empty; @@ -124,18 +124,18 @@ public void UpdateUI() numberLabel.text = (index + 1).ToString("00"); // fill or create all necessary item labels - for (int i = 0; i < displayedAction.enter.activates.Count; i++) + for (int i = 0; i < _displayedAction.enter.activates.Count; i++) { if (i < poiPredicateItems.Count) { poiPredicateItems[i].gameObject.SetActive(true); - poiPredicateItems[i].SetUp(this, displayedAction.enter.activates[i]); + poiPredicateItems[i].SetUp(this, _displayedAction.enter.activates[i]); } else { var poiItemInstance = Instantiate(poiPredicateItemPrefab, poiPredicatesParent); var poiListItem = poiItemInstance.GetComponent(); - poiListItem.SetUp(this, displayedAction.enter.activates[i]); + poiListItem.SetUp(this, _displayedAction.enter.activates[i]); poiListItem.OnAnnotationItemClicked += OnAnnotationSelected; poiPredicateItems.Add(poiListItem); } @@ -145,7 +145,7 @@ public void UpdateUI() ActionEditor.Instance.AddMenuVisible = !activityManager.ActiveAction.enter.activates.Any(); // disable all unused item labels - for (int i = displayedAction.enter.activates.Count; i < poiPredicateItems.Count; i++) + for (int i = _displayedAction.enter.activates.Count; i < poiPredicateItems.Count; i++) { poiPredicateItems[i].gameObject.SetActive(false); } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/AudioEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/AudioEditor.cs index e47683869..1976cd074 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/AudioEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/AudioEditor.cs @@ -25,14 +25,14 @@ public class AudioEditor : MonoBehaviour [SerializeField] private Toggle loop; [SerializeField] private Toggle stepTrigger; - private Action action; - private ToggleObject annotationToEdit; + private Action _action; + private ToggleObject _annotationToEdit; - private AudioClip capturedClip; + private AudioClip _capturedClip; - private bool isRecording; - private bool isPaused; - private int timerSeconds = 0; + private bool _isRecording; + private bool _isPaused; + private int _timerSeconds = 0; public AudioSource PlayerAudioSource => audioSource; @@ -46,12 +46,12 @@ public DialogRecorder DialogRecorderPanel public bool IsRecording { - get => isRecording; + get => _isRecording; private set { - isRecording = value; - timerIcon.enabled = isRecording; // recorder circle shows only on recording - startRecordingButton.interactable = !isRecording; + _isRecording = value; + timerIcon.enabled = _isRecording; // recorder circle shows only on recording + startRecordingButton.interactable = !_isRecording; } } @@ -63,7 +63,7 @@ public bool IsPlaying public AudioClip CapturedClip() { - return capturedClip; + return _capturedClip; } @@ -76,23 +76,23 @@ private void Update() { if (!gameObject) return; - if (gameObject.activeInHierarchy && !isRecording && IsPlaying) + if (gameObject.activeInHierarchy && !_isRecording && IsPlaying) { progress.value = audioSource.time / audioSource.clip.length; UpdatePlayBackTimer(); } - else - timerText.text = SecToTimeFormat(timerSeconds); + else + timerText.text = SecToTimeFormat(_timerSeconds); } private IEnumerator Timer() { - timerSeconds = 0; + _timerSeconds = 0; - while (isRecording) + while (_isRecording) { yield return new WaitForSeconds(1); - timerSeconds++; + _timerSeconds++; } } @@ -100,10 +100,10 @@ private void UpdateUI() { if (!gameObject) return; - stopRecordingButton.interactable = IsPlaying || isRecording; - pauseButton.gameObject.SetActive(!isPaused && IsPlaying); + stopRecordingButton.interactable = IsPlaying || _isRecording; + pauseButton.gameObject.SetActive(!_isPaused && IsPlaying); playButton.interactable = !IsRecording; - progress.gameObject.SetActive(!isRecording && capturedClip); + progress.gameObject.SetActive(!_isRecording && _capturedClip); timerText.enabled = !progress.gameObject.activeInHierarchy; } @@ -124,10 +124,10 @@ private static string SecToTimeFormat(int seconds) public void Close() { // when editor is closed play the spatial audio if it is exist - if (annotationToEdit != null) + if (_annotationToEdit != null) { - var audioPlayer = GameObject.Find(annotationToEdit.poi).GetComponentInChildren(); - if (annotationToEdit != null && audioPlayer != null) + var audioPlayer = GameObject.Find(_annotationToEdit.poi).GetComponentInChildren(); + if (_annotationToEdit != null && audioPlayer != null) { audioPlayer.PlayAudio(); } @@ -135,9 +135,9 @@ public void Close() StopRecording(); - action = null; - annotationToEdit = null; - capturedClip = null; + _action = null; + _annotationToEdit = null; + _capturedClip = null; SaveFileName = string.Empty; IsPlaying = false; @@ -152,10 +152,10 @@ public void Close() public void Open(Action action, ToggleObject annotation) { gameObject.SetActive(true); - this.action = action; - annotationToEdit = annotation; + this._action = action; + _annotationToEdit = annotation; IsRecording = false; - timerSeconds = 0; + _timerSeconds = 0; audiotype.isOn = false; foreach (var foundAudioSource in FindObjectsOfType()) @@ -166,22 +166,22 @@ public void Open(Action action, ToggleObject annotation) audioSource = GameObject.Find(annotation.id).GetComponentInChildren(); } - if (annotationToEdit != null) + if (_annotationToEdit != null) { - SaveFileName = annotationToEdit.url; - - capturedClip = SaveLoadAudioUtilities.LoadAudioFile(GetExistingAudioFile()); + SaveFileName = _annotationToEdit.url; + + _capturedClip = SaveLoadAudioUtilities.LoadAudioFile(GetExistingAudioFile()); - if (annotationToEdit.option.Contains("3d")) + if (_annotationToEdit.option.Contains("3d")) { audiotype.isOn = true; - loop.isOn = annotationToEdit.option.Split('#')[1] == "1"; - radius.text = annotationToEdit.option.Split('#')[2]; + loop.isOn = _annotationToEdit.option.Split('#')[1] == "1"; + radius.text = _annotationToEdit.option.Split('#')[2]; OnAudioTypeToggle(); } // check if the trigger for this audio is on - stepTrigger.isOn = activityManager.ActiveAction.triggers.Find(t => t.id == annotationToEdit.poi) != null; + stepTrigger.isOn = activityManager.ActiveAction.triggers.Find(t => t.id == _annotationToEdit.poi) != null; // re-recording is not allowed startRecordingButton.interactable = false; @@ -202,16 +202,16 @@ public void PlayAudio() public void PlayAudioFileAt(float slideValue = 0) { - if (isPaused) + if (_isPaused) { audioSource.Play(); - isPaused = false; + _isPaused = false; } else { - if (capturedClip != null ) + if (_capturedClip != null) { - audioSource.clip = capturedClip; + audioSource.clip = _capturedClip; audioSource.time = slideValue; audioSource.Play(); IsPlaying = true; @@ -225,11 +225,11 @@ private void OnTriggerValueChanged() { loop.interactable = audiotype.isOn && !stepTrigger.isOn; - //disable loop if trigger is active + // disable loop if trigger is active if (stepTrigger.isOn) loop.isOn = false; if (stepTrigger.isOn && - activityManager.ActionsOfTypeAction.IndexOf(action) == activityManager.ActionsOfTypeAction.Count - 1) + activityManager.ActionsOfTypeAction.IndexOf(_action) == activityManager.ActionsOfTypeAction.Count - 1) { // give the info and close DialogWindow.Instance.Show("Info!", @@ -244,28 +244,28 @@ private void SaveTriggerValue() { if (stepTrigger.isOn) { - if (annotationToEdit == null) return; - action.AddOrReplaceArlemTrigger(TriggerMode.Audio, ActionType.Audio, annotationToEdit.poi, audioSource.clip.length, string.Empty); + if (_annotationToEdit == null) return; + _action.AddOrReplaceArlemTrigger(TriggerMode.Audio, ActionType.Audio, _annotationToEdit.poi, audioSource.clip.length, string.Empty); } else { - action.RemoveArlemTrigger(annotationToEdit); + _action.RemoveArlemTrigger(_annotationToEdit); } } public void Initialize(Action action) { - this.action = action; - annotationToEdit = null; + this._action = action; + _annotationToEdit = null; IsRecording = false; SaveFileName = string.Empty; } private string GetExistingAudioFile() { - var audioName = annotationToEdit.url; + var audioName = _annotationToEdit.url; const string httpPrefix = "http://"; - + string originalFileName = !audioName.StartsWith(httpPrefix) ? Path.Combine(Application.persistentDataPath, audioName) : Path.Combine(activityManager.ActivityPath, Path.GetFileName(audioName.Remove(0, httpPrefix.Length))); @@ -275,15 +275,15 @@ private string GetExistingAudioFile() // set the correct dialog recorder(correct character) to the audio player foreach (var character in FindObjectsOfType()) { - if (character.MyAction == action && character.DialogRecorder.DialogSaveName != string.Empty) + if (character.MyAction == _action && character.DialogRecorder.DialogSaveName != string.Empty) { SaveFileName = character.DialogRecorder.DialogSaveName; originalFilePath = Path.Combine(activityManager.ActivityPath, SaveFileName); - GameObject.Find(annotationToEdit.poi).GetComponentInChildren().DialogRecorderPanel = character.transform.GetChild(0).GetComponentInChildren(); //TODO: Possible NRE + GameObject.Find(_annotationToEdit.poi).GetComponentInChildren().DialogRecorderPanel = character.transform.GetChild(0).GetComponentInChildren(); // TODO: Possible NRE break; } } - + return originalFilePath; } @@ -302,23 +302,23 @@ private static void PlayAllLoopedVideo() public void OnAccept() { StopRecording(); - if (annotationToEdit != null) + if (_annotationToEdit != null) { // delete the previous audio file if a new file is recorded var originalFilePath = GetExistingAudioFile(); - if (File.Exists(originalFilePath) && SaveFileName != string.Empty && annotationToEdit.url == null) + if (File.Exists(originalFilePath) && SaveFileName != string.Empty && _annotationToEdit.url == null) { - EventManager.DeactivateObject(annotationToEdit); + EventManager.DeactivateObject(_annotationToEdit); File.Delete(originalFilePath); } // edit audio type , loop and radius as option - AudioOptionsAdjustment(annotationToEdit); + AudioOptionsAdjustment(_annotationToEdit); } else { var workplaceManager = RootObject.Instance.workplaceManager; - Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(action.id)); + Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(_action.id)); GameObject originT = GameObject.Find(detectable.id); // move the audio player to the spawn point @@ -328,24 +328,24 @@ public void OnAccept() annotationStartingPoint.transform.rotation, originT.transform.position, originT.transform.rotation); - - annotationToEdit = RootObject.Instance.augmentationManager.AddAugmentation(action, offset); - annotationToEdit.predicate = "audio"; - //save audio type , loop and radius as option - AudioOptionsAdjustment(annotationToEdit); + _annotationToEdit = RootObject.Instance.augmentationManager.AddAugmentation(_action, offset); + _annotationToEdit.predicate = "audio"; + + // save audio type , loop and radius as option + AudioOptionsAdjustment(_annotationToEdit); - annotationToEdit.scale = 0.5f; + _annotationToEdit.scale = 0.5f; } - if(SaveFileName != string.Empty ) + if (SaveFileName != string.Empty) { - annotationToEdit.url = $"http://{SaveFileName}"; + _annotationToEdit.url = $"http://{SaveFileName}"; - EventManager.ActivateObject(annotationToEdit); - EventManager.NotifyActionModified(action); + EventManager.ActivateObject(_annotationToEdit); + EventManager.NotifyActionModified(_action); - var player = GameObject.Find(annotationToEdit.poi).GetComponentInChildren(); + var player = GameObject.Find(_annotationToEdit.poi).GetComponentInChildren(); if (player != null) { player.DialogRecorderPanel = DialogRecorderPanel; @@ -359,7 +359,7 @@ public void OnAccept() private void AudioOptionsAdjustment(ToggleObject annotationToEdit) { - //save audio type , loop and radius as option + // save audio type , loop and radius as option if (!audiotype.isOn) annotationToEdit.option = "2d"; else @@ -405,13 +405,13 @@ public void StopRecording() IsPlaying = false; } - if (isRecording) + if (_isRecording) { - capturedClip = AudioRecorder.Stop(); + _capturedClip = AudioRecorder.Stop(); IsRecording = false; - audioSource.clip = capturedClip; + audioSource.clip = _capturedClip; UpdatePlayBackTimer(); SaveRecording(); @@ -428,12 +428,12 @@ private void SaveRecording() SaveFileName = SaveFileName.Remove(0, httpPrefix.Length); } string fullFilePath = Path.Combine(activityManager.ActivityPath, SaveFileName); - SaveLoadAudioUtilities.Save(fullFilePath, capturedClip); + SaveLoadAudioUtilities.Save(fullFilePath, _capturedClip); } public void PauseAudio() { - isPaused = true; + _isPaused = true; audioSource.Pause(); UpdateUI(); @@ -442,13 +442,13 @@ public void PauseAudio() private void ResetSlider() { IsPlaying = false; - isPaused = false; + _isPaused = false; UpdateUI(); } public void ChangeAudioTime() { - if (!audioSource.clip || isRecording || !gameObject.activeInHierarchy) return; + if (!audioSource.clip || _isRecording || !gameObject.activeInHierarchy) return; if (audioSource.clip.length * progress.value < audioSource.clip.length) { audioSource.time = audioSource.clip.length * progress.value; diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CharacterAugmentation.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CharacterAugmentation.cs index ff558e176..cd81f71f1 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CharacterAugmentation.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CharacterAugmentation.cs @@ -15,11 +15,11 @@ public class CharacterAugmentation : MonoBehaviour private const float _distanceFromGround = 0.6f; // Increase to move the character down private const float _defaultScaleFactor = 0.8f; - private Action action; - private ToggleObject annotationToEdit; + private Action _action; + private ToggleObject _annotationToEdit; - private GameObject character; - private string modelname; + private GameObject _character; + private string _modelname; private void Start() @@ -32,8 +32,8 @@ private void Start() public void SetMovementType() { - if (!character) return; - var characterController = character.GetComponent(); + if (!_character) return; + var characterController = _character.GetComponent(); characterController.MovementType = "followpath"; characterController.AgentReturnAtTheEnd = false; CreatePath(); @@ -45,62 +45,62 @@ private void CreatePath() var taskStationPosition = TaskStationDetailMenu.Instance.ActiveTaskStation.transform; var spawnPosition = taskStationPosition.position + taskStationPosition.transform.forward * _distanceToTaskSTation; // Behind the task station var des = Instantiate(pointCont, spawnPosition - Vector3.up * _distanceFromGround, Quaternion.identity); - des.transform.rotation *= Quaternion.Euler(0, 180 , 0); - des.GetComponent().MyCharacter = character.GetComponent(); - des.transform.SetParent(character.transform.parent); + des.transform.rotation *= Quaternion.Euler(0, 180, 0); + des.GetComponent().MyCharacter = _character.GetComponent(); + des.transform.SetParent(_character.transform.parent); destinations.Add(des); - // character.transform.position = des.transform.position + new Vector3(0.2f , 0, 0); - character.GetComponent().Destinations = destinations; + // character.transform.position = des.transform.position + new Vector3(0.2f , 0, 0); + _character.GetComponent().Destinations = destinations; - character.gameObject.transform.localScale *= _defaultScaleFactor; + _character.gameObject.transform.localScale *= _defaultScaleFactor; } private void CreateCharacter(string modelname) { - this.modelname = modelname; + this._modelname = modelname; Create(); } public async void Create() { - if (annotationToEdit != null) + if (_annotationToEdit != null) { - annotationToEdit.predicate = $"char:{modelname}"; - EventManager.DeactivateObject(annotationToEdit); + _annotationToEdit.predicate = $"char:{_modelname}"; + EventManager.DeactivateObject(_annotationToEdit); } else { var workplaceManager = RootObject.Instance.workplaceManager; - Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(action.id)); + Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(_action.id)); GameObject originT = GameObject.Find(detectable.id); - Vector3 spawnPosition = TaskStationDetailMenu.Instance.ActiveTaskStation.transform.position + Vector3.forward; + Vector3 spawnPosition = TaskStationDetailMenu.Instance.ActiveTaskStation.transform.position + Vector3.forward; Quaternion spawnRot = Quaternion.identity; Vector3 offset = Utilities.CalculateOffset(spawnPosition, spawnRot, originT.transform.position, originT.transform.rotation); - annotationToEdit = RootObject.Instance.augmentationManager.AddAugmentation(action, offset); - annotationToEdit.predicate = "char:" + modelname; + _annotationToEdit = RootObject.Instance.augmentationManager.AddAugmentation(_action, offset); + _annotationToEdit.predicate = "char:" + _modelname; } - EventManager.ActivateObject(annotationToEdit); - EventManager.NotifyActionModified(action); + EventManager.ActivateObject(_annotationToEdit); + EventManager.NotifyActionModified(_action); - var characterObjectName = $"{annotationToEdit.id}/{annotationToEdit.poi}/{annotationToEdit.predicate}"; + var characterObjectName = $"{_annotationToEdit.id}/{_annotationToEdit.poi}/{_annotationToEdit.predicate}"; - while (character == null) + while (_character == null) { - character = GameObject.Find(characterObjectName); + _character = GameObject.Find(characterObjectName); await Task.Delay(10); } SetMovementType(); - var characterController = character.GetComponent(); + var characterController = _character.GetComponent(); characterController.AudioEditorCheck(); - characterController.MyAction = action; + characterController.MyAction = _action; Close(); } @@ -108,8 +108,8 @@ public async void Create() public void Close() { gameObject.SetActive(false); - action = null; - annotationToEdit = null; + _action = null; + _annotationToEdit = null; Destroy(gameObject); } @@ -118,8 +118,8 @@ public void Open(Action action, ToggleObject annotation) { // character = myCharacter; gameObject.SetActive(true); - this.action = action; - annotationToEdit = annotation; + this._action = action; + _annotationToEdit = annotation; } } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CropHandeler.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CropHandeler.cs index 5cebf8946..221095904 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CropHandeler.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/CropHandeler.cs @@ -58,15 +58,16 @@ public void TakeScreenShot(int width, int height, string filePath) { screenShotName = filePath; myCamera.targetTexture = RenderTexture.GetTemporary(width, height, 16); - takeScreenShotOnNextFrame = true; + takeScreenShotOnNextFrame = true; } public static void TakeScreenshot_static(int width, int height, string filePath) { - instance.TakeScreenShot(width, height, filePath); + instance.TakeScreenShot(width, height, filePath); } - public Texture2D GetCropped() { + public Texture2D GetCropped() + { return RR; } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/DrawingEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/DrawingEditor.cs index 10fea0113..a8a5f11c6 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/DrawingEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/DrawingEditor.cs @@ -185,7 +185,8 @@ public void Open(Action action, ToggleObject annotation) tiltInstance = Instantiate(tiltPrefab); tiltInstance.SetViewOnly(true); } - else{ + else + { tiltInstance = Tiltbrush.Instance; } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhostRecorder.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhostRecorder.cs index 4ba885be0..ca9594e17 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhostRecorder.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhostRecorder.cs @@ -15,14 +15,14 @@ public class GhostRecorder public GhostDataFrame LastFrame => _lastFrame; private readonly List _ghostFrames = new List(); - + private GhostDataFrame _lastFrame; private CancellationTokenSource _cancellationTokenSource; private Transform _anchor; private Transform _cameraTransform; private int _cooldown; private bool _isRecording; - + /// /// Write the data in an .xml file and save it locally. /// @@ -41,7 +41,7 @@ public static void ExportToFile(string filePath, List ghostDataF Debug.Log($"saved ghost track file: {filePath}"); } - + /// /// Load the data from an .xml file /// @@ -50,7 +50,7 @@ public static void ExportToFile(string filePath, List ghostDataF public static bool TryLoadFromFile(string filePath, out List ghostDataFrames) { ghostDataFrames = null; - + if (!File.Exists(filePath)) return false; using (var file = File.Open(filePath, FileMode.Open)) @@ -62,7 +62,7 @@ public static bool TryLoadFromFile(string filePath, out List gho return ghostDataFrames != null && ghostDataFrames.Count != 0; } - + /// /// Start recording the position of the ghost /// @@ -73,7 +73,7 @@ public static bool TryLoadFromFile(string filePath, out List gho public void Start(Transform anchor, Transform camera, float? cooldown = null) { const int millisecondsInSecond = 1000; - + if (_isRecording) { throw new Exception("A new recording cannot be started because the previous one has not been completed."); @@ -83,16 +83,16 @@ public void Start(Transform anchor, Transform camera, float? cooldown = null) _cancellationTokenSource = new CancellationTokenSource(); _cameraTransform = camera; _anchor = anchor; - + _ghostFrames.Clear(); _isRecording = true; StartAsync(); } - + public List Stop() { - if (!_isRecording) + if (!_isRecording) { throw new Exception("The recording cannot be stopped because the recording has not been started."); } @@ -115,11 +115,11 @@ private async void StartAsync() catch (TaskCanceledException) { /*hide exception*/ } } } - + private void rec() { if (!_isRecording) return; - + var cameraRotation = _cameraTransform.rotation; var defaultRotation = Quaternion.Inverse(_anchor.localRotation) * cameraRotation; @@ -137,13 +137,13 @@ private void rec() var rotation = Quaternion.LookRotation(rightHandRay.direction, Vector3.up); _lastFrame.rightHand = CreateLocalPose(_anchor, rightHandRay.origin, rotation); } - + if (InputRayUtils.TryGetHandRay(Handedness.Left, out var leftHandRay)) { var rotation = Quaternion.LookRotation(leftHandRay.direction, Vector3.up); - _lastFrame.leftHand = CreateLocalPose(_anchor, leftHandRay.origin, rotation); + _lastFrame.leftHand = CreateLocalPose(_anchor, leftHandRay.origin, rotation); } - + _ghostFrames.Add(_lastFrame); } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhosttrackEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhosttrackEditor.cs index f66b22a7e..c3f645d18 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhosttrackEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/GhosttrackEditor.cs @@ -4,6 +4,10 @@ using UnityEngine; using UnityEngine.UI; +/// +/// Editor logic for creating a ghost track +/// The ghost track consists of a recording of an expert's movement and audio +/// public class GhosttrackEditor : MonoBehaviour { private static ActivityManager activityManager => RootObject.Instance.activityManager; @@ -30,16 +34,17 @@ public class GhosttrackEditor : MonoBehaviour private Transform _augOrigin; private Transform _cameraTransform; - + private Image _maleThumbnailSelectedIcon; private Image _femaleThumbnailSelectedIcon; - + private string _ghostFileName; private string _audioFileName; - + private readonly GhostRecorder _ghostRecorder = new GhostRecorder(); - + private bool _isRecording; + private bool IsRecording { get => _isRecording; @@ -51,9 +56,15 @@ private bool IsRecording } } + /// + /// Closes the ghost track editor + /// public void Close() { - if (_isRecording) StopRecording(); + if (_isRecording) + { + StopRecording(); + } _action = null; _annotationToEdit = null; gameObject.SetActive(false); @@ -76,7 +87,7 @@ public void OnAccept() Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(_action.id)); var originT = GameObject.Find(detectable.id); var offset = Utilities.CalculateOffset(_augOrigin.position, _augOrigin.rotation, originT.transform.position, originT.transform.rotation); - + StopRecording(); if (_annotationToEdit != null) { @@ -89,9 +100,9 @@ public void OnAccept() File.Delete(xmlPath); } // delete old audio annotation before creating a new one - activityManager.ActionsOfTypeAction.ForEach(a => - { - if (a.enter.activates.Contains(_annotationToEdit) && _annotationToEdit.option.Contains(":")) + activityManager.ActionsOfTypeAction.ForEach(a => + { + if (a.enter.activates.Contains(_annotationToEdit) && _annotationToEdit.option.Contains(":")) { var myAudioPoi = _annotationToEdit.option.Split(':')[1]; var myAudioToggleObject = a.enter.activates.Find(t => t.poi == myAudioPoi); @@ -102,10 +113,10 @@ public void OnAccept() myAudioToggleObject.url.Replace("http://", "")); File.Delete(audioFilePath); } - } + } }); - Debug.LogError(_annotationToEdit == null); + Debug.LogError(_annotationToEdit == null); } else { @@ -118,7 +129,7 @@ public void OnAccept() var ghostFilePath = Path.Combine(activityManager.ActivityPath, _ghostFileName); GhostRecorder.ExportToFile(ghostFilePath, _ghostFrames); - + var audioFilePath = Path.Combine(activityManager.ActivityPath, _audioFileName); SaveLoadAudioUtilities.Save(audioFilePath, _audioClip); @@ -151,17 +162,17 @@ public void OnAccept() EventManager.NotifyActionModified(_action); Close(); } - + private void Initialize() { _cameraTransform = Camera.main.transform; - + _maleThumbnailSelectedIcon = _maleButton.transform.GetChild(0).GetComponent(); _femaleThumbnailSelectedIcon = _femaleButton.transform.GetChild(0).GetComponent(); - + _maleButton.onClick.AddListener(OnMaleButtonClick); _femaleButton.onClick.AddListener(OnFemaleButtonClick); - + Debug.Log("GhostTrackAnnotation: warm up holosensors"); } @@ -200,7 +211,7 @@ private void SetPoint() Destroy(GameObject.Find("GhostOrigin")); _augOrigin = null; } - + _augOrigin = new GameObject("GhostOrigin").transform; _augOrigin.position = _cameraTransform.position; _augOrigin.rotation = GameObject.Find(_action.id).transform.rotation; @@ -238,10 +249,10 @@ public void StartRecording() SetPoint(); _augOrigin = GameObject.Find(_action.id).transform; // TODO: possible NRE. replace with direct ref - + var timeStamp = System.DateTime.Now.ToFileTimeUtc(); - _audioFileName = $"MirageXR_Audio_{timeStamp}.wav"; - + _audioFileName = $"MirageXR_Audio_{timeStamp}.wav"; + Debug.Log("GhostTrackAnnotation: send filename timestamp to audio: " + _ghostFileName); var previewPos = _cameraTransform.position + _cameraTransform.forward * 1.0f + _cameraTransform.right * 0.2f + _cameraTransform.up * 0.1f; @@ -250,10 +261,10 @@ public void StartRecording() _ghostPreviewTransform = _ghostPreview.transform; _ghostPreviewHeadTransform = _ghostPreviewTransform.Find("Head"); - + _ghostRecorder.Start(_augOrigin, _cameraTransform); AudioRecorder.Start(_audioFileName); - + IsRecording = true; } Debug.Log("GhostTrackAnnotation.StartRecording done"); @@ -278,7 +289,7 @@ public void StopRecording() _ghostFrames = _ghostRecorder.Stop(); _audioClip = AudioRecorder.Stop(); - + Maggie.Speak("Stopped recording ghost track"); Debug.Log("Stopped recording ghost track"); } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphEditor.cs index 76631fa41..c6f97741a 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphEditor.cs @@ -10,7 +10,7 @@ public class GlyphEditor : MonoBehaviour [SerializeField] private GlyphListItem _glyphListItemPrefab; [SerializeField] private ActionObject[] _actionObjects; - + private Transform _annotationStartingPoint; private Action _action; private ToggleObject _annotationToEdit; @@ -34,10 +34,10 @@ public void Open(Action action, ToggleObject annotation) gameObject.SetActive(true); _action = action; _annotationToEdit = annotation; - + GenerateActionList(); - if(_annotationToEdit != null) + if (_annotationToEdit != null) { var trigger = activityManager.ActiveAction.triggers.Find(t => t.id == _annotationToEdit.poi); var duration = trigger != null ? trigger.duration : 1; @@ -73,12 +73,13 @@ public void Create(string iconName) _annotationStartingPoint.transform.rotation, originT.transform.position, originT.transform.rotation); - + _annotationToEdit = RootObject.Instance.augmentationManager.AddAugmentation(_action, offset); } // change predicate on all steps - activityManager.ActionsOfTypeAction.ForEach(a => { + activityManager.ActionsOfTypeAction.ForEach(a => + { var anno = a.enter.activates.Find(t => t.poi == _annotationToEdit.poi); if (anno != null) { diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphListItem.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphListItem.cs index dd45e84fd..c3a029240 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphListItem.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/Glyph/GlyphListItem.cs @@ -12,7 +12,7 @@ public class GlyphListItem : MonoBehaviour private ActionObject _actionObject; private Action _onClick; - + public void Init(ActionObject actionObject, Action onClick) { _actionObject = actionObject; diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ImageMarkerController.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ImageMarkerController.cs index 79b2e2087..411c7e14d 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ImageMarkerController.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ImageMarkerController.cs @@ -182,7 +182,7 @@ private void HoloLensCreateImageTargetFromImageFile() Debug.Log("is tracker active = " + objectTracker.IsActive); - + var runtimeImageSource = objectTracker.RuntimeImageSource; bool result = runtimeImageSource.SetImage(_ImageMarkerImage, _obj.scale, ImgMName); // get the runtime image source and set the texture to load @@ -192,17 +192,17 @@ private void HoloLensCreateImageTargetFromImageFile() var dataset = objectTracker.CreateDataSet(); if (result) - { + { trackableBehaviour = dataset.CreateTrackable(runtimeImageSource, ImgMName); - // use dataset and use the source to create a new trackable image target called ImageTarget + // use dataset and use the source to create a new trackable image target called ImageTarget Debug.Log(trackableBehaviour.name); IM = trackableBehaviour.gameObject; IM.AddComponent(); - // IM.AddComponent(); + // IM.AddComponent(); // add the DefaultTrackableEventHandler to the newly created game object - GameObject detectableParentObj = GameObject.Find("Detectables"); + GameObject detectableParentObj = GameObject.Find("Detectables"); IM.transform.parent = detectableParentObj.transform; detectableAsChild(); // move the Image marker to be a child of the Detectables object in the player scene and set the current detectable to be a child of the newly created Image marker @@ -212,13 +212,13 @@ private void HoloLensCreateImageTargetFromImageFile() } #endif - - + + public void detectableAsChild() { //IM.GetComponent().augmentation = GameObject.Find(detectable.id); ; - + var workplaceManager = RootObject.Instance.workplaceManager; Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(_obj.id)); @@ -228,7 +228,7 @@ public void detectableAsChild() augmentation.transform.parent = GameObject.Find(ImgMName).transform; - augmentation.transform.localPosition = new Vector3(0, 0.1f, 0); + augmentation.transform.localPosition = new Vector3(0, 0.1f, 0); } @@ -291,7 +291,7 @@ private void Awake() /// called when the tracking state changes. /// private void OnTrackableStateChanged(TrackableBehaviour.StatusChangeResult status) // , TrackableBehaviour.Status newStatus) - { + { switch (status.NewStatus) { @@ -312,7 +312,7 @@ protected virtual void OnTrackingFound() { Debug.Log("Trackable " + _trackableBehaviour.TrackableName + " found"); // onTrackingFound.Invoke(); - // augmentation.transform.position = _trackableBehaviour.transform.position;//new Vector3(0, 0, 0); + // augmentation.transform.position = _trackableBehaviour.transform.position;//new Vector3(0, 0, 0); tracked = true; } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ReferenceImageLibrary.asset b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ReferenceImageLibrary.asset index 0b40aec23..1aea3949f 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ReferenceImageLibrary.asset +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarker Prefabs/ReferenceImageLibrary.asset @@ -14,6 +14,10 @@ MonoBehaviour: m_EditorClassIdentifier: m_GuidLow: 5017792793749427099 m_GuidHigh: 6323162187164850849 + m_DataStore: + m_Storage: + - key: com.unity.xr.arcore + value: 0a980350551943a567424279e31a4310769d42be4f6543cb42d7420151ff42c5c9df422b176343e2a68842b63bb1429d512642b44e974273ee654278b0ed4204bf6542c3b1ec429e38d742f9436543652da942cd5585432ea49d4233f11a43bcc98c42370875431cd88e424bef4142c86fa0425f558543a39a8c42da3d5242d073a0424ae95343075b81420657604387a68d42ee7ab1422c25d7424e4997420bab2642642a0243e5b86542da4ff94295583142d13a7b4302f18b4245154143c3a79d423231b142dee36542be19a442f6f12e42f7212242ab0e4242f110f9422c9f5d42d16b2f4321499542afaeed42dc682642e41d97422a1dd74203280243bb672642219759435e7dc0423bfbf842ae6a0542bbda5f43d24f6e4261d949429d1d95421b393a43cf329542df203a43abc5a14218d05f43f6081442f2542843edb88b4295e653439e33a9429584334367a99d4288cf1c431e7295422b154143ae958c42f9c55f43bbcec342d91845435d4f954235fef842fe4ac842e517a4428eea5d42043e3a4359f7944230b05b438b5dcc42f6752443ac389442122d08ac021095011d0000803f222038653936313539366461366134623436626233343831653033633936336630301a3300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022ad010a280801122439363261663032312d363561362d323936362d616165662d35626166346232663162616512280806122431626333336263662d383633372d323732362d613835652d3234376433313866656634361a280806122436313631656365362d383961342d323732362d616164342d31643566356364366461376522280806122439343738356132372d386138322d323732362d613933372d3135383463366663396333365203312e32a206a6040a98034c9e147f70f2268138b6e52122d5fe787f42c5d36742be678030a5d884b725bff62e00969da24a84fdc3508a3333ebb580cdc6aade352750f859642051f7fbe05d90c66af1f424ac831d7b0d80a5cf18ddb982ef899218902d5998512bca4ebb9f9912b07ce9d8882e422463abd49a7a2849920fc7254a3483898dbd105acc973f02950c8b82482ee7fa973c010b56245d60a0a6b1a8588c0e8f12a09e29944c5580276642bb2f8319b8c1ec144def2b7a39a9227f4454aa538ef9f11595cd06c1e4ba4891fc94a59b51deaf2c0bc5e47792f67e09678b1658036dcdea6baad486ed927e80d9814cb9741d46f6d6bebb24af90cc0abd8f412458402cfe7d6b66e933f22eaeeb328ee442a9860a75eae86f702dff780d805afc7e3efe2df9a5fda6db3cf99387f32be68c696144fd523452eb9ba90acf1a6b5bf19e7b63535694d69bf2c19f179429b472683a13d10820ebe04e94f9cbead520f3d90483c25829590a4b97024408e75f3a07a06039bc8ce53fdeab6b49ea457665335f5fd20230393cf778e6efb5e3806cac396a3e4ee3e8a532e4ea43426c12880180800433b01103f63a03fc8b0103d601034203d033092c03c22903c802039a5503a41103031a03cc04031405b801031c03f22b030a03b43303aa04039e23031e030e03060386890103e40103ba0103f41c03f20a03960703d42103bc0303ec0503d01e03c40303d43203c21203b20203ca0903ac0b03b002036a032a03ae0103f63603c61103901e m_Images: - m_SerializedGuid: m_GuidLow: 5424262952407930262 diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarkerEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarkerEditor.cs index 8545d2fd3..b185c31e1 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarkerEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/ImageMarkerEditor.cs @@ -40,7 +40,7 @@ public void SetAnnotationStartingPoint(Transform startingPoint) annotationStartingPoint = startingPoint; } - #region TakePhoto + #region TakePhoto public bool IsThumbnail { @@ -50,7 +50,7 @@ public bool IsThumbnail #if UNITY_WSA private UnityEngine.Windows.WebCam.PhotoCapture photoCaptureObject = null; #endif - + private void OnPictureTaken(bool result, Texture2D texture2D) { PlayCameraSound(); @@ -60,17 +60,18 @@ private void OnPictureTaken(bool result, Texture2D texture2D) Debug.Log("Image W: " + _capturedImage.width); Debug.Log("Image H: " + _capturedImage.height); - // _capturedImage.Resize((_capturedImage.width / 2), (_capturedImage.height / 2)); + // _capturedImage.Resize((_capturedImage.width / 2), (_capturedImage.height / 2)); Debug.Log("Image W: " + _capturedImage.width); Debug.Log("Image H: " + _capturedImage.height); var sprite = Sprite.Create(_capturedImage, new Rect(0, 0, _capturedImage.width, _capturedImage.height), new Vector2(0.5f, 0.5f), 100.0f); - + previewImage.sprite = sprite; previewImage.SetNativeSize(); - while (previewImage.rectTransform.sizeDelta.x > 100) { - previewImage.rectTransform.sizeDelta /= 2; + while (previewImage.rectTransform.sizeDelta.x > 100) + { + previewImage.rectTransform.sizeDelta /= 2; } } @@ -107,7 +108,7 @@ public async void CaptureImageAsync() acceptButton.gameObject.SetActive(false); closeButton.gameObject.SetActive(false); -#if UNITY_WSA +#if UNITY_WSA await ShowCountdown(); #endif if (_capturedImage) Destroy(_capturedImage); @@ -115,12 +116,12 @@ public async void CaptureImageAsync() } public void PlayCameraSound() - { - shutterPlayer.Play(); - } -#endregion + { + shutterPlayer.Play(); + } + #endregion -#region Crop Photo + #region Crop Photo private Texture2D Cropper(Texture2D sourceTexture) { @@ -152,7 +153,7 @@ public void scroll() cropImage.sizeDelta = new Vector2(HW, HW); } -#endregion + #endregion private void SaveImageMarker(Texture2D tex) { @@ -168,7 +169,7 @@ private void SaveImageMarker(Texture2D tex) public void OnAccept() { SaveImageMarker(Cropper(previewImage.sprite.texture)); - // SaveImageMarker(TestImage); + // SaveImageMarker(TestImage); if (annotationToEdit != null) { @@ -223,7 +224,8 @@ public void Open(Action action, ToggleObject annotation) cropScroll.value = 1; } - public void mobiletest() { + public void mobiletest() + { imageMarkerMobile.SetActive(true); } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/LabelEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/LabelEditor.cs index c9cf672ea..44c78b509 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/LabelEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/LabelEditor.cs @@ -12,7 +12,7 @@ public class LabelEditor : MonoBehaviour [SerializeField] private GameObject acceptButton; public GameObject AcceptButton => acceptButton; - + private Action action; private ToggleObject annotationToEdit; diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Correct-Ding.wav b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Correct-Ding.wav new file mode 100644 index 000000000..f14e2adba Binary files /dev/null and b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Correct-Ding.wav differ diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Correct-Ding.wav.meta b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Correct-Ding.wav.meta new file mode 100644 index 000000000..6911a134b --- /dev/null +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Correct-Ding.wav.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: 183b136b9d4dcd24598234f8a7bb54d1 +AudioImporter: + externalObjects: {} + serializedVersion: 6 + defaultSettings: + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + preloadAudioData: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Incorrect-Buzzer.wav b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Incorrect-Buzzer.wav new file mode 100644 index 000000000..cf1c1c469 Binary files /dev/null and b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Incorrect-Buzzer.wav differ diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Incorrect-Buzzer.wav.meta b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Incorrect-Buzzer.wav.meta new file mode 100644 index 000000000..8eb1bd8c7 --- /dev/null +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Incorrect-Buzzer.wav.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: 47259c5f576006f4984e308794b6b1f3 +AudioImporter: + externalObjects: {} + serializedVersion: 6 + defaultSettings: + loadType: 0 + sampleRateSetting: 0 + sampleRateOverride: 44100 + compressionFormat: 1 + quality: 1 + conversionMode: 0 + platformSettingOverrides: {} + forceToMono: 0 + normalize: 1 + preloadAudioData: 1 + loadInBackground: 0 + ambisonic: 0 + 3D: 1 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Pick.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Pick.cs index 54029eba7..189d67bb3 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Pick.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Pick.cs @@ -1,34 +1,60 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.UI; - -namespace MirageXR +namespace MirageXR { + using System.Collections; + using System.Collections.Generic; + using UnityEngine; + using UnityEngine.UI; + public class Pick : MonoBehaviour { + [SerializeField] private Transform _placeLocation; + [SerializeField] private GameObject _pickOb; + [SerializeField] private float _correctionDistance; + [SerializeField] private bool _resetOnMiss = true; + [SerializeField] private SpriteToggle _lockToggle; + [SerializeField] private Button _changeModelButton; + [SerializeField] private Text _hoverGuide; + + [SerializeField] private AudioSource _audioSource; + [SerializeField] private AudioClip _correctAudio; + [SerializeField] private AudioClip _incorrectAudio; + + private bool _shouldPlaySound; + + private Vector3 _resetPosition; + private Quaternion _resetRotation; + private bool _isMoving = false; + private bool _moveMode = true; + private float _targetRadius; + private Color _originalArrowColor; + + private bool _isTrigger = false; + private int _triggerStepIndex; + private float _triggerDuration; + + private bool _editMode = false; + + private const string _LockHelpText = "When locked the arrow (or 3D model) will bounce back to this location if it is not correctly placed on the target"; + private const string _ModelButtonHelpText = "Click this button and select a 3D model from the augmentation list to change the pick and place object model"; - [SerializeField] private Transform placeLocation; - [SerializeField] private GameObject pickOb; - [SerializeField] private float correctionDistance; - [SerializeField] private bool resetOnMiss = true; - [SerializeField] private SpriteToggle lockToggle; - [SerializeField] private Button changeModelButton; - [SerializeField] private Text hoverGuide; + private static MirageXR.ActivityManager _activityManager => MirageXR.RootObject.Instance.activityManager; - [SerializeField] private Vector3 resetPos; - private bool isMoving = false; - private bool moveMode = true; - private float targetRadius; - private Color originalArrowColor; + public bool EditMode + { + get { return _editMode; } + set { _editMode = value; } + } - private const string lockHelpText = "When locked the arrow (or 3D model) will bounce back to this location if it is not correctly placed on the target"; - private const string modelButtonHelpText = "Click this button and select a 3D model from the augmentation list to change the pick and place object model"; + public Vector3 ResetPosition + { + get { return _resetPosition; } + set { _resetPosition = value; } + } - public Vector3 ResetPos + public Quaternion ResetRotation { - get { return resetPos; } - set { resetPos = value; } + get { return _resetRotation; } + set { _resetRotation = value; } } public MeshRenderer ArrowRenderer @@ -40,16 +66,27 @@ public Button ChangeModelButton { get { - return changeModelButton; + return _changeModelButton; } } public bool MoveMode { - set => moveMode = value; - get => moveMode; + get => _moveMode; + set => _moveMode = value; } + public bool IsTrigger + { + get => IsTrigger; + set => IsTrigger = value; + } + + public int TriggerStepIndex + { + get => TriggerStepIndex; + set => TriggerStepIndex = value; + } public string MyModelID { @@ -58,28 +95,26 @@ public string MyModelID void Start() { - targetRadius = placeLocation.transform.localScale.x / 2; - pickOb = this.gameObject; - ChangeCorrectionDistance(targetRadius); - moveMode = false; - lockToggle.IsSelected = true; - - originalArrowColor = pickOb.GetComponentInChildren().material.color; - - changeModelButton.onClick.AddListener(CapturePickModel); - + _targetRadius = _placeLocation.transform.localScale.x / 2; + _pickOb = this.gameObject; + ChangeCorrectionDistance(_targetRadius); + _moveMode = false; + _lockToggle.IsSelected = true; + _originalArrowColor = ArrowRenderer.material.color; - AddHoverGuide(lockToggle.gameObject, lockHelpText); - AddHoverGuide(changeModelButton.gameObject, modelButtonHelpText); + _changeModelButton.onClick.AddListener(CapturePickModel); + AddHoverGuide(_lockToggle.gameObject, _LockHelpText); + AddHoverGuide(_changeModelButton.gameObject, _ModelButtonHelpText); + _shouldPlaySound = false; } void Update() { - float targetRadiusUpdate = placeLocation.transform.localScale.x / 2; + float targetRadiusUpdate = _placeLocation.transform.localScale.x / 2; - if (!moveMode) + if (!_moveMode) { if (transform.hasChanged) { @@ -91,14 +126,16 @@ void Update() } transform.hasChanged = false; } - - if (targetRadius != targetRadiusUpdate) + else if (_moveMode && ArrowRenderer.material.color != _originalArrowColor) { + ArrowRenderer.material.SetColor("_Color", _originalArrowColor); + } - targetRadius = targetRadiusUpdate; - - ChangeCorrectionDistance(targetRadius); + if (_targetRadius != targetRadiusUpdate) + { + _targetRadius = targetRadiusUpdate; + ChangeCorrectionDistance(_targetRadius); } } @@ -107,37 +144,30 @@ void Update() /// private void CapturePickModel() { - changeModelButton.GetComponent().color = Color.red; + _changeModelButton.GetComponent().color = Color.red; ActionEditor.Instance.pickArrowModelCapturing = (true, this); } - - - /// - /// Sets the target transform for the pick object - /// public void SetMoveMode() { - if (moveMode) + if (_moveMode) { - moveMode = false; - SetResetPos(pickOb.transform.localPosition); + _moveMode = false; + ResetPosition = _pickOb.transform.localPosition; + ResetRotation = _pickOb.transform.localRotation; + _shouldPlaySound = false; } else { - moveMode = true; + _moveMode = true; } - lockToggle.ToggleValue(); + _lockToggle.ToggleValue(); } - /// - /// Sets the target transform for the pick object - /// public void SetRestOnMiss(bool reset) { - Debug.Log(reset); - resetOnMiss = reset; + _resetOnMiss = reset; } /// @@ -145,16 +175,7 @@ public void SetRestOnMiss(bool reset) /// public void SetTargettransform(Transform target) { - placeLocation = target; - } - - - /// - /// Sets the possition of the pick objects reset location - /// - public void SetResetPos(Vector3 pos) - { - resetPos = pos; + _placeLocation = target; } /// @@ -162,48 +183,95 @@ public void SetResetPos(Vector3 pos) /// public void ChangeCorrectionDistance(float distance) { - correctionDistance = distance; + _correctionDistance = distance; } /// - /// Sets isMoving to true to show that the object is being manipulated + /// Sets isMoving to true to show that the object is being manipulated. /// public void ManipulationStart() { - isMoving = true; + ArrowRenderer.material.SetColor("_Color", _originalArrowColor); + _isMoving = true; } /// - /// Sets isMoving to false to show that the object has stopped being manipulated + /// Checks if the pick object has been placed correctly and sets isMoving to false to show that the object has stopped being manipulated. /// public void ManipulationStop() { - isMoving = false; - - if (Mathf.Abs(pickOb.transform.localPosition.x - placeLocation.localPosition.x) <= correctionDistance && - Mathf.Abs(pickOb.transform.localPosition.y - placeLocation.localPosition.y) <= correctionDistance && - Mathf.Abs(pickOb.transform.localPosition.z - placeLocation.localPosition.z) <= correctionDistance) + if (_isMoving) { - pickOb.transform.localPosition = new Vector3(placeLocation.localPosition.x, placeLocation.localPosition.y, placeLocation.localPosition.z); - pickOb.GetComponentInChildren().material.SetColor("_Color", Color.green); + if (Mathf.Abs(_pickOb.transform.localPosition.x - _placeLocation.localPosition.x) <= _correctionDistance && + Mathf.Abs(_pickOb.transform.localPosition.y - _placeLocation.localPosition.y) <= _correctionDistance && + Mathf.Abs(_pickOb.transform.localPosition.z - _placeLocation.localPosition.z) <= _correctionDistance) + { + _pickOb.transform.localPosition = new Vector3(_placeLocation.localPosition.x, _placeLocation.localPosition.y, _placeLocation.localPosition.z); + + ArrowRenderer.material.SetColor("_Color", Color.green); + + if (_shouldPlaySound) + { + PlayAudio(_correctAudio); + } + if (_isTrigger && !EditMode) + { + StartCoroutine(TriggerAction()); + } + } + else if (_resetOnMiss) + { + _pickOb.transform.localPosition = ResetPosition; + _pickOb.transform.localRotation = ResetRotation; + + ArrowRenderer.material.SetColor("_Color", _originalArrowColor); + if (_shouldPlaySound) + { + PlayAudio(_incorrectAudio); + } + } } - else if (resetOnMiss) - { - pickOb.transform.localPosition = new Vector3(resetPos.x, resetPos.y, resetPos.z); - + _isMoving = false; + _shouldPlaySound = true; + } - pickOb.GetComponentInChildren().material.SetColor("_Color", originalArrowColor); - } + private void PlayAudio(AudioClip clip) + { + _audioSource.clip = clip; + _audioSource.Play(); } - private void AddHoverGuide(GameObject obj, string hoverMessage) { var HoverGuilde = obj.AddComponent(); - HoverGuilde.SetGuildText(hoverGuide); + HoverGuilde.SetGuildText(_hoverGuide); HoverGuilde.SetMessage(hoverMessage); + } + + private IEnumerator TriggerAction() + { + yield return new WaitForSeconds(_triggerDuration); + + _activityManager.ActivateActionByIndex(_triggerStepIndex); + } + public void SetTrigger(Trigger trigger) + { + _isTrigger = trigger != null ? true : false; + + if (_isTrigger) + { + var stepIndex = int.Parse(trigger.value) - 1; + + if (stepIndex > _activityManager.ActionsOfTypeAction.Count) + { + stepIndex = _activityManager.ActionsOfTypeAction.Count - 1; + } + + _triggerStepIndex = stepIndex; + _triggerDuration = trigger.duration; + } } } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceController.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceController.cs index e12648b6d..ab8133460 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceController.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceController.cs @@ -3,43 +3,46 @@ using UnityEngine; using System.IO; using UnityEngine.UI; +using Microsoft.MixedReality.Toolkit.UI.BoundsControl; namespace MirageXR { public class PickAndPlaceController : MirageXRPrefab { - private static ActivityManager activityManager => RootObject.Instance.activityManager; + private static ActivityManager _activityManager => RootObject.Instance.activityManager; - private ToggleObject myObj; - [SerializeField] private Transform pickObject; - [SerializeField] private Transform targetObject; - [SerializeField] private Transform lockToggle; - [SerializeField] private SpriteToggle spriteToggle; - [SerializeField] private Text textLabel; - private Pick pickComponent; + private ToggleObject _myObj; + [SerializeField] private Transform _pickObject; + [SerializeField] private Transform _targetObject; + [SerializeField] private Transform _lockToggle; + [SerializeField] private SpriteToggle _spriteToggle; + [SerializeField] private Text _textLabel; + private Pick _pickComponent; - private Vector3 defaultTargetSize = new Vector3(0.2f, 0.2f, 0.2f); + private bool _isTrigger; + + private Vector3 _defaultTargetSize = new Vector3(0.2f, 0.2f, 0.2f); private void Start() { - pickComponent = pickObject.GetComponent(); - EditModeChanges(activityManager.EditModeActive); + _pickComponent = _pickObject.GetComponent(); + EditModeChanges(_activityManager.EditModeActive); - if (File.Exists(Path.Combine(activityManager.ActivityPath, "pickandplaceinfo/" + myObj.poi + ".json"))) + if (File.Exists(Path.Combine(_activityManager.ActivityPath, "pickandplaceinfo/" + _myObj.poi + ".json"))) { LoadPickAndPlacePositions(); } - spriteToggle.IsSelected = !pickComponent.MoveMode; - + _spriteToggle.IsSelected = !_pickComponent.MoveMode; + CheckTrigger(); } public ToggleObject MyPoi { get { - return myObj; + return _myObj; } } @@ -47,7 +50,7 @@ public Transform Target { get { - return targetObject; + return _targetObject; } } @@ -67,17 +70,22 @@ private void OnDisable() private void EditModeChanges(bool editModeState) { - lockToggle.gameObject.SetActive(editModeState); - targetObject.gameObject.SetActive(editModeState); - pickComponent.ChangeModelButton.gameObject.SetActive(editModeState); + _lockToggle.gameObject.SetActive(editModeState); + _targetObject.gameObject.SetActive(editModeState); + _pickComponent.ChangeModelButton.gameObject.SetActive(editModeState); + _pickComponent.EditMode = editModeState; + var boundsControl = _pickObject.GetComponent(); + if (boundsControl != null) + { + boundsControl.Active = editModeState; + } } - public override bool Init(ToggleObject obj) { - myObj = obj; + _myObj = obj; - textLabel.text = myObj.text; + _textLabel.text = _myObj.text; // Try to set the parent and if it fails, terminate initialization. if (!SetParent(obj)) @@ -98,64 +106,73 @@ public override bool Init(ToggleObject obj) private void LoadPickAndPlacePositions() { - var json = File.ReadAllText(Path.Combine(activityManager.ActivityPath, "pickandplaceinfo/" + myObj.poi + ".json")); + var json = File.ReadAllText(Path.Combine(_activityManager.ActivityPath, "pickandplaceinfo/" + _myObj.poi + ".json")); Positions positions = JsonUtility.FromJson(json); - if (myObj.key == "1") + if (_myObj.key == "1") { - pickObject.localPosition = positions.resetPosition; + _pickObject.localPosition = positions.resetPosition; } else { - pickObject.localPosition = positions.pickObjectPosition; + _pickObject.localPosition = positions.pickObjectPosition; } - pickObject.localRotation = positions.pickObjectRotation; - targetObject.localPosition = positions.targetObjectPosition; - targetObject.localScale = positions.targetObjectScale != null ? positions.targetObjectScale : defaultTargetSize; - pickComponent.MoveMode = positions.moveMode; - pickComponent.ResetPos = positions.resetPosition; - pickComponent.MyModelID = positions.modelID; - - if (pickComponent.MyModelID != string.Empty) - StartCoroutine(LoadMyModel(pickComponent.MyModelID)); + _pickObject.localRotation = positions.pickObjectRotation; + _pickObject.localScale = positions.pickObjectScale; + _targetObject.localPosition = positions.targetObjectPosition; + _targetObject.localScale = positions.targetObjectScale != null ? positions.targetObjectScale : _defaultTargetSize; + _pickComponent.MoveMode = positions.moveMode; + _pickComponent.ResetPosition = positions.resetPosition; + _pickComponent.ResetRotation = positions.resetRotation; + _pickComponent.MyModelID = positions.modelID; + + if (_pickComponent.MyModelID != string.Empty) + StartCoroutine(LoadMyModel(_pickComponent.MyModelID)); } public void SavePositions() { - - if (myObj == null || myObj.poi == string.Empty) + if (_myObj == null || _myObj.poi == string.Empty || gameObject == null) { return; // only if the poi is instantiated not the prefab } - - Positions positions = new Positions - { - pickObjectPosition = pickObject.localPosition, - pickObjectRotation = pickObject.localRotation, - modelID = pickComponent.MyModelID, - targetObjectPosition = targetObject.localPosition, - targetObjectScale = targetObject.localScale, - resetPosition = pickComponent.ResetPos, - moveMode = pickComponent.MoveMode - }; - - string pickAndPlaceData = JsonUtility.ToJson(positions); - if (!Directory.Exists($"{activityManager.ActivityPath}/pickandplaceinfo ")) + try { - Directory.CreateDirectory($"{activityManager.ActivityPath}/pickandplaceinfo"); + Positions positions = new Positions + { + pickObjectPosition = _pickObject.localPosition, + pickObjectRotation = _pickObject.localRotation, + pickObjectScale = _pickObject.localScale, + modelID = _pickComponent.MyModelID, + targetObjectPosition = _targetObject.localPosition, + targetObjectScale = _targetObject.localScale, + resetPosition = _pickComponent.ResetPosition, + resetRotation = _pickComponent.ResetRotation, + moveMode = _pickComponent.MoveMode, + }; + + string pickAndPlaceData = JsonUtility.ToJson(positions); + if (!Directory.Exists($"{_activityManager.ActivityPath}/pickandplaceinfo")) + { + Directory.CreateDirectory($"{_activityManager.ActivityPath}/pickandplaceinfo"); + } + + string jsonPath = Path.Combine(_activityManager.ActivityPath, $"pickandplaceinfo/{_myObj.poi}.json"); + + // delete the exsiting file first + if (File.Exists(jsonPath)) + { + File.Delete(jsonPath); + } + + File.WriteAllText(jsonPath, pickAndPlaceData); } - - string jsonPath = Path.Combine(activityManager.ActivityPath, $"pickandplaceinfo/{myObj.poi}.json"); - - // delete the exsiting file first - if (File.Exists(jsonPath)) + catch (Exception e) { - File.Delete(jsonPath); + Debug.LogError("Pick and Place Exception " + e); } - - File.WriteAllText(jsonPath, pickAndPlaceData); } private IEnumerator LoadMyModel(string MyModelID) @@ -169,13 +186,13 @@ private IEnumerator LoadMyModel(string MyModelID) yield return null; } - StartCoroutine(ActionEditor.Instance.SpawnNewPickModel(pickComponent, newModel)); + StartCoroutine(ActionEditor.Instance.SpawnNewPickModel(_pickComponent, newModel)); } private void DeletePickAndPlaceData(ToggleObject toggleObject) { if (toggleObject != MyPoi) return; - var arlemPath = activityManager.ActivityPath; + var arlemPath = _activityManager.ActivityPath; var jsonPath = Path.Combine(arlemPath, $"pickandplaceinfo/{MyPoi.poi}.json"); if (File.Exists(jsonPath)) @@ -189,6 +206,13 @@ private void OnDestroy() { SavePositions(); } + + private void CheckTrigger() + { + var trigger = _activityManager.ActiveAction.triggers.Find(t => t.id == Annotation.poi); + _isTrigger = trigger != null ? true : false; + _pickComponent.SetTrigger(trigger); + } } [Serializable] @@ -196,10 +220,12 @@ public class Positions { public Vector3 pickObjectPosition = Vector3.zero; public Quaternion pickObjectRotation = Quaternion.identity; + public Vector3 pickObjectScale = Vector3.zero; public Vector3 targetObjectPosition = Vector3.zero; public Vector3 targetObjectScale = Vector3.zero; public Vector3 resetPosition = Vector3.zero; + public Quaternion resetRotation = Quaternion.identity; public bool moveMode = false; public bool reset = false; public string modelID; diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceEditor.cs index f9f2d2c48..2cd822098 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/PickAndPlaceEditor.cs @@ -4,55 +4,82 @@ public class PickAndPlaceEditor : MonoBehaviour { - private static AugmentationManager augmentationManager => RootObject.Instance.augmentationManager; - private static WorkplaceManager workplaceManager => RootObject.Instance.workplaceManager; + private static AugmentationManager _augmentationManager => RootObject.Instance.augmentationManager; + private static ActivityManager _activityManager => RootObject.Instance.activityManager; + private static WorkplaceManager _workplaceManager => RootObject.Instance.workplaceManager; - [SerializeField] private Transform annotationStartingPoint; - [SerializeField] private InputField textInputField; + [SerializeField] private Transform _annotationStartingPoint; + [SerializeField] private InputField _textInputField; + [SerializeField] private Toggle _toggleTrigger; + [SerializeField] private InputField _triggerStepIndex; + [SerializeField] private InputField _triggerStepTime; + [SerializeField] private GameObject _triggerHelp; + [SerializeField] private GameObject _triggerIndexHelp; + [SerializeField] private GameObject _triggerTimeHelp; + [SerializeField] private Dropdown _resetOnDropDown; - private Action action; - private ToggleObject annotationToEdit; - private int resetOption = 0; + [SerializeField] private GameObject _editor; + [SerializeField] private GameObject _triggerSettings; + + [SerializeField] private Text _hoverGuide; + + private const string _triggerHelpText = "This toggle gives this pick and place augmentation a trigger, allowing you to jump to another step once placed correctly"; + private const string _triggerIndexHelpText = "Use this input box to enter the step the trigger should take you to"; + private const string _triggerTimeHelpText = "use this input box to determine the time between correct placement and moving onto the set step"; + + private bool _isTrigger; + private Action _action; + private ToggleObject _annotationToEdit; + private int _resetOption = 0; public void SetAnnotationStartingPoint(Transform startingPoint) { - annotationStartingPoint = startingPoint; + _annotationStartingPoint = startingPoint; } public void Create() { - if (annotationToEdit != null) + if (_annotationToEdit != null) { // annotationToEdit.predicate = "pickandplace"; - EventManager.DeactivateObject(annotationToEdit); + EventManager.DeactivateObject(_annotationToEdit); } else { - Detectable detectable = workplaceManager.GetDetectable(workplaceManager.GetPlaceFromTaskStationId(action.id)); + Detectable detectable = _workplaceManager.GetDetectable(_workplaceManager.GetPlaceFromTaskStationId(_action.id)); GameObject originT = GameObject.Find(detectable.id); - var offset = Utilities.CalculateOffset(annotationStartingPoint.transform.position, - annotationStartingPoint.transform.rotation, + var offset = Utilities.CalculateOffset(_annotationStartingPoint.transform.position, + _annotationStartingPoint.transform.rotation, originT.transform.position, originT.transform.rotation); - annotationToEdit = augmentationManager.AddAugmentation(action, offset); - annotationToEdit.predicate = "pickandplace"; + _annotationToEdit = _augmentationManager.AddAugmentation(_action, offset); + _annotationToEdit.predicate = "pickandplace"; + } + _annotationToEdit.text = _textInputField.text; + _annotationToEdit.key = _resetOption.ToString(); + + if (_isTrigger) + { + _action.AddOrReplaceArlemTrigger(TriggerMode.PickAndPlace, ActionType.PickAndPlace, _annotationToEdit.poi, int.Parse(_triggerStepTime.text), _triggerStepIndex.text); + } + else + { + _action.RemoveArlemTrigger(_annotationToEdit); } - annotationToEdit.text = textInputField.text; - annotationToEdit.key = resetOption.ToString(); - EventManager.ActivateObject(annotationToEdit); - EventManager.NotifyActionModified(action); + EventManager.ActivateObject(_annotationToEdit); + EventManager.NotifyActionModified(_action); Close(); } public void Close() { - action = null; - annotationToEdit = null; + _action = null; + _annotationToEdit = null; gameObject.SetActive(false); Destroy(gameObject); @@ -61,14 +88,98 @@ public void Close() public void Open(Action action, ToggleObject annotation) { gameObject.SetActive(true); - this.action = action; - annotationToEdit = annotation; - textInputField.text = annotation != null ? annotation.text : string.Empty; + CloseTriggerSettings(); + this._action = action; + _annotationToEdit = annotation; + _textInputField.text = annotation != null ? annotation.text : string.Empty; + _isTrigger = false; + + AddHoverGuide(_triggerHelp, _triggerHelpText); + AddHoverGuide(_triggerIndexHelp, _triggerIndexHelpText); + AddHoverGuide(_triggerTimeHelp, _triggerTimeHelpText); + + if (_annotationToEdit != null) + { + _textInputField.text = _annotationToEdit.text; + + _resetOption = int.Parse(_annotationToEdit.key); + _resetOnDropDown.value = _resetOption; + + var trigger = _activityManager.ActiveAction.triggers.Find(t => t.id == _annotationToEdit.poi); + _isTrigger = trigger != null ? true : false; + if (_isTrigger) + { + _toggleTrigger.isOn = _isTrigger; + _triggerStepTime.text = trigger.duration.ToString(); + _triggerStepIndex.text = trigger.value; + } + } + } + + public void SetResetOption(int option) + { + _resetOption = option; + } + + public void TriggerToggle(bool trigger) + { + var numberOfSteps = _activityManager.ActionsOfTypeAction.Count; + + if (numberOfSteps == 1) + { + if (_toggleTrigger.isOn) + { + DialogWindow.Instance.Show( + "Info!", + "Only one step has been found in this activity!\n Add a new step and try again.", + new DialogButtonContent("Ok")); + + _toggleTrigger.isOn = false; + } + return; + } + else + { + _isTrigger = _toggleTrigger.isOn; + _triggerStepIndex.interactable = _toggleTrigger.isOn; + _triggerStepIndex.text = numberOfSteps.ToString(); + _triggerStepTime.interactable = _toggleTrigger.isOn; + _triggerStepTime.text = "1"; + } + } + + public void OpenTriggerSettings() + { + _editor.SetActive(false); + _triggerSettings.SetActive(true); } - public void setResetOption(int option) + public void CloseTriggerSettings() { - resetOption = option; + _editor.SetActive(true); + _triggerSettings.SetActive(false); + } + + public void OnStepTriggerValueChanged() + { + var numberOfSteps = _activityManager.ActionsOfTypeAction.Count; + + if (numberOfSteps < int.Parse(_triggerStepIndex.text)) + { + DialogWindow.Instance.Show( + "Info!", + "The entered step number doesn't exist yet. This trigger will jump to the last avalible step", + new DialogButtonContent("Ok")); + + _triggerStepIndex.text = numberOfSteps.ToString(); + return; + } } + private void AddHoverGuide(GameObject obj, string hoverMessage) + { + var HoverGuilde = obj.AddComponent(); + HoverGuilde.SetGuildText(_hoverGuide); + HoverGuilde.SetMessage(hoverMessage); + } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Place.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Place.cs index 98d30a841..4d96281af 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Place.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/PickAndPlace/Place.cs @@ -33,7 +33,7 @@ void Start() { pickOb = this.gameObject; ChangeCorrectionDistance(0.5f); - SetResetPos(pickOb.transform.localPosition); + SetResetPos(pickOb.transform.localPosition); } >>>>>>> 55eb6be7398f057b0e0973d8af228b1c3495229f @@ -99,7 +99,7 @@ public void setTargettransform(Transform target) /// /// Sets the possition of the pick objects reset location - /// + /// public void setResetPos(Vector3 pos) { resetPos = pos; @@ -110,7 +110,7 @@ public void setResetPos(Vector3 pos) } else { moveMode = true; - } + } } /// @@ -141,7 +141,7 @@ public void changeCorrectionDistance(float distance) <<<<<<< HEAD /// - /// Sets isMoving to true to show that the object is being manipulated + /// Sets isMoving to true to show that the object is being manipulated /// public void manipulationStart() { @@ -149,7 +149,7 @@ public void manipulationStart() } /// - /// Sets isMoving to false to show that the object has stopped being manipulated + /// Sets isMoving to false to show that the object has stopped being manipulated /// public void manipulationStop() { @@ -169,7 +169,7 @@ public void manipulationStop() ======= /// /// Sets the possition of the pick objects reset location - /// + /// public void SetResetPos(Vector3 pos) { resetPos = pos; @@ -183,14 +183,14 @@ public void ChangeCorrectionDistance(float distance) { } /// - /// Sets isMoving to true to show that the object is being manipulated + /// Sets isMoving to true to show that the object is being manipulated /// public void ManipulationStart() { isMoving = true; } /// - /// Sets isMoving to false to show that the object has stopped being manipulated + /// Sets isMoving to false to show that the object has stopped being manipulated /// public void ManipulationStop() { isMoving = false; diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VFX/VFXEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VFX/VFXEditor.cs index c2368a360..5d82991c7 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VFX/VFXEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VFX/VFXEditor.cs @@ -7,7 +7,7 @@ public class VFXEditor : MonoBehaviour [SerializeField] private Transform _contentContainer; [SerializeField] private VfxListItem _vfxListItemPrefab; [SerializeField] private VfxObject[] _vfxObjects; - + private Action _action; private ToggleObject _annotationToEdit; private Transform _annotationStartingPoint; @@ -39,7 +39,7 @@ private void OnDisable() { foreach (var icon in _contentContainer.GetComponentsInChildren()) { - if(icon.gameObject != _contentContainer.gameObject) + if (icon.gameObject != _contentContainer.gameObject) Destroy(icon.gameObject); } } diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VideoEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VideoEditor.cs index edc70329c..b0a2e08ff 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VideoEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionDetailView/Annotation Editors/VideoEditor.cs @@ -76,13 +76,13 @@ public void Open(Action action, ToggleObject annotation) public void OnAccept() { - if(IsRecording) + if (IsRecording) StopRecording(); #if UNITY_EDITOR - if(annotationToEdit == null) + if (annotationToEdit == null) { // create dummy video clip so that the augmentation can be created in Unity (debugging only) newFileName = $"videoTest_MP4.mp4"; @@ -132,16 +132,16 @@ public void OnAccept() GameObject originT = GameObject.Find(detectable.id); var startPointTr = annotationStartingPoint.transform; - var offset = Utilities.CalculateOffset(startPointTr.position, startPointTr.rotation, + var offset = Utilities.CalculateOffset(startPointTr.position, startPointTr.rotation, originT.transform.position, originT.transform.rotation); annotationToEdit = RootObject.Instance.augmentationManager.AddAugmentation(action, offset); annotationToEdit.predicate = "video"; } - + // saving of the movie file has already happened since it has been written to file while recording annotationToEdit.url = httpPrefix + newFileName; - + EventManager.ActivateObject(annotationToEdit); EventManager.NotifyActionModified(action); @@ -179,16 +179,16 @@ public async void StartRecording() VuforiaBehaviour.Instance.enabled = false; IsRecording = true; - if(annotationToEdit != null) + if (annotationToEdit != null) await DeleteOldVideoFile(); newFileName = $"MirageXR_Video_{System.DateTime.Now.ToFileTimeUtc()}.mp4"; var filepath = Path.Combine(activityManager.ActivityPath, newFileName); - + NativeCameraController.StartRecordingVideo(filepath, OnVideoRecordingStopped); Maggie.Speak("Recording"); } - + private void OnVideoRecordingStopped(bool result, string path) { Maggie.Speak("Stopped recording"); @@ -202,7 +202,7 @@ private void OnVideoRecordingStopped(bool result, string path) previewImage.texture = NativeCameraController.GetVideoThumbnail(path); } } - + /// /// User has intended to stop recording /// diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionEditor.cs index 2d709c846..9838c1ef3 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/ActionEditor.cs @@ -9,7 +9,7 @@ public class ActionEditor : MonoBehaviour { private static ActivityManager activityManager => RootObject.Instance.activityManager; - + [SerializeField] private GameObject TaskStationMenuPanel; [SerializeField] private GameObject TaskStationOpenButton; [SerializeField] private InputField titleField; @@ -20,7 +20,7 @@ public class ActionEditor : MonoBehaviour [SerializeField] private GameObject annotationAddMenu; [SerializeField] private GameObject poiAddItemPrefab; [SerializeField] private Button thumbnailButton; - [SerializeField] private Text instructionText; + [SerializeField] private Text instructionText; [SerializeField] private Text helpText; [SerializeField] private Transform DefaultAugmentationStartingPoint; @@ -41,7 +41,7 @@ public class ActionEditor : MonoBehaviour [SerializeField] private GameObject imageMarkerPrefab; [SerializeField] private GameObject pluginPrefab; [SerializeField] private GameObject drawingEditorPrefab; - + private LabelEditor labelEditor; private AudioEditor audioEditor; private ImageEditor imageEditor; @@ -78,7 +78,7 @@ public bool AddMenuVisible annotationAddMenu.SetActive(value && activityManager.EditModeActive); poiList.SetActive(!value); - if(TaskStationDetailMenu.Instance && value) + if (TaskStationDetailMenu.Instance && value) { StepNavigationTargetCapturing = false; TaskStationDetailMenu.Instance.SelectedButton = null; @@ -106,14 +106,14 @@ private void Awake() private void OnEnable() { EventManager.OnEditModeChanged += SetEditModeState; - titleField.onValueChanged.AddListener( OnTitleChanged); - descriptionField.onValueChanged.AddListener(OnDescriptionChanged) ; + titleField.onValueChanged.AddListener(OnTitleChanged); + descriptionField.onValueChanged.AddListener(OnDescriptionChanged); if (activityManager != null) { SetEditModeState(activityManager.EditModeActive); } - + if (!PlatformManager.Instance.WorldSpaceUi) { CloseTaskStationMenu(); @@ -122,7 +122,7 @@ private void OnEnable() private void OnDisable() { - titleField.onValueChanged.RemoveListener( OnTitleChanged); + titleField.onValueChanged.RemoveListener(OnTitleChanged); descriptionField.onValueChanged.RemoveListener(OnDescriptionChanged); EventManager.OnEditModeChanged -= SetEditModeState; } @@ -147,7 +147,7 @@ private void Start() { var augmentationCorrectTypeName = listOfAugmentations[i].Replace("&", "and").Replace(" ", string.Empty).ToUpper(); var augmentationIndexOnEnum = (int)Enum.Parse(typeof(ContentType), augmentationCorrectTypeName); - var type = (ContentType) augmentationIndexOnEnum; + var type = (ContentType)augmentationIndexOnEnum; var addItemInstance = Instantiate(poiAddItemPrefab, annotationAddMenu.transform); var listItem = addItemInstance.GetComponent(); listItem.Initialize(type, i, listOfAugmentations[i], type.GetIcon()); @@ -179,7 +179,7 @@ public Transform GetDefaultAugmentationStartingPoint() { return DefaultAugmentationStartingPoint; } - + private void OnToggleActionTargetCapture() { //if there is no annotations @@ -203,7 +203,7 @@ private void OnToggleActionTargetCapture() /// Control the helper text under the target button /// /// - /// + /// Co-Routine values private IEnumerator NavigatorNotification(string msg, int sec) { navigationTargetButton.GetComponentInChildren().enabled = true; @@ -232,7 +232,7 @@ private void CaptureNavigationTarget(ToggleObject annotation) navigationTargetButton.GetComponent().color = Color.white; navigationTargetButton.GetComponentInChildren().enabled = false; StepNavigationTargetCapturing = false; - TaskStationDetailMenu.Instance.NavigatorTarget = ActionListMenu.CorrectTargetObject(annotation); + TaskStationDetailMenu.Instance.NavigatorTarget = ActionListMenu.CorrectTargetObject(annotation); TaskStationDetailMenu.Instance.TargetPredicate = annotation.predicate; // show the target icon if annotation is the target of this action @@ -302,7 +302,7 @@ public IEnumerator SpawnNewPickModel(Pick pick, GameObject newModel) public void OnTitleChanged(string newTitle) { - if (detailView.DisplayedAction!= null) + if (detailView.DisplayedAction != null) { detailView.DisplayedAction.instruction.title = newTitle; EventManager.NotifyActionModified(detailView.DisplayedAction); @@ -358,7 +358,7 @@ public void OnAnnotationAddItemSelected(ContentType type) case ContentType.ACT: glyphEditor = LoadEditorPanel(GlyphSelectorPrefab); glyphEditor.SetAnnotationStartingPoint(DefaultAugmentationStartingPoint); - glyphEditor.Open(detailView.DisplayedAction,null); + glyphEditor.Open(detailView.DisplayedAction, null); break; case ContentType.VFX: vfxEditor = LoadEditorPanel(VfxEditorPrefab); @@ -400,11 +400,11 @@ public void OnAnnotationAddItemSelected(ContentType type) } } -/// + /// /// This function instantiates the relevant prefab and, depending on the augmentation type, /// allows the controller component to be returned after configuration. /// - /// + /// The component which should be searched on the instantiated prefab and which is returned /// /// A component of the type specified during the function call. private T LoadEditorPanel(GameObject prefabToLoad) where T : Component @@ -420,7 +420,7 @@ private T LoadEditorPanel(GameObject prefabToLoad) where T : Component } public object CreateEditorView(ContentType type) - { + { switch (type) { case ContentType.IMAGE: @@ -439,7 +439,7 @@ public void OnAnnotationHover(ContentType type, int index) var taskStation = detailView.GetCurrentTaskStation(); if (!taskStation) return; - + TaskStationDetailMenu.Instance.BindPoiToTaskStation(taskStation.transform, augmentationsButtons[index].transform); instructionText.text = type.GetHint(); @@ -458,12 +458,12 @@ public void EditAnnotation(ToggleObject annotation) CaptureNavigationTarget(annotation); // pick and place can only use the model augmentation as it's arrow - if(annotation.predicate.StartsWith("3d") ) + if (annotation.predicate.StartsWith("3d")) CapturePickArrowTarget(annotation, pickArrowModelCapturing.Item2); switch (annotation.predicate) { - case "label": + case "label": labelEditor = LoadEditorPanel(TextEditorPrefab); labelEditor.Open(detailView.DisplayedAction, annotation); break; @@ -473,7 +473,7 @@ public void EditAnnotation(ToggleObject annotation) break; case "image": imageEditor = LoadEditorPanel(ImageEditorPrefab); - imageEditor.Open(detailView.DisplayedAction, annotation); + imageEditor.Open(detailView.DisplayedAction, annotation); break; case "video": videoEditor = LoadEditorPanel(VideoEditorPrefab); @@ -544,7 +544,7 @@ public void DisableAllPoiEditors() imageMarkerEditor.Close(); if (pluginEditor) pluginEditor.Close(); - if(drawingEditor) + if (drawingEditor) drawingEditor.Close(); @@ -567,7 +567,7 @@ private void SetEditModeState(bool editModeActive) spawnPointVisualPart.SetActive(editModeActive); DisableAllPoiEditors(); - + if (!PlatformManager.Instance.WorldSpaceUi) { CloseTaskStationMenu(); diff --git a/Assets/MirageXR/Common/Scripts/CombinedEditor/AnnotationEditor.cs b/Assets/MirageXR/Common/Scripts/CombinedEditor/AnnotationEditor.cs index c77a5a7a8..69a331a71 100644 --- a/Assets/MirageXR/Common/Scripts/CombinedEditor/AnnotationEditor.cs +++ b/Assets/MirageXR/Common/Scripts/CombinedEditor/AnnotationEditor.cs @@ -42,7 +42,7 @@ public void DeleteAnnotation() if (TaskStationDetailMenu.Instance.SelectedButton == GetComponent /// Action toggle object. /// Returns true if initialization succesfull. - public override bool Init (ToggleObject obj) + public override bool Init(ToggleObject obj) { _obj = obj; - + // Check that url is not empty. - if (string.IsNullOrEmpty (obj.url)) + if (string.IsNullOrEmpty(obj.url)) { - Debug.Log ("Content URL not provided."); + Debug.Log("Content URL not provided."); return false; } - + // Try to set the parent and if it fails, terminate initialization. - if (!SetParent (obj)) + if (!SetParent(obj)) { - Debug.Log ("Couldn't set the parent."); + Debug.Log("Couldn't set the parent."); return false; } @@ -107,17 +107,17 @@ public override bool Init (ToggleObject obj) } // Load audio from resources. - if (obj.url.StartsWith ("resources://")) + if (obj.url.StartsWith("resources://")) { audioName = obj.url.Replace("resources://", ""); - CreateAudioPlayer (false, audio3dMode, radius, Loop); + CreateAudioPlayer(false, audio3dMode, radius, Loop); } // Load audio from server. else { audioName = obj.url; - CreateAudioPlayer (true, audio3dMode, radius, Loop); + CreateAudioPlayer(true, audio3dMode, radius, Loop); } // If all went well, return true. @@ -125,13 +125,13 @@ public override bool Init (ToggleObject obj) } - private void Update () + private void Update() { if (audioEditor && (audioEditor.IsRecording || audioEditor.IsPlaying)) { StopAudio(); - if(iconImage) - iconImage.sprite = pauseIcon; + if (iconImage) + iconImage.sprite = pauseIcon; return; } @@ -139,18 +139,18 @@ private void Update () { if (isReady == true) { - PlayAudio (); + PlayAudio(); } } - if (Input.GetKeyUp (KeyCode.M)) + if (Input.GetKeyUp(KeyCode.M)) { - MuteAudio (); + MuteAudio(); } } /// /// This method starts playback of the audio file, unmuted and on full volume. - /// If the audio track is already being played, it will be restarted from the beginning. + /// If the audio track is already being played, it will be restarted from the beginning. /// If audio source doesn't exist, or hasn't finished loading, the method returns without doing anything /// public void PlayAudio() @@ -160,16 +160,16 @@ public void PlayAudio() return; } var audioSource = gameObject.GetComponent(); - + if (audioSource != null) { if (audioSource.isPlaying == true) { - audioSource.Stop (); + audioSource.Stop(); } audioSource.mute = false; audioSource.volume = 1.0f; - audioSource.Play (); + audioSource.Play(); isPlaying = true; audioLength = audioSource.clip.length; @@ -200,7 +200,11 @@ private static IEnumerator ActivateTrigger(AudioSource audioSource, Trigger trig activityManager.ActiveAction.isCompleted = true; } - activityManager.ActivateNextAction(); + if (int.TryParse(trigger.value, out var stepNumber)) + { + activityManager.ActivateActionByIndex(stepNumber - 1); + } + TaskStationDetailMenu.Instance.SelectedButton = null; } } @@ -209,23 +213,23 @@ private static IEnumerator ActivateTrigger(AudioSource audioSource, Trigger trig /// /// Pause the playback of audio, or if already paused, resume play /// - public void PauseAudio () + public void PauseAudio() { if (isReady == false) { return; } - AudioSource audioSource = gameObject.GetComponent (); + AudioSource audioSource = gameObject.GetComponent(); if (audioSource != null) { if (audioSource.isPlaying == true) { - audioSource.Pause (); + audioSource.Pause(); isPlaying = false; } else { - audioSource.Play (); + audioSource.Play(); isPlaying = true; } } @@ -235,18 +239,18 @@ public void PauseAudio () /// /// Stop the playback of audio /// - public void StopAudio () + public void StopAudio() { if (isReady == false) { return; } - AudioSource audioSource = gameObject.GetComponent (); + AudioSource audioSource = gameObject.GetComponent(); if (audioSource != null) { if (audioSource.isPlaying == true) { - audioSource.Stop (); + audioSource.Stop(); isPlaying = false; } } @@ -257,13 +261,13 @@ public void StopAudio () /// Set the volume of the audio /// /// 0.0-1.0 - public void SetAudioVolume (float targetVolume) + public void SetAudioVolume(float targetVolume) { if (isReady == false) { return; } - AudioSource audioSource = gameObject.GetComponent (); + AudioSource audioSource = gameObject.GetComponent(); if (audioSource != null) { audioSource.mute = false; @@ -274,13 +278,13 @@ public void SetAudioVolume (float targetVolume) /// /// This method mutes the audio, or unmutes it, if it is already muted /// - public void MuteAudio () + public void MuteAudio() { if (isReady == false) { return; } - AudioSource audioSource = gameObject.GetComponent (); + AudioSource audioSource = gameObject.GetComponent(); if (audioSource != null) { audioSource.mute = !audioSource.mute; @@ -292,13 +296,13 @@ public void MuteAudio () /// This method is used to set the audio to loop itself or be a one-shot /// /// if true, audio repeats itself - public void LoopAudio (bool setLooping) + public void LoopAudio(bool setLooping) { if (isReady == false) { return; } - AudioSource audioSource = gameObject.GetComponent (); + AudioSource audioSource = gameObject.GetComponent(); if (audioSource != null) { audioSource.loop = setLooping; @@ -312,19 +316,19 @@ public void LoopAudio (bool setLooping) /// PlayAudio() must be called to start the audio playback. /// /// If true, load video from application's LocalState folder, if false, load from project resources. - public void CreateAudioPlayer (bool useExternalAudioSource = false, bool spatialAudio = false, float radius = 0f, bool loopAduio = false) + public void CreateAudioPlayer(bool useExternalAudioSource = false, bool spatialAudio = false, float radius = 0f, bool loopAduio = false) { useExternalSource = useExternalAudioSource; - if (gameObject.GetComponent () != null) + if (gameObject.GetComponent() != null) { - Destroy (gameObject.GetComponent ()); + Destroy(gameObject.GetComponent()); } isReady = false; isPlaying = false; - // Create audio source component - var audioPlayer = gameObject.AddComponent (); + // Create audio source component + var audioPlayer = gameObject.AddComponent(); if (spatialAudio) { @@ -338,17 +342,17 @@ public void CreateAudioPlayer (bool useExternalAudioSource = false, bool spatial if (useExternalSource == true) { - StartCoroutine (nameof(LoadAudio)); + StartCoroutine(nameof(LoadAudio)); } else { // If the audio clip name has a suffix, remove it - if (audioName.EndsWith (".mp3") || audioName.EndsWith (".wav")) + if (audioName.EndsWith(".mp3") || audioName.EndsWith(".wav")) { - audioName = audioName.Substring (0, audioName.Length - 4); + audioName = audioName.Substring(0, audioName.Length - 4); } - Debug.Log ("Trying to load audio: " + audioName); - AudioClip audioClip = Resources.Load (audioName, typeof (AudioClip)) as AudioClip; + Debug.Log("Trying to load audio: " + audioName); + AudioClip audioClip = Resources.Load(audioName, typeof(AudioClip)) as AudioClip; audioPlayer.clip = audioClip; audioPlayer.playOnAwake = false; isReady = true; @@ -357,18 +361,18 @@ public void CreateAudioPlayer (bool useExternalAudioSource = false, bool spatial } - private IEnumerator LoadAudio () + private IEnumerator LoadAudio() { - AudioSource audioPlayer = gameObject.GetComponent (); - if (audioName.StartsWith ("http") == false) + AudioSource audioPlayer = gameObject.GetComponent(); + if (audioName.StartsWith("http") == false) { // Local file string dataPath = Application.persistentDataPath; string completeAudioName = "file://" + dataPath + "/" + audioName; - Debug.Log ("Trying to load audio: " + completeAudioName); - WWW www = new WWW (completeAudioName); + Debug.Log("Trying to load audio: " + completeAudioName); + WWW www = new WWW(completeAudioName); yield return www; - AudioClip audioClip = www.GetAudioClip (false, false, AudioType.WAV); + AudioClip audioClip = www.GetAudioClip(false, false, AudioType.WAV); audioPlayer.clip = audioClip; audioPlayer.playOnAwake = false; isReady = true; @@ -410,12 +414,14 @@ private void OnDestroy() Destroy(_contentObject); } - public float getAudioLength() { + public float getAudioLength() + { return audioLength; } - public float getCurrenttime() { + public float getCurrenttime() + { AudioSource audioSource = gameObject.GetComponent(); return audioSource.time; } diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Detect/Detect.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Detect/Detect.cs index 67fdfe9ab..a9ac9b6c1 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Detect/Detect.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Detect/Detect.cs @@ -36,23 +36,23 @@ public class Detect : MirageXRPrefab private float _rotationFactor = 0.35f; // Use this for initialization - private void Awake () + private void Awake() { // Disable the default gaze guide since we are using a custom one... UseGuide = false; - + // Attach components - - _startingPoint = GameObject.FindGameObjectWithTag ("MainCamera").transform; - _lineRend = GetComponent (); - _timerCircle = transform.Find ("TimerCircle").GetComponent (); - _triangles = transform.Find ("Triangles").GetComponent (); - _trianglesTransform = transform.Find ("Triangles").GetComponent (); - _centerDot = transform.Find ("Center").GetComponent (); + _startingPoint = GameObject.FindGameObjectWithTag("MainCamera").transform; + + _lineRend = GetComponent(); + _timerCircle = transform.Find("TimerCircle").GetComponent(); + _triangles = transform.Find("Triangles").GetComponent(); + _trianglesTransform = transform.Find("Triangles").GetComponent(); + _centerDot = transform.Find("Center").GetComponent(); - _audio = GetComponent (); + _audio = GetComponent(); } /// @@ -60,12 +60,12 @@ private void Awake () /// /// Action toggle object. /// Returns true if initialization succesfull. - public override bool Init (ToggleObject obj) + public override bool Init(ToggleObject obj) { // Try to set the parent and if it fails, terminate initialization. - if (!SetParent (obj)) + if (!SetParent(obj)) { - Debug.Log ("Couldn't set the parent."); + Debug.Log("Couldn't set the parent."); return false; } @@ -73,15 +73,15 @@ public override bool Init (ToggleObject obj) name = obj.predicate; // Set scale, if defined in the action step configuration. - if (!obj.scale.Equals (0)) - GetComponent ().localScale = new Vector3 (obj.scale, obj.scale, obj.scale) / 2048; + if (!obj.scale.Equals(0)) + GetComponent().localScale = new Vector3(obj.scale, obj.scale, obj.scale) / 2048; // If scaling is not set, default to 5 cm symbol. else - GetComponent ().localScale = new Vector3 (0.05f, 0.05f, 0.05f) / 2048; + GetComponent().localScale = new Vector3(0.05f, 0.05f, 0.05f) / 2048; // Set target duration if defined in the action configuration. - if (!obj.duration.Equals (0)) + if (!obj.duration.Equals(0)) _target = obj.duration; // If duration is not set, default to 1.5 seconds. @@ -96,7 +96,7 @@ public override bool Init (ToggleObject obj) } // Update is called once per frame - private void Update () + private void Update() { // Line renderer is enabled once a proper location reference is received. if (_lineRend.enabled) @@ -118,14 +118,14 @@ private void Update () } // Rotate triangles. The closer you get, the slower the rotation. - _trianglesTransform.Rotate (Vector3.forward, Vector3.Distance (transform.position, _startingPoint.position) * _rotationFactor); + _trianglesTransform.Rotate(Vector3.forward, Vector3.Distance(transform.position, _startingPoint.position) * _rotationFactor); // If not detected and not yet completed, draw the line between the symbol and the cursor. if (!_isDetected && !_isCompleted) { _lineRend.enabled = true; - _lineRend.SetPosition (0, _startingPoint.position); - _lineRend.SetPosition (1, transform.position); + _lineRend.SetPosition(0, _startingPoint.position); + _lineRend.SetPosition(1, transform.position); _centerDot.enabled = true; _triangles.enabled = true; _timerCircle.enabled = true; @@ -173,7 +173,7 @@ private void Update () } // Ding dong. - _audio.Play (); + _audio.Play(); // Wohoo! _isCompleted = true; diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/GazeGuide/GazeGuide.cs b/Assets/MirageXR/Player/Scripts/Augmentations/GazeGuide/GazeGuide.cs index aa4cdbb62..d871fafdd 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/GazeGuide/GazeGuide.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/GazeGuide/GazeGuide.cs @@ -14,20 +14,20 @@ public class GazeGuide : MonoBehaviour public GameObject Parent { get; set; } // Inbuild Unity function launched when object is first rendered with any camera. - private void OnBecameVisible () + private void OnBecameVisible() { // Raise the flag when object has become visible. _isVisible = true; } // Inbuild Unity function launched when object is no more rendered with any cameras. - private void OnBecameInvisible () + private void OnBecameInvisible() { // Lower the flag when object has become invisible. _isVisible = false; } - private void Update () + private void Update() { // If object has entered the view, count time the timer. if (_isVisible && !_isFound) @@ -48,7 +48,7 @@ private void Update () _isFound = true; // Disable the gaze guide. - Parent.GetComponent ().enabled = false; + Parent.GetComponent().enabled = false; // Disable this object. //gameObject.SetActive (false); diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/ImageViewer/FloatingImageViewer.cs b/Assets/MirageXR/Player/Scripts/Augmentations/ImageViewer/FloatingImageViewer.cs index 6c5fb5ec2..24b8ad90a 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/ImageViewer/FloatingImageViewer.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/ImageViewer/FloatingImageViewer.cs @@ -1,15 +1,16 @@ using Microsoft.MixedReality.Toolkit.UI.BoundsControl; -using System.Collections; +using System.IO; +using System.Linq; +using System.Threading.Tasks; using UnityEngine; namespace MirageXR { public class FloatingImageViewer : MirageXRPrefab { - private ActivityManager activityManager => RootObject.Instance.activityManager; + private const string MAIN_TEXTUERE = "_MainTex"; - private float _width = 0.4f; - private float _height = 0.3f; + private ActivityManager activityManager => RootObject.Instance.activityManager; [Tooltip("Image file. .jpg and .png formats supported")] @@ -24,26 +25,17 @@ public class FloatingImageViewer : MirageXRPrefab [SerializeField] private GameObject Background; - - //private Transform _contentPanel; private Vector3 _originalPosition = Vector3.zero; private Quaternion _originalRotation = Quaternion.identity; private Vector3 _originalScale = Vector3.one; - private bool _originalGuideState; - private GameObject _thinLine; private ToggleObject _obj; - + private GameObject _thinLine; private GameObject _contentObject; + private Texture2D _texture; public ToggleObject ToggleObject => _obj; - - // private void Awake() - // { - // _contentPanel = GameObject.FindGameObjectWithTag("ContentPanel").transform; - // } - /// /// Initialization method. /// @@ -75,24 +67,23 @@ public override bool Init(ToggleObject obj) { SetOrientation(FrameLandscape, FramePortrait, BackgroundLandscape); } + // Get the last bit of the url. - var id = obj.url.Split('/')[obj.url.Split('/').Length - 1]; + var id = obj.url.Split('/').LastOrDefault(); // Rename with the predicate + id to get unique name. - name = obj.predicate + "_" + id; + name = $"{obj.predicate}_{id}"; // Load from resources. if (obj.url.StartsWith("resources://")) { // Set image url. - imageName = obj.url.Replace("resources://", ""); + imageName = obj.url.Replace("resources://", string.Empty); // Create image viewer. Defaults to 4:3 landscape images for now. CreateImageViewer(1.0f, 0.75f, false); } - - // Load from external url. - else + else // Load from external url. { // Set image url. imageName = obj.url; @@ -108,13 +99,18 @@ public override bool Init(ToggleObject obj) { // Setup guide line feature. if (!SetGuide(obj)) + { return false; + } _thinLine = transform.FindDeepChild("ThinLine").gameObject; } - // this ensures objectmanipulator and billboard components are set - GetComponentInParent().UpdateManipulationOptions(gameObject); + var poiEditor = GetComponentInParent(); + if (poiEditor) + { + poiEditor.UpdateManipulationOptions(gameObject); + } return base.Init(obj); } @@ -127,25 +123,14 @@ public override bool Init(ToggleObject obj) /// If true, load image from application's LocalState folder, if false, load from project resources. public void CreateImageViewer(float width, float height, bool useExternalImageSource) { - if (width > 0) - { - _width = width; - } - if (height > 0) - { - _height = height; - } useExternalSource = useExternalImageSource; - // Create image viewer screen - MeshFilter meshFilter = Background.GetComponent(); - // meshFilter.mesh = CreatePlaneMesh (); - MeshRenderer renderer = Background.GetComponent(); - renderer.material.shader = Shader.Find("Unlit/Texture"); + var meshRenderer = Background.GetComponent(); + meshRenderer.material.shader = Shader.Find("Unlit/Texture"); - if (useExternalSource == true) + if (useExternalSource) { - StartCoroutine(nameof(LoadImage)); + LoadImage().AsAsyncVoid(); } else { @@ -154,52 +139,41 @@ public void CreateImageViewer(float width, float height, bool useExternalImageSo { imageName = imageName.Substring(0, imageName.Length - 4); } - Texture2D imageTex = Resources.Load(imageName, typeof(Texture2D)) as Texture2D; - renderer.sharedMaterial.SetTexture("_MainTex", imageTex); + + var imageTex = Resources.Load(imageName, typeof(Texture2D)) as Texture2D; + meshRenderer.sharedMaterial.SetTexture(MAIN_TEXTUERE, imageTex); } } - - private IEnumerator LoadImage() + private async Task LoadImage() { - MeshRenderer renderer = Background.GetComponent(); - if (imageName.StartsWith("http") == false) + var meshRenderer = Background.GetComponent(); + string path; + if (imageName.StartsWith("http")) { - string dataPath = Application.persistentDataPath; - string completeImageName = "file://" + dataPath + "/" + imageName; - Debug.Log("Trying to load image from:" + completeImageName); - WWW www = new WWW(completeImageName); - yield return www; - Texture2D imageTex = new Texture2D(4, 4, TextureFormat.DXT1, false); - www.LoadImageIntoTexture(imageTex); - renderer.sharedMaterial.SetTexture("_MainTex", imageTex); + if (!imageName.Contains('/')) + { + Debug.LogError($"Can't parse file name '{imageName}'"); + } + + var fileName = imageName.Split('/').LastOrDefault(); + path = Path.Combine(activityManager.ActivityPath, fileName); } else { - // Online files stored locally. - var url = imageName.Split('/'); - var filename = url[url.Length - 1]; - - var completeImageName = $"file://{activityManager.ActivityPath}/{filename}"; - - Debug.Log("Trying to load image from:" + completeImageName); - - WWW www = new WWW(completeImageName); - yield return www; - Texture2D imageTex = new Texture2D(4, 4, TextureFormat.DXT1, false); - www.LoadImageIntoTexture(imageTex); - renderer.sharedMaterial.SetTexture("_MainTex", imageTex); - - // Online files. - /* - WWW www = new WWW (imageName); - yield return www; - Texture2D imageTex = new Texture2D (4, 4, TextureFormat.DXT1, false); - www.LoadImageIntoTexture (imageTex); - renderer.sharedMaterial.SetTexture ("_MainTex", imageTex); - */ + path = Path.Combine(Application.persistentDataPath, imageName); + } + + if (!File.Exists(path)) + { + Debug.LogError($"File {path} doesn't exists"); + return; } + var data = await File.ReadAllBytesAsync(path); + _texture = new Texture2D(2, 2, TextureFormat.RGB24, false); + _texture.LoadImage(data); + meshRenderer.sharedMaterial.SetTexture(MAIN_TEXTUERE, _texture); } private void SetOrientation(GameObject activeFrame, GameObject unusedFrame, GameObject background) @@ -214,41 +188,12 @@ private void SetOrientation(GameObject activeFrame, GameObject unusedFrame, Game Background = background; - BoundsControl boundsControl = gameObject.GetComponent(); + var boundsControl = gameObject.GetComponent(); boundsControl.enabled = false; boundsControl.enabled = true; // required to reset the bounding boxes of the frame used so that it displays correctly } - /// - /// Create a simple 2-triangle rectangle mesh in standing up position - /// - // private Mesh CreatePlaneMesh () - // { - // Mesh m = new Mesh (); - // m.name = "PlaneMesh"; - // m.vertices = new Vector3 [] { - // new Vector3( _width/2f, -_height/2f, 0 ), - // new Vector3( -_width/2f, -_height/2f, 0 ), - // new Vector3( -_width/2f, _height/2f, 0 ), - // new Vector3( _width/2f, _height/2f, 0 ) - // }; - // m.uv = new Vector2 [] { - // new Vector2 (1, 0), - // new Vector2 (0, 0), - // new Vector2 (0, 1), - // new Vector2 (1, 1) - // }; - // m.triangles = new int [] { 0, 1, 2, 0, 2, 3 }; - // m.RecalculateNormals (); - - // return m; - //} - - - - - public void ToggleInPanel(bool inPanel) { if (inPanel) @@ -263,10 +208,8 @@ public void ToggleInPanel(bool inPanel) _thinLine.SetActive(false); } - InPanel = true; } - else { InPanel = false; @@ -283,20 +226,21 @@ private void Update() { if (InPanel) { - // GetComponent().enabled = false; - // transform.position = _contentPanel.position; - // transform.rotation = _contentPanel.rotation; transform.localScale = Vector3.one * 0.35f; } - - // else - // GetComponent().enabled = true; } private void OnDestroy() { if (_contentObject != null) + { Destroy(_contentObject); + } + + if (_texture) + { + Destroy(_texture); + } } } } diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Label/Label.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Label/Label.cs index d1a5ba0ba..1adf9928d 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Label/Label.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Label/Label.cs @@ -21,19 +21,19 @@ public class Label : MirageXRPrefab /// /// Action toggle object. /// Returns true if initialization succesfull. - public override bool Init (ToggleObject obj) + public override bool Init(ToggleObject obj) { // Check if the label text is set. - if (string.IsNullOrEmpty (obj.text)) + if (string.IsNullOrEmpty(obj.text)) { - Debug.Log ("Label text not provided."); + Debug.Log("Label text not provided."); return false; } // Try to set the parent and if it fails, terminate initialization. - if (!SetParent (obj)) + if (!SetParent(obj)) { - Debug.Log ("Couldn't set the parent."); + Debug.Log("Couldn't set the parent."); return false; } diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/MirageXRPrefab.cs b/Assets/MirageXR/Player/Scripts/Augmentations/MirageXRPrefab.cs index 0a51c3a71..4b42a03f6 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/MirageXRPrefab.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/MirageXRPrefab.cs @@ -230,7 +230,7 @@ public virtual bool Init(ToggleObject obj) /// public virtual void Delete() { - if(gameObject != null) + if (gameObject != null) Destroy(gameObject); } @@ -312,8 +312,8 @@ protected bool SetParent(ToggleObject obj) /// - /// Reads and convert the PoiEditor's scale factor, - /// checking for null values and, in case of error, + /// Reads and convert the PoiEditor's scale factor, + /// checking for null values and, in case of error, /// reverting to the given default value. /// /// @@ -343,7 +343,7 @@ protected static Vector3 GetPoiScale(PoiEditor poiEditor, Vector3 defaultScale) } /// - /// Reads and convert the PoiEditor's rotation factor, + /// Reads and convert the PoiEditor's rotation factor, /// checking for null values. If not set, reverts to /// euler angle version of Quaternion.identity. /// @@ -361,8 +361,8 @@ protected static Vector3 GetPoiRotation(PoiEditor poiEditor) private bool IsGazeTrigger() { - return activityManager.ActiveAction.triggers.Find(t => t.id == Annotation.poi) != null - && Annotation.predicate != "video" && Annotation.predicate != "audio" && !Annotation.predicate.StartsWith("char"); + return activityManager.ActiveAction.triggers.Find(t => t.id == Annotation.poi) != null + && Annotation.predicate != "video" && Annotation.predicate != "audio" && !Annotation.predicate.StartsWith("char") && Annotation.predicate != "pickandplace"; } @@ -407,7 +407,7 @@ private void DetectLabelOnGaze() gazeCircle = Instantiate(Resources.Load("Prefabs/UI/GazeSpinner"), hit.collider.transform.position, transform.rotation); gazeCircle.AddComponent(); gazeCircle.GetComponent().Duration = trigger.duration; - gazeCircle.GetComponent().stepNumber = triggerStepNumber; + gazeCircle.GetComponent().stepNumber = triggerStepNumber; gazeCircle.transform.SetParent(transform); } } diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Model/Model.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Model/Model.cs index ef77aa47f..aba938b27 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Model/Model.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Model/Model.cs @@ -6,7 +6,9 @@ namespace MirageXR { public class Model : MirageXRPrefab - { + { + private static ActivityManager _activityManager => RootObject.Instance.activityManager; + private float startLoadTime = 0.0f; private ToggleObject myToggleObject; private Animation animation; @@ -21,6 +23,13 @@ private void Start() private void OnDestroy() { + var poiEditor = GetComponentInParent(); + + if (poiEditor) + { + poiEditor.EnableBoundsControl(false); + } + UnSubscribe(); } @@ -49,16 +58,16 @@ public override bool Init(ToggleObject obj) myToggleObject = obj; // Check that url is not empty. - if (string.IsNullOrEmpty (obj.url)) + if (string.IsNullOrEmpty(obj.url)) { - Debug.Log ("Content URL not provided."); + Debug.Log("Content URL not provided."); return false; } - + // Try to set the parent and if it fails, terminate initialization. - if (!SetParent (obj)) + if (!SetParent(obj)) { - Debug.Log ("Couldn't set the parent."); + Debug.Log("Couldn't set the parent."); return false; } @@ -72,8 +81,9 @@ public override bool Init(ToggleObject obj) // Setup guide line feature. if (!SetGuide(obj)) return false; } - + // If all went well, return true. + return true; } @@ -89,7 +99,7 @@ private void LoadModel(ToggleObject obj) private void OnFinishLoadingAsync(GameObject model, AnimationClip[] clip) { - if(this == null) + if (this == null) { Destroy(model); return; @@ -130,6 +140,13 @@ private void OnFinishLoadingAsync(GameObject model, AnimationClip[] clip) animation.clip.legacy = true; animation.Play(); } + + var poiEditor = GetComponentInParent(); + + if (poiEditor) + { + poiEditor.EnableBoundsControl(true); + } } private List colliders; @@ -167,18 +184,18 @@ private void ConfigureModel(GameObject _model, AnimationClip[] clips) var newCollider = g.AddComponent(); colliders.Add(newCollider.bounds); } - + } else { colliders.Add(g.GetComponent().bounds); } - } + } } private static void AddCapsuleCollidersToPatient(Transform rootBone) { - for (int child = 0; child < rootBone.childCount; child++) + for (int child = 0; child < rootBone.childCount; child++) { var childBone = rootBone.GetChild(child); var capcoll = childBone.gameObject.AddComponent(); diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelAnnotationEditor.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelAnnotationEditor.cs index a3bffe0d8..ecf0d4232 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelAnnotationEditor.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelAnnotationEditor.cs @@ -51,7 +51,7 @@ public class MirageXRModelAnnotationEditor : MonoBehaviour // gameObject.GetComponent().menuItemTexts[i] = modelsCollection[i]; // gameObject.GetComponent().menuItemNames[i]= "PlaceModel"; // } - + // } @@ -124,7 +124,7 @@ void DestroyChild() } /// - /// method to call the expand model + /// method to call the expand model /// public void ExpandModel() @@ -138,7 +138,7 @@ public void CompressModel() Debug.Log("3d model compressed"); gameObject.GetComponentInChildren().SendMessage("CompressModel", SendMessageOptions.DontRequireReceiver); } - + public void RotateModel() { Destroy(gameObject.GetComponent()); diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelExpander.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelExpander.cs index cebb9cfb7..3211bd7bf 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelExpander.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Model/Old/MirageXRModelExpander.cs @@ -6,7 +6,7 @@ /// /// @bibeg /// basic class for expanding the 3d model based on the parent gameobject which holds all the subcomponenet 3d models -/// The methods is activated on airtap +/// The methods is activated on airtap /// public class MirageXRModelExpander : MonoBehaviour { @@ -25,8 +25,8 @@ public class MirageXRModelExpander : MonoBehaviour /// /// The scalr to determine how far the model will expand /// - private float expansionFactor = 0.1f; - + private float expansionFactor = 0.1f; + // Use this for initialization void Start() { @@ -57,13 +57,13 @@ void ExpandModel() //calculate the vector between 2 points pointing from center to the center of the child and increase it by a scalar Vector3 direction = g.GetComponent().bounds.center - modelCenter; //normalize and add the new vector to the old child position - g.position += direction.normalized * expansionFactor; + g.position += direction.normalized * expansionFactor; //g.localPosition not working } } - else + else { - Debug.Log(isExpanded + " " + modelBlock.Count); + Debug.Log(isExpanded + " " + modelBlock.Count); } //change the expanded state isExpanded = !isExpanded; @@ -71,7 +71,7 @@ void ExpandModel() } /// - /// methods for compressing the class back to original state. How ever since the initial position of the child is not saved the opposite vector + /// methods for compressing the class back to original state. How ever since the initial position of the child is not saved the opposite vector /// is calculated and added to the expanded vector /// void CompressModel() @@ -80,11 +80,11 @@ void CompressModel() { foreach (Transform g in modelBlock) { - //using transfrom.position and using localPos to origin or model center didnt work + //using transfrom.position and using localPos to origin or model center didnt work Vector3 direction = modelCenter - g.GetComponent().bounds.center; //normalize but since the direction is opposite it should subract based on point to point system. - g.position += direction.normalized * expansionFactor; - + g.position += direction.normalized * expansionFactor; + } } else diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Plugin/PluginEditor.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Plugin/PluginEditor.cs index e95b7ed75..3f8e65b4b 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Plugin/PluginEditor.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Plugin/PluginEditor.cs @@ -16,13 +16,13 @@ public struct Plugin public string name; public string manifest; } - + [SerializeField] private Transform annotationStartingPoint; [SerializeField] private Transform contentContainer; [SerializeField] private GameObject iconPrefab; [SerializeField] private Texture2D defaultIcon; [SerializeField] private Plugin[] Plugins; - + private Action _action; private ToggleObject _annotationToEdit; @@ -101,7 +101,7 @@ public void Create(App plugin) _annotationToEdit.predicate = "plugin:" + plugin.name; _annotationToEdit.url = plugin.manifest; - + workplaceManager.workplace.apps.Add(plugin); _action.appIDs.Add(plugin.id); diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/AudioRecorder.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/AudioRecorder.cs index 500470a92..54e293699 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/AudioRecorder.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/AudioRecorder.cs @@ -12,7 +12,7 @@ public static class AudioRecorder private const string RECORD_NAME = "record"; private const int CYCLE_RECORDING_TIME = 60; private const int DEFAULT_FREQUENCY = 96000; - + private static AudioClip _audioClip; private static readonly List _buffer = new List(); private static int _maxFrequency; @@ -32,7 +32,7 @@ public static string[] GetRecordingDevices() return null; } } - + public static void SetRecordingDevice(string recordingDevice) { if (IsRecording) @@ -55,10 +55,11 @@ public static void SetRecordingDevice(string recordingDevice) throw new ArgumentException($"Device {recordingDevice} does not exist"); } } - - public static void Start(string recordName = RECORD_NAME) { + + public static void Start(string recordName = RECORD_NAME) + { _recordName = recordName; - + if (IsRecording) { Stop(); @@ -69,20 +70,21 @@ public static void Start(string recordName = RECORD_NAME) { var devices = GetRecordingDevices(); _device = devices?.First(); } - + Microphone.GetDeviceCaps(_device, out _, out _maxFrequency); if (_maxFrequency == 0) _maxFrequency = DEFAULT_FREQUENCY; _buffer.Clear(); _audioClip = null; StartRecord(CYCLE_RECORDING_TIME); } - - public static void Pause() { + + public static void Pause() + { if (!IsRecording) return; - + var lastTime = Microphone.GetPosition(_device); if (lastTime == 0) return; - + cancellationTokenSource.Cancel(); cancellationTokenSource = null; var samples = new float[_audioClip.samples]; @@ -94,13 +96,15 @@ public static void Pause() { _audioClip = null; } - public static void Resume() { + public static void Resume() + { if (IsRecording || _buffer.Count == 0) return; - + StartRecord(CYCLE_RECORDING_TIME); } - - public static AudioClip Stop() { + + public static AudioClip Stop() + { Pause(); _audioClip = null; var audioClip = AudioClip.Create(_recordName, _buffer.Count, 1, _maxFrequency, false); diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/HololensSensors.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/HololensSensors.cs index 5f0a26bf9..756afe169 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/HololensSensors.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/HololensSensors.cs @@ -25,7 +25,7 @@ private void Start() public override void FixedFrameUpdate() { var cameraTransform = Camera.main.transform; - + currentSensorDataFrame = new SensorDataFrame(); // Check if the raycast from the user's head in the direction of his gaze hit an object. diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/SensorBase.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/SensorBase.cs index 955beebef..a5568da8e 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/SensorBase.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Sensor/SensorBase.cs @@ -3,7 +3,7 @@ namespace MirageXR { - public class SensorBase : MonoBehaviour // TODO: now is useless + public class SensorBase : MonoBehaviour // TODO: now is useless { // streaming data: list of registered callback listeners (registered to get an update for each data frame captured) public delegate void CallbackStack(SensorDataFrame currentFrame); @@ -27,7 +27,7 @@ private void Start() /// /// FixedFrameUpdate is used (instead of Update) to set /// the sensor update frame rate to the desired interval. - /// The routine is registered in Start(). The public float + /// The routine is registered in Start(). The public float /// updateInterval can be overridden in order to change the frequency. /// public virtual void FixedFrameUpdate() @@ -66,12 +66,12 @@ public virtual bool StopCapture() return (true); } - public virtual void RegisterStreamListener ( CallbackStack fun ) + public virtual void RegisterStreamListener(CallbackStack fun) { - OnSensorStreamUpdate += fun; + OnSensorStreamUpdate += fun; } - public virtual void UnregisterStreamListener( CallbackStack fun) + public virtual void UnregisterStreamListener(CallbackStack fun) { OnSensorStreamUpdate -= fun; } diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/Symbol/RotationMachine.cs b/Assets/MirageXR/Player/Scripts/Augmentations/Symbol/RotationMachine.cs index 3370fb985..99fa36bb8 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/Symbol/RotationMachine.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/Symbol/RotationMachine.cs @@ -13,33 +13,37 @@ public class RotationMachine : MonoBehaviour private float _speedFactor = 1f; // Rotation axis selection. - public enum Axis { None, X, Y, Z }; + public enum Axis { None, X, Y, Z } public Axis ActiveAxis = Axis.X; // Rotation direction selection - public enum Direction { CW, CCW }; + public enum Direction { CW, CCW } public Direction ActiveDirection = Direction.CW; public float Speed = 1f; // Update is called once per frame - void Update () + private void Update() { if (ActiveDirection == Direction.CW) + { _speedFactor = -1f; + } else + { _speedFactor = 1f; + } switch (ActiveAxis) { case Axis.X: - transform.Rotate (_speedFactor * Speed, 0, 0); + transform.Rotate(_speedFactor * Speed, 0, 0); break; case Axis.Y: - transform.Rotate (0, _speedFactor * Speed, 0); + transform.Rotate(0, _speedFactor * Speed, 0); break; case Axis.Z: - transform.Rotate (0, 0, _speedFactor * Speed); + transform.Rotate(0, 0, _speedFactor * Speed); break; case Axis.None: default: diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/UiSymbol/UiSymbol.cs b/Assets/MirageXR/Player/Scripts/Augmentations/UiSymbol/UiSymbol.cs index 193c875a3..61b71a4e2 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/UiSymbol/UiSymbol.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/UiSymbol/UiSymbol.cs @@ -7,37 +7,37 @@ namespace MirageXR { public class UiSymbol : MirageXRPrefab { - private void Awake () + private void Awake() { // We don't need the gaze guide for UI symbols. UseGuide = false; } - + /// /// Initialization method. /// /// Action toggle object. /// Returns true if initialization succesfull. - public override bool Init (ToggleObject content) + public override bool Init(ToggleObject content) { // Try to fetch the symbol sprite from the resources. - var symbol = Resources.Load (content.predicate); + var symbol = Resources.Load(content.predicate); // If symbol couldn't be found, terminate initialization. if (symbol == null) { - Debug.Log ("Symbol couldn't be found. " + content.predicate); + Debug.Log("Symbol couldn't be found. " + content.predicate); return false; } // Set the displayed sprite to the one just loaded. - GetComponent ().sprite = symbol; + GetComponent().sprite = symbol; // Set parent. - transform.SetParent (GameObject.FindGameObjectWithTag ("ActionUi.Symbols").transform); + transform.SetParent(GameObject.FindGameObjectWithTag("ActionUi.Symbols").transform); // Get the rect transform component. - var rectTransform = GetComponent (); + var rectTransform = GetComponent(); // Set initial transform. rectTransform.localPosition = Vector3.zero; @@ -49,13 +49,13 @@ public override bool Init (ToggleObject content) rectTransform.localScale = Vector3.one; // Set final position, if defined in action step. - if (!string.IsNullOrEmpty (content.position)) + if (!string.IsNullOrEmpty(content.position)) rectTransform.localPosition = Utilities.ParseStringToVector3(content.position); // Set final rotation, if defined in action step. - if (!string.IsNullOrEmpty (content.rotation)) + if (!string.IsNullOrEmpty(content.rotation)) rectTransform.localEulerAngles = Utilities.ParseStringToVector3(content.rotation); - + // Set name. name = content.predicate; diff --git a/Assets/MirageXR/Player/Scripts/Augmentations/VideoViewer/FloatingVideoViewer.cs b/Assets/MirageXR/Player/Scripts/Augmentations/VideoViewer/FloatingVideoViewer.cs index 25e68a75d..2486ea81a 100644 --- a/Assets/MirageXR/Player/Scripts/Augmentations/VideoViewer/FloatingVideoViewer.cs +++ b/Assets/MirageXR/Player/Scripts/Augmentations/VideoViewer/FloatingVideoViewer.cs @@ -20,16 +20,6 @@ public class FloatingVideoViewer : MirageXRPrefab [Tooltip("Set to false to read from project's 'Resources' folder; set to true to read from applications 'LocalState' folder on HoloLens, or online, if filename starts with 'http'")] [SerializeField] private bool useExternalSource = false; - [Tooltip("The video texture component")] - [SerializeField] private UnityEngine.UI.RawImage _renderTexture; - - [SerializeField] private RectTransform cardRT; - [SerializeField] private RectTransform videoRT; - [SerializeField] private RectTransform slider; - [SerializeField] private RectTransform pause; - [SerializeField] private RectTransform stop; - [SerializeField] private RectTransform play; - private bool isAudioReady = false; private bool isVideoReady = false; private bool isPlaying = false; @@ -46,20 +36,52 @@ public class FloatingVideoViewer : MirageXRPrefab private ToggleObject _obj; + [SerializeField] private GameObject _landscapePlayerObject; + [SerializeField] private GameObject _portraitPlayerObject; + + + [Tooltip("The video texture component")] + private UnityEngine.UI.RawImage _renderTexture; + [SerializeField] private UnityEngine.UI.RawImage _renderTextureLand; + [SerializeField] private UnityEngine.UI.RawImage _renderTexturePort; + private VideoPlayer _videoPlayer; + [SerializeField] private VideoPlayer _videoPlayerLandscape; + [SerializeField] private VideoPlayer _videoPlayerPortrait; private AudioSource _audioSource; + [SerializeField] private AudioSource _audioSourceLandscape; + [SerializeField] private AudioSource _audioSourcePortrait; public bool VideoClipLoaded => _videoPlayer.clip != null; public float VideoDuration => (float)_videoPlayer.length; - private void Awake() + /// + /// Initialization method. + /// + /// Action toggle object. + /// Returns true if initialization successful. + public override bool Init(ToggleObject content) { - // _contentPanel = GameObject.FindGameObjectWithTag("ContentPanel").transform; - _videoPlayer = transform.Find("VideoCanvas").Find("Slider").GetComponent(); - _audioSource = transform.Find("VideoCanvas").Find("Slider").GetComponent(); + _obj = content; - // Fix for the missing audio track issue (hopefully...). + if (_obj.key == "P") + { + _landscapePlayerObject.SetActive(false); + _portraitPlayerObject.SetActive(true); + + _videoPlayer = _videoPlayerPortrait; + _audioSource = _audioSourcePortrait; + _renderTexture = _renderTexturePort; + } + else + { + _landscapePlayerObject.SetActive(true); + _portraitPlayerObject.SetActive(false); + _videoPlayer = _videoPlayerLandscape; + _audioSource = _audioSourceLandscape; + _renderTexture = _renderTextureLand; + } if (ServiceManager.GetService().UseAudioTrack) { @@ -67,16 +89,6 @@ private void Awake() _videoPlayer.EnableAudioTrack(0, true); _videoPlayer.SetTargetAudioSource(0, _audioSource); } - } - - /// - /// Initialization method. - /// - /// Action toggle object. - /// Returns true if initialization successful. - public override bool Init(ToggleObject content) - { - _obj = content; // Check that url is not empty. if (string.IsNullOrEmpty(content.url)) @@ -94,7 +106,7 @@ public override bool Init(ToggleObject content) // Rename with the predicate + id to get unique name. name = content.predicate; - + // Load video from resources. videoName = content.url.StartsWith("resources://") ? content.url.Replace("resources://", string.Empty) : content.url; @@ -125,20 +137,6 @@ public override bool Init(ToggleObject content) videoFilePath = $"file://{videoFilePath}"; #endif - if (content.key == "P") - { - this.transform.eulerAngles = new Vector3(0, 0, -90); - - play.Rotate(0, 0, 90); - pause.Rotate(0, 0, 90); - stop.Rotate(0, 0, 90); - slider.Rotate(0, 0, 90); - slider.localPosition = new Vector3(0.27f, 0, 0); - } - - - videoRT.sizeDelta = new Vector2(160, 90); - SetupNewRenderTexture(); _videoPlayer.url = videoFilePath; @@ -168,7 +166,6 @@ public override bool Init(ToggleObject content) // Check if trigger is active StartCoroutine(ActivateTrigger()); - Debug.Log("KEY IS: " + content.key); // If all went well, return true. return base.Init(content); } @@ -228,7 +225,7 @@ private IEnumerator ActivateTrigger() var triggerDuration = myTrigger.duration; yield return new WaitForSeconds(triggerDuration); - + if (!activityManager.IsLastAction(activityManager.ActiveAction)) { if (activityManager.ActiveAction != null) @@ -290,7 +287,7 @@ public void StopVideo() } /// - /// Set the volume of the audio in the video being played + /// Set the volume of the audio in the video being played /// /// 0.0-1.0 public void SetAudioVolume(float targetVolume) @@ -338,9 +335,9 @@ public void MuteAudio() } /// - /// This method creates a video player according to the input dimensions. - /// Set "videoName" and "audioName" variables before calling this method, or default filenames "video" and "audio" are used. - /// Destroys any already existing video player in this GameObject. + /// This method creates a video player according to the input dimensions. + /// Set "videoName" and "audioName" variables before calling this method, or default filenames "video" and "audio" are used. + /// Destroys any already existing video player in this GameObject. /// PlayVideo() must be called to start the video playback. /// /// Use to set video aspect ratio. If 0 or negative, default 16:9 is used. @@ -373,7 +370,7 @@ public void CreateVideoPlayer(float width = 0.16f, float height = 0.09f, bool ha isPlaying = false; isPaused = false; - // Create video player screen + // Create video player screen var meshFilter = gameObject.GetComponent(); meshFilter.mesh = CreatePlaneMesh(); var meshRenderer = gameObject.GetComponent(); @@ -512,16 +509,16 @@ private Mesh CreatePlaneMesh() { name = "PlaneMesh", vertices = new Vector3[] { - new Vector3( _width / 2f, -_height / 2f, 0 ), - new Vector3( -_width / 2f, -_height / 2f, 0 ), - new Vector3( -_width / 2f, _height / 2f, 0 ), - new Vector3( _width / 2f, _height / 2f, 0 ) + new Vector3(_width / 2f, -_height / 2f, 0), + new Vector3(-_width / 2f, -_height / 2f, 0), + new Vector3(-_width / 2f, _height / 2f, 0), + new Vector3(_width / 2f, _height / 2f, 0) }, uv = new Vector2[] { - new Vector2 (1, 0), - new Vector2 (0, 0), - new Vector2 (0, 1), - new Vector2 (1, 1) + new Vector2(1, 0), + new Vector2(0, 0), + new Vector2(0, 1), + new Vector2(1, 1) }, triangles = new int[] { 0, 1, 2, 0, 2, 3 } }; diff --git a/Assets/MirageXR/Player/Scripts/Behaviours/ContainerBehaviour.cs b/Assets/MirageXR/Player/Scripts/Behaviours/ContainerBehaviour.cs index 1264455a4..9fe19ec2d 100644 --- a/Assets/MirageXR/Player/Scripts/Behaviours/ContainerBehaviour.cs +++ b/Assets/MirageXR/Player/Scripts/Behaviours/ContainerBehaviour.cs @@ -7,13 +7,13 @@ namespace MirageXR /// public class ContainerBehaviour : MonoBehaviour { - private void OnEnable () + private void OnEnable() { // Register to events. EventManager.OnClearAll += ClearContainer; } - private void OnDisable () + private void OnDisable() { // Unregister from events. EventManager.OnClearAll -= ClearContainer; @@ -22,7 +22,7 @@ private void OnDisable () /// /// Resets the container to empty state. /// - private void ClearContainer () + private void ClearContainer() { // Destroy all the child objects inside the container. foreach (Transform obj in transform) diff --git a/Assets/MirageXR/Player/Scripts/Behaviours/DetectableBehaviour.cs b/Assets/MirageXR/Player/Scripts/Behaviours/DetectableBehaviour.cs index 6c1c41d22..9459e2501 100644 --- a/Assets/MirageXR/Player/Scripts/Behaviours/DetectableBehaviour.cs +++ b/Assets/MirageXR/Player/Scripts/Behaviours/DetectableBehaviour.cs @@ -58,19 +58,19 @@ public enum TrackingStyle Extended } - [Tooltip ("Trackable TrackableType of this trackable. Set by the workplace file through the WorkplaceParser.")] + [Tooltip("Trackable TrackableType of this trackable. Set by the workplace file through the WorkplaceParser.")] public TrackableType Type = TrackableType.Anchor; - [Tooltip ("Tracking style of this trackable. Set by the workplace file through the WorkplaceParser.")] + [Tooltip("Tracking style of this trackable. Set by the workplace file through the WorkplaceParser.")] public TrackingStyle Style = TrackingStyle.Raw; - [Tooltip ("The game object that should be moved by this trackable.")] + [Tooltip("The game object that should be moved by this trackable.")] public GameObject AttachedObject; - [Tooltip ("Radius for defining fixed and handheld object active area (in meters).")] + [Tooltip("Radius for defining fixed and handheld object active area (in meters).")] public float Radius = 1.5f; - [Tooltip ("Tolerance for handheld movements (in meters).")] + [Tooltip("Tolerance for handheld movements (in meters).")] public float Tolerance = 0.01f; private void Awake() @@ -78,12 +78,12 @@ private void Awake() _trackableComponent = GetComponent(); } - private void OnEnable () + private void OnEnable() { EventManager.OnPlayerReset += PlayerReset; } - private void OnDisable () + private void OnDisable() { EventManager.OnPlayerReset -= PlayerReset; @@ -106,29 +106,29 @@ private void DetachTrackable() } // Use this for initialization. - private void Start () + private void Start() { // Hololens camera position is the same as user position. _userPosition = GameObject.FindGameObjectWithTag("MainCamera").transform; // Attach _origin object - if(transform.Find ("Origin") != null) - _origin = transform.Find ("Origin").transform; + if (transform.Find("Origin") != null) + _origin = transform.Find("Origin").transform; // Attach the renderer check - if (transform.Find ("RendererCheck") != null) - _rendererCheck = transform.Find ("RendererCheck").GetComponent(); + if (transform.Find("RendererCheck") != null) + _rendererCheck = transform.Find("RendererCheck").GetComponent(); IsDetectableReady = true; } private void Delete() { - if(!CompareTag("Permanent")) + if (!CompareTag("Permanent")) Destroy(gameObject); } - private void PlayerReset () + private void PlayerReset() { IsLocated = false; IsActive = false; @@ -139,11 +139,11 @@ private void PlayerReset () transform.localEulerAngles = Vector3.zero; } - + // Attach anchor. - public void AttachAnchor () + public void AttachAnchor() { AttachedObject.transform.position = transform.position; AttachedObject.transform.rotation = transform.rotation; @@ -152,7 +152,7 @@ public void AttachAnchor () } // Update is called once per frame - private void Update () + private void Update() { // Detectable behaviour can behave only if a tracker is attached... if (IsDetectableReady && AttachedObject != null) @@ -177,7 +177,7 @@ private void Update () // Behave according to set tracking style... switch (Style) { - // If normal Vuforia tracking is set... + // If normal Vuforia tracking is set... case (TrackingStyle.Raw): default: // ...update the position of the attached object. @@ -193,31 +193,31 @@ private void Update () // ...which means that we can safely enable the gaze guiding. IsLocated = true; } - + // ... tell attached object to show content - AttachedObject.SendMessage ("ShowContent", SendMessageOptions.DontRequireReceiver); + AttachedObject.SendMessage("ShowContent", SendMessageOptions.DontRequireReceiver); } // ... and if detectable is lost else { // ... tell attached object to hide content - AttachedObject.SendMessage ("HideContent", SendMessageOptions.DontRequireReceiver); + AttachedObject.SendMessage("HideContent", SendMessageOptions.DontRequireReceiver); } break; // If handheld tracking style is set... case TrackingStyle.Handheld: - + // If not yet active and if the distance between the detectable position and the attached object position is greater than Tolerance... - if (!IsActive && Mathf.Abs (Vector3.Distance (transform.position, AttachedObject.transform.position)) > Tolerance) + if (!IsActive && Mathf.Abs(Vector3.Distance(transform.position, AttachedObject.transform.position)) > Tolerance) { // ...update the position of the attached object. AttachedObject.transform.localPosition = _origin.position; AttachedObject.transform.localRotation = _origin.rotation; // ... tell attached object to show content - AttachedObject.SendMessage ("ShowContent", SendMessageOptions.DontRequireReceiver); + AttachedObject.SendMessage("ShowContent", SendMessageOptions.DontRequireReceiver); // Set active flag IsActive = true; @@ -225,8 +225,8 @@ private void Update () // If active and within active area (arms length), update attached object transform if movement Tolerance is exceeded... if (IsActive && - Mathf.Abs (Vector3.Distance (_userPosition.position, AttachedObject.transform.position)) < Radius && - Mathf.Abs (Vector3.Distance (transform.position, AttachedObject.transform.position)) > Tolerance) + Mathf.Abs(Vector3.Distance(_userPosition.position, AttachedObject.transform.position)) < Radius && + Mathf.Abs(Vector3.Distance(transform.position, AttachedObject.transform.position)) > Tolerance) { // ...update the position of the attached object. AttachedObject.transform.localPosition = _origin.position; @@ -236,7 +236,7 @@ private void Update () // If detectable is lost, tell attached object to hide content and set inactive flag if (!IsDetected) { - AttachedObject.SendMessage ("HideContent", SendMessageOptions.DontRequireReceiver); + AttachedObject.SendMessage("HideContent", SendMessageOptions.DontRequireReceiver); IsActive = false; } @@ -252,14 +252,14 @@ private void Update () } // If not yet active and if the distance between the detectable position and the attached object position is greater than Tolerance... - if (!IsActive && Mathf.Abs (Vector3.Distance (transform.position, AttachedObject.transform.position)) > Tolerance) + if (!IsActive && Mathf.Abs(Vector3.Distance(transform.position, AttachedObject.transform.position)) > Tolerance) { // ...update the position of the attached object. AttachedObject.transform.localPosition = _origin.position; AttachedObject.transform.localRotation = _origin.rotation; // ... tell attached object to show content - AttachedObject.SendMessage ("ShowContent", SendMessageOptions.DontRequireReceiver); + AttachedObject.SendMessage("ShowContent", SendMessageOptions.DontRequireReceiver); // Set active flag IsActive = true; @@ -269,7 +269,7 @@ private void Update () if (Mathf.Abs(Vector3.Distance(_userPosition.position, AttachedObject.transform.position)) > Radius) { // ... tell attached object to hide content - AttachedObject.SendMessage ("HideContent", SendMessageOptions.DontRequireReceiver); + AttachedObject.SendMessage("HideContent", SendMessageOptions.DontRequireReceiver); // Set inactive flag IsActive = false; @@ -280,7 +280,7 @@ private void Update () // If the TrackableType is not supported... default: - EventManager.DebugLog ("Error: Detectable behaviour: " + name + ": Unknown sensor TrackableType"); + EventManager.DebugLog("Error: Detectable behaviour: " + name + ": Unknown sensor TrackableType"); break; } } diff --git a/Assets/MirageXR/Player/Scripts/Behaviours/DeviceMqttBehaviour.cs b/Assets/MirageXR/Player/Scripts/Behaviours/DeviceMqttBehaviour.cs index a46db96df..e60a9c954 100644 --- a/Assets/MirageXR/Player/Scripts/Behaviours/DeviceMqttBehaviour.cs +++ b/Assets/MirageXR/Player/Scripts/Behaviours/DeviceMqttBehaviour.cs @@ -126,7 +126,7 @@ public async Task Init(Sensor sensor) return false; } } - + // All good! return true; } @@ -356,7 +356,7 @@ public void LinkDisplay(Transform anchor) _sensorDisplay.GetComponent().enabled = false; } - private void Delete () + private void Delete() { _mqtt.Disconnect(); Destroy(gameObject); @@ -366,7 +366,7 @@ private void Update() { _sensorDisplay.name = _sensor.id; - if(_connectionEstablished && _connectionEstablished != _connectionEstablishedPrevious) + if (_connectionEstablished && _connectionEstablished != _connectionEstablishedPrevious) ConnectionEstablishedRoutine(); _connectionEstablishedPrevious = _connectionEstablished; } diff --git a/Assets/MirageXR/Player/Scripts/Behaviours/ThingBehaviour.cs b/Assets/MirageXR/Player/Scripts/Behaviours/ThingBehaviour.cs index 9b2dbfc05..af327a8f9 100644 --- a/Assets/MirageXR/Player/Scripts/Behaviours/ThingBehaviour.cs +++ b/Assets/MirageXR/Player/Scripts/Behaviours/ThingBehaviour.cs @@ -31,11 +31,11 @@ public void HideGuides() // transform.GetComponentInChildren(true).IsVisible = false; } - private void Delete () + private void Delete() { - Destroy (gameObject); + Destroy(gameObject); } - + /// /// Show content stored inside this thing. /// @@ -46,7 +46,7 @@ private void ShowContent() rend.enabled = true; } - foreach (var coll in transform.GetComponentsInChildren ()) + foreach (var coll in transform.GetComponentsInChildren()) { coll.enabled = true; } @@ -57,12 +57,12 @@ private void ShowContent() /// private void HideContent() { - foreach (var rend in transform.GetComponentsInChildren ()) + foreach (var rend in transform.GetComponentsInChildren()) { rend.enabled = false; } - foreach (var coll in transform.GetComponentsInChildren ()) + foreach (var coll in transform.GetComponentsInChildren()) { coll.enabled = false; } diff --git a/Assets/MirageXR/Player/Scripts/Character Aug/CharacterController.cs b/Assets/MirageXR/Player/Scripts/Character Aug/CharacterController.cs index a1cf626d2..8d1ccdafc 100644 --- a/Assets/MirageXR/Player/Scripts/Character Aug/CharacterController.cs +++ b/Assets/MirageXR/Player/Scripts/Character Aug/CharacterController.cs @@ -33,7 +33,8 @@ public class CharacterController : MirageXRPrefab // Animation variables private bool animationClipPlaying; private bool animationPlayedOnce; - public bool CharacterParsed { + public bool CharacterParsed + { get; private set; } @@ -82,15 +83,15 @@ public bool IsImageAssignModeActive } // Check the character gender - private List _maleNames = new List{ "Boy_A", "Boy_B", "Boy_C", "Fridolin", "Man_A", "Man_B", "Man_C", "Alien" }; + private List _maleNames = new List { "Boy_A", "Boy_B", "Boy_C", "Fridolin", "Man_A", "Man_B", "Man_C", "Alien" }; private bool IAmMale { get { if (_maleNames.Find(n => n.Contains(name.Replace("char:", "").Replace("(Clone)", ""))) != null) - return true; + return true; else - return false; + return false; } } @@ -161,7 +162,7 @@ public override bool Init(ToggleObject obj) private async void Start() { Subscribe(); - + // The folder where character data will be saved in characterDataFolder = Path.Combine(activityManager.ActivityPath, "characterinfo"); @@ -169,8 +170,7 @@ private async void Start() _pathNodesColor = new Color( UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), - UnityEngine.Random.Range(0f, 1f) - ); + UnityEngine.Random.Range(0f, 1f)); var objectManipulator = transform.parent.GetComponent(); if (objectManipulator) @@ -187,13 +187,13 @@ private async void Start() var cam = Camera.main; if (cam.GetComponentInChildren() == null) { - var navmeshObstaclePrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/NavmeshObstacle"); - if(navmeshObstaclePrefab != null) + var navmeshObstaclePrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/NavmeshObstacle"); + if (navmeshObstaclePrefab != null) { var navmeshObstacle = Instantiate(navmeshObstaclePrefab, cam.transform.position, cam.transform.rotation); navmeshObstacle.transform.SetParent(cam.transform); } - + } } @@ -206,8 +206,8 @@ private async void OnEnable() _agent = GetComponent(); // create the character setting - var characterSettingPrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/CharacterSettingPanel"); - if(characterSettingPrefab != null) + var characterSettingPrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/CharacterSettingPanel"); + if (characterSettingPrefab != null) { var spawnPoint = transform.Find("UISpawnPoint"); _characterSetting = Instantiate(characterSettingPrefab, spawnPoint.position, spawnPoint.rotation).GetComponent(); @@ -227,7 +227,7 @@ private async void OnEnable() // create image container var imageContainerPrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/PictureContainer"); - if(imageContainerPrefab != null) + if (imageContainerPrefab != null) { imageContainer = Instantiate(imageContainerPrefab, Vector3.zero, Quaternion.identity); imageContainer.transform.SetParent(transform.Find("CharacterGroup").transform); @@ -324,7 +324,7 @@ private void OnToggleObjectActivated(ToggleObject toggleObject, bool value) SaveJson(); } } - + /// /// Check that there is an audio editor present and, if not, create one. /// @@ -346,8 +346,8 @@ public async void AudioEditorCheck(bool forceRemove = false) } else { - var audioEditorPrefab = await ReferenceLoader.GetAssetReferenceAsync("EditorPanels/AudioEditor"); - if(audioEditorPrefab != null) + var audioEditorPrefab = await ReferenceLoader.GetAssetReferenceAsync("EditorPanels/AudioEditor"); + if (audioEditorPrefab != null) { var audioEditorObject = Instantiate(audioEditorPrefab, transform, true); MyAudioEditor = audioEditorObject.GetComponent(); @@ -360,14 +360,15 @@ private void FixedUpdate() if (!CharacterParsed) return; - if (this == null) { + if (this == null) + { StopAllCoroutines(); return; } triggerDuration = DialogRecorder.DialogLength() >= animationLength ? DialogRecorder.DialogLength() : animationLength; - if (!_anim || !_agent || MovementType == string.Empty || !CharacterParsed ) return; + if (!_anim || !_agent || MovementType == string.Empty || !CharacterParsed) return; // Deactivate the animation selector if movement is follow path and loop is on animationMenu.interactable = !(AgentReturnAtTheEnd && !movementManger.FollowPlayer.isOn); @@ -383,11 +384,11 @@ private void FixedUpdate() _agent.updatePosition = true; // start walking animation a bit after moving - if(Vector3.Distance(charPosXZ, destinationPosXZ) > _agent.stoppingDistance + 0.1f) + if (Vector3.Distance(charPosXZ, destinationPosXZ) > _agent.stoppingDistance + 0.1f) PlayClip("Walk"); // if image display is playing stop the particles and hide the image - if(animationClipPlaying) + if (animationClipPlaying) StartCoroutine(OnImageDisplayIntro(false)); } else @@ -430,7 +431,7 @@ private async void AddWatsonAssistant() } // Create a new Watson assistant for this character - var watsonServicePrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/IBMWatsonAssistant"); + var watsonServicePrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/IBMWatsonAssistant"); if (watsonServicePrefab != null) { watsonService = Instantiate(watsonServicePrefab, Vector3.zero, Quaternion.Euler(0, 180, 0)); @@ -493,7 +494,7 @@ private void OnTriggerValueChanged() private IEnumerator WaitForMovementType() { // wait until the movement type is set - while(MovementType == string.Empty) + while (MovementType == string.Empty) { yield return null; } @@ -554,7 +555,7 @@ public async void FollowPlayer() { Destinations = new List(); var destinationPrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/CharacterDestination"); - if(destinationPrefab != null) + if (destinationPrefab != null) { var des = Instantiate(destinationPrefab, transform.position, Quaternion.identity); des.GetComponent().MyCharacter = this; @@ -590,7 +591,7 @@ private Tuple PrepareNodesToSave() for (int i = 0; i < Destinations.Count; i++) { var desNode = Destinations[i].transform; - //create a point from this des point + //create a point from this des point points[i] = new Point(i, desNode.localPosition, desNode.localRotation, Destinations[i].name); } @@ -646,9 +647,9 @@ public void SaveJson() // Each time we call this method the json file will be regenrated with all steps settings the: // save the active step settings for the character - if(step.actionId == activityManager.ActiveActionId) + if (step.actionId == activityManager.ActiveActionId) { - var(destinationPoints, movementType) = PrepareNodesToSave(); + var (destinationPoints, movementType) = PrepareNodesToSave(); step.movementType = movementType; step.destinations = destinationPoints; //null if not followpath step.animationType = animationMenu.options[animationMenu.value].text; //TODO: possible Out Of Range Error @@ -744,7 +745,7 @@ public void SaveJson() var manifestFilePath = $"{Application.dataPath}/MirageXR/Common/AssetBundles/{_myObj.option}.manifest"; var bundleFilePath = $"{Application.dataPath}/MirageXR/Common/AssetBundles/{_myObj.option}"; if (File.Exists(manifestFilePath)) - File.Copy(manifestFilePath , assetBundlePath + ".manifest"); + File.Copy(manifestFilePath, assetBundlePath + ".manifest"); if (File.Exists(bundleFilePath)) File.Copy(bundleFilePath, assetBundlePath); } @@ -830,7 +831,7 @@ private IEnumerator DoOnEndOFPath() SelectClip(); DialogRecorder.PlayDialog(); var yRot = Destinations.LastOrDefault().transform.localRotation.y; - transform.parent.localRotation = Quaternion.Euler(0, yRot , 0); + transform.parent.localRotation = Quaternion.Euler(0, yRot, 0); } private async Task CheckIndex(int index, bool backNow) @@ -874,7 +875,7 @@ private void OnAnimationLoopToggle() { if (!CharacterParsed) return; - if (_characterSetting.AnimationLoopToggle.isOn) animationClipPlaying = false; + if (_characterSetting.AnimationLoopToggle.isOn) animationClipPlaying = false; AnimationLoop = _characterSetting.AnimationLoopToggle.isOn; } @@ -882,7 +883,7 @@ private void OnAnimationClipChanged() { if (!CharacterParsed) return; - StartCoroutine(OnImageDisplayIntro(true)); + StartCoroutine(OnImageDisplayIntro(true)); animationClipPlaying = false; } @@ -910,7 +911,7 @@ public async void SelectClip(string clip = null) { var animationIntValue = await GetAnimationMenuValue(AnimationType); - if (animationIntValue != 9999) //TODO: remove magic number + if (animationIntValue != 9999) //TODO: remove magic number { animationMenu.value = animationIntValue; } @@ -944,7 +945,7 @@ public async void SelectClip(string clip = null) animationClipPlaying = true; var time = 0f; - if(_anim != null) + if (_anim != null) foreach (var animationClip in _anim.runtimeAnimatorController.animationClips) { if (animationClip.name == AnimationType) @@ -958,7 +959,7 @@ public async void SelectClip(string clip = null) //Do not wait for idle because the idle is default one anyway if (AnimationType != "Idle") { - await Task.Delay((int) (time * 1000)); + await Task.Delay((int)(time * 1000)); } if (!_characterSetting.AnimationLoopToggle.isOn && AnimationType != _characterSetting.defaultImageDisplayAnimationName) @@ -973,7 +974,7 @@ public async void SelectClip(string clip = null) private async Task GetAnimationMenuValue(string clipName) { int num = 9999; - for (int i = 0; i < animationMenu.options.Count; i++) + for (int i = 0; i < animationMenu.options.Count; i++) { var option = animationMenu.options[i].text; if (option == clipName) @@ -997,7 +998,7 @@ private void DestroyDestinationsOnDisable() } } - public async Task ActivateCharacterOnEnable() + public async Task ActivateCharacterOnEnable() { var characterLoaded = false; //if any character path has been found parse it @@ -1011,7 +1012,7 @@ public async Task ActivateCharacterOnEnable() return characterLoaded; } - private void SetEditModeState(bool editModeActive) + private void SetEditModeState(bool editModeActive) { //hilde all nodes(the root object of node, Destination.cs, will not be deactivated) foreach (var des in Destinations) @@ -1037,7 +1038,7 @@ private void SetEditModeState(bool editModeActive) //disable all bound box Destinations.ForEach(d => d.GetComponent().Active = false); } - else + else { if (DialogRecorder) { @@ -1047,10 +1048,10 @@ private void SetEditModeState(bool editModeActive) } //enable boundbox of the last node - Destinations[Destinations.Count-1].GetComponent ().Active = true; + Destinations[Destinations.Count - 1].GetComponent().Active = true; } } - + /// /// parse the destination nodes that character should follow /// @@ -1124,11 +1125,11 @@ public async Task ParseCharacters(string jsonPath) movementManger.PathLoop.isOn = destinationPoint.returnPath; movementManger.FollowPlayer.isOn = movementType == "followplayer"; - //and if the destinations are still not created + //and if the destinations are still not created if (movementType == "followpath") { var nodePrefab = await ReferenceLoader.GetAssetReferenceAsync("Characters/CharacterDestination"); - if(nodePrefab != null) + if (nodePrefab != null) { foreach (Point desPoint in destinationPoint.points) { @@ -1250,7 +1251,7 @@ private IEnumerator MoveMyImage(GameObject img, ToggleObject annotation) while (img != null && MyImageAnnotation == annotation) { img.transform.position = imageContainer.transform.GetChild(0).position; - img.transform.rotation = imageContainer.transform.GetChild(0).rotation * Quaternion.Euler(90,0,0); + img.transform.rotation = imageContainer.transform.GetChild(0).rotation * Quaternion.Euler(90, 0, 0); img.transform.localScale = imageContainer.transform.localScale; yield return null; } @@ -1422,7 +1423,7 @@ public class Point public Quaternion rotation; public string name; - public Point(int index, Vector3 pos,Quaternion rot, string name) + public Point(int index, Vector3 pos, Quaternion rot, string name) { this.index = index; this.position = pos; diff --git a/Assets/MirageXR/Player/Scripts/Character Aug/CharacterSettings.cs b/Assets/MirageXR/Player/Scripts/Character Aug/CharacterSettings.cs index 7f5df8c3f..482dbb113 100644 --- a/Assets/MirageXR/Player/Scripts/Character Aug/CharacterSettings.cs +++ b/Assets/MirageXR/Player/Scripts/Character Aug/CharacterSettings.cs @@ -43,7 +43,7 @@ private void Start() AddHoverGuide(aiToggle.gameObject, "Select for artificial intelligence mode. The dialogue can be set by changing the assistant ID in the character model JSON in the LMS. AI can be activated only for one of the existing characters in this action step."); AddHoverGuide(preRecordToggle.gameObject, "If enabled, you are able to record an audio and the character will play it as a dialogue."); - animationMenu.onValueChanged.AddListener(delegate{ OnAnimationMenuOOptionChanged(); }); + animationMenu.onValueChanged.AddListener(delegate { OnAnimationMenuOOptionChanged(); }); trigger.onValueChanged.AddListener(delegate { OnTriggerValueChanged(); }); aiToggle.onValueChanged.AddListener(delegate { OnAiToggleValueChanged(); }); preRecordToggle.onValueChanged.AddListener(delegate { OnPreRecordToggleValueChanged(); }); diff --git a/Assets/MirageXR/Player/Scripts/Character Aug/Destination.cs b/Assets/MirageXR/Player/Scripts/Character Aug/Destination.cs index 60e7167bc..d8a308feb 100644 --- a/Assets/MirageXR/Player/Scripts/Character Aug/Destination.cs +++ b/Assets/MirageXR/Player/Scripts/Character Aug/Destination.cs @@ -50,7 +50,7 @@ void ManipulationStarted() void ManipulationEnded() { - MyCharacter.AnyNodeMoving = false; + MyCharacter.AnyNodeMoving = false; MyCharacter.AnimationClipPlaying(false); } @@ -60,8 +60,8 @@ void ManipulationEnded() private void AvoidSpatialCover() { if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 1, LayerMask.NameToLayer("Spatial Awareness"))) - if(Mathf.Abs(hit.point.y - transform.position.y) < 0.01f) - gameObject.transform.localPosition += new Vector3(0,0.2f,0); + if (Mathf.Abs(hit.point.y - transform.position.y) < 0.01f) + gameObject.transform.localPosition += new Vector3(0, 0.2f, 0); } @@ -123,7 +123,7 @@ private void FixedUpdate() if (MyCharacter.Destinations.Count == 1) { // The character position when there is only one node - if(MyCharacter.MovementType != "followplayer") + if (MyCharacter.MovementType != "followplayer") { MyCharacter.GetComponent().updatePosition = false; MyCharacter.transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, transform.localPosition.z); @@ -133,7 +133,7 @@ private void FixedUpdate() } // last node decides the rotation of the character - else if ( MyCharacter.Destinations[MyCharacter.Destinations.Count - 1] == gameObject && + else if (MyCharacter.Destinations[MyCharacter.Destinations.Count - 1] == gameObject && Vector3.Distance(charPosXZ, MyPosXZ) <= MyCharacter.Agent.stoppingDistance && MyCharacter.transform.localRotation != transform.localRotation) MyCharacter.transform.localRotation = Quaternion.Lerp(MyCharacter.transform.localRotation, transform.localRotation, 0.5f); @@ -175,7 +175,7 @@ public void DeleteNode() MyCharacter.FollowThePath(MyCharacter.Destinations.Count - 1, false); // activate bounding of the last node - MyCharacter.Destinations[MyCharacter.Destinations.Count-1].GetComponent().Active = true; + MyCharacter.Destinations[MyCharacter.Destinations.Count - 1].GetComponent().Active = true; // delete this node Destroy(gameObject); diff --git a/Assets/MirageXR/Player/Scripts/Character Aug/DialogRecorder.cs b/Assets/MirageXR/Player/Scripts/Character Aug/DialogRecorder.cs index 866f2a1b7..e339976b4 100644 --- a/Assets/MirageXR/Player/Scripts/Character Aug/DialogRecorder.cs +++ b/Assets/MirageXR/Player/Scripts/Character Aug/DialogRecorder.cs @@ -30,7 +30,8 @@ public float DialogLength() return _audioSource.clip.length; } - public string DialogSaveName { + public string DialogSaveName + { get; set; } @@ -63,7 +64,7 @@ private void Init() // For character who has lipsync the audio source is added to the object with ThreeLSControl component var threeLSControl = MyCharacter.GetComponentInChildren(); - if(threeLSControl) + if (threeLSControl) { _audioSource = threeLSControl.GetComponent(); } @@ -75,7 +76,7 @@ private void Init() MyCharacter.GetComponent().AudioEditorCheck(); _audioEditor = MyCharacter.MyAudioEditor; - if(_audioEditor != null) + if (_audioEditor != null) { _audioEditor.DialogRecorderPanel = this; _audioSource.loop = LoopToggle.isOn; @@ -122,7 +123,7 @@ private void SetEditorState(bool editModeActive) public void UpdateLoopStatus() { - if(_audioSource) + if (_audioSource) _audioSource.loop = LoopToggle.isOn; } @@ -131,7 +132,7 @@ public void OpenDialogRecorder() if (_audioSource == null) return; // if a dialog is already recorded - if(_audioSource.clip == null) + if (_audioSource.clip == null) { recordButton.SetActive(activityManager.EditModeActive); stopButton.SetActive(!activityManager.EditModeActive); @@ -164,7 +165,7 @@ public void CloseDialogRecorder() closeButton.SetActive(false); LoopToggle.gameObject.SetActive(false); - if(_audioEditor) + if (_audioEditor) _audioEditor.Close(); } @@ -190,7 +191,7 @@ private bool AllowToRecord() if (AIIsActiveInThisScene) { - /// give the info and close + // give the info and close DialogWindow.Instance.Show("Info!", "For recordeing an audio, you need to deactivate AI on all characters in this step.", new DialogButtonContent("Ok")); @@ -199,7 +200,7 @@ private bool AllowToRecord() if (RecordingIsActiveInThisScene) { - /// give the info and close + // give the info and close DialogWindow.Instance.Show("Info!", "You are recording audio using another character. Please stop recording there first.", new DialogButtonContent("Ok")); @@ -237,8 +238,8 @@ public void StopDialogRecording() { _audioSource.Stop(); isPlaying = false; - } - else if(isRecording) + } + else if (isRecording) { _audioEditor.StopRecording(); _audioEditor.OnAccept(); @@ -268,7 +269,7 @@ public void PlayDialog() public void StopDialog() { - if(_audioSource) + if (_audioSource) _audioSource.Stop(); } } diff --git a/Assets/MirageXR/Player/Scripts/Character Aug/EyeBlink.cs b/Assets/MirageXR/Player/Scripts/Character Aug/EyeBlink.cs index cd3922be3..102c6825c 100644 --- a/Assets/MirageXR/Player/Scripts/Character Aug/EyeBlink.cs +++ b/Assets/MirageXR/Player/Scripts/Character Aug/EyeBlink.cs @@ -4,7 +4,7 @@ public class EyeBlink : MonoBehaviour { private SkinnedMeshRenderer skinnedMeshRenderer; - [Range (0,100)] + [Range(0, 100)] [SerializeField] private int DefaultEyeOpenAmount = 10; [SerializeField] private int blinkingBlendIndex = 0; [SerializeField] private float blinkSpeed = 8f; @@ -35,7 +35,7 @@ IEnumerator Blink() _blinking += blinkSpeed; - if(_blinking >= 100) + if (_blinking >= 100) _eyesOpened = true; } @@ -48,8 +48,8 @@ IEnumerator Blink() if (_blinking <= DefaultEyeOpenAmount) { _eyesOpened = false; - yield return new WaitForSeconds(Random.Range(2f / blinkingFreq , 20 / blinkingFreq)); - } + yield return new WaitForSeconds(Random.Range(2f / blinkingFreq, 20 / blinkingFreq)); + } } yield return null; diff --git a/Assets/MirageXR/Player/Scripts/Controllers/AugmentationManager.cs b/Assets/MirageXR/Player/Scripts/Controllers/AugmentationManager.cs index 6f1e37ec7..cb9671f65 100644 --- a/Assets/MirageXR/Player/Scripts/Controllers/AugmentationManager.cs +++ b/Assets/MirageXR/Player/Scripts/Controllers/AugmentationManager.cs @@ -6,141 +6,141 @@ namespace MirageXR { - public class AugmentationManager - { - private const string AUGMENTATION_FORMAT = "AN-{0}"; - private static ActivityManager activityManager => RootObject.Instance.activityManager; - - public ToggleObject AddAugmentation(Action action, Vector3 position) - { - var annotation = new ToggleObject - { - id = action.id, - poi = string.Format(AUGMENTATION_FORMAT, Guid.NewGuid()), - type = ActionType.Tangible, - scale = 1 - }; - - int currentActionIndex = 0; - for (var i = 0; i < activityManager.ActionsOfTypeAction.Count; i++) - { - if (activityManager.ActionsOfTypeAction[i].id == activityManager.ActiveActionId) - { - currentActionIndex = i; - break; - } - } - - AddAllAugmentationsBetweenSteps(currentActionIndex, currentActionIndex, annotation, position); - - return annotation; - } - - public void AddAllAugmentationsBetweenSteps(int startIndex, int endIndex, ToggleObject annotation, Vector3 position) - { - var actionList = activityManager.ActionsOfTypeAction; - //remove the annotation from out of the selected steps range - - for (int i = 0; i < actionList.Count; i++) - { - if (i >= startIndex && i <= endIndex) - { - continue; - } - - var action = actionList[i]; - foreach (var anno in action.enter.activates.FindAll(p => p.poi == annotation.poi)) - { - DeleteAugmentationFromStep(actionList[i], anno); - } - - if (action == activityManager.ActiveAction) - { - EventManager.DeactivateObject(annotation); - } - } - - //add the annotation to the selected steps range if already not exist - for (int i = startIndex; i <= endIndex; i++) - { - if (actionList[i].enter.activates.All(p => p.poi != annotation.poi)) - { - actionList[i].enter.activates.Add(annotation); - } - - if (actionList[i].exit.deactivates.All(p => p.poi != annotation.poi))// also create an exit object (w/out activate options) - { - actionList[i].exit.deactivates.Add(annotation); - } - } - - //the objects of the annotation will be created only for the original step not all steps. - RootObject.Instance.workplaceManager.AddAnnotation(activityManager.ActiveAction, annotation, position); - } - - public void DeleteAugmentation(ToggleObject annotation, Action step = null) - { - var poi = annotation.poi; - - //close all editor before deleting an annotation, some pois like audio throw exception if you delete the file but the editor is open - Object.FindObjectOfType().DisableAllPoiEditors(); - - //delete the annotation form all steps which include the annotation - //annotation does not exist in other step, then delete it and it's files from anywhere - if (step == null) - { - foreach (var actionObj in activityManager.ActionsOfTypeAction) - { - //remove this from triggers - var trigger = actionObj.triggers.Find(t => t.id == poi); - actionObj.triggers.Remove(trigger); - - //remove this from activates - foreach (var anno in actionObj.enter.activates.FindAll(p => p.poi == poi)) - { - DeleteAugmentationFromStep(actionObj, anno); - DeleteAugmentationFile(anno); - RootObject.Instance.workplaceManager.DeleteAugmentation(actionObj, anno); - } - - EventManager.NotifyActionModified(actionObj); - activityManager.SaveData();//save data(annotations) after deleting additional files like character or models data - EventManager.NotifyAugmentationDeleted(annotation);//All augmentations classes should do whatever should be done on augmentation deletion - } - } - else - { - foreach (var anno in step.enter.activates.FindAll(p => p.poi == poi)) - { - DeleteAugmentationFromStep(step, anno); - } - EventManager.NotifyActionModified(step); - - //save data(annotations) after deleting additional files like character or models data - activityManager.SaveData(); - } - } - - public void DeleteAugmentationFromStep(Action action, ToggleObject annotation) - { - action.enter.activates.Remove(annotation); - action.exit.deactivates.Remove(annotation); - } - - private static void DeleteAugmentationFile(ToggleObject annotation) - { - const string httpPrefix = "http://"; - - var filePath = annotation.url; - if (filePath.StartsWith(httpPrefix)) - { - filePath = filePath.Remove(0, httpPrefix.Length); - } - var localFilePath = Path.Combine(activityManager.ActivityPath, Path.GetFileName(filePath)); - if (File.Exists(localFilePath)) - { - File.Delete(localFilePath); - } - } - } + public class AugmentationManager + { + private const string AUGMENTATION_FORMAT = "AN-{0}"; + private static ActivityManager activityManager => RootObject.Instance.activityManager; + + public ToggleObject AddAugmentation(Action action, Vector3 position) + { + var annotation = new ToggleObject + { + id = action.id, + poi = string.Format(AUGMENTATION_FORMAT, Guid.NewGuid()), + type = ActionType.Tangible, + scale = 1 + }; + + int currentActionIndex = 0; + for (var i = 0; i < activityManager.ActionsOfTypeAction.Count; i++) + { + if (activityManager.ActionsOfTypeAction[i].id == activityManager.ActiveActionId) + { + currentActionIndex = i; + break; + } + } + + AddAllAugmentationsBetweenSteps(currentActionIndex, currentActionIndex, annotation, position); + + return annotation; + } + + public void AddAllAugmentationsBetweenSteps(int startIndex, int endIndex, ToggleObject annotation, Vector3 position) + { + var actionList = activityManager.ActionsOfTypeAction; + //remove the annotation from out of the selected steps range + + for (int i = 0; i < actionList.Count; i++) + { + if (i >= startIndex && i <= endIndex) + { + continue; + } + + var action = actionList[i]; + foreach (var anno in action.enter.activates.FindAll(p => p.poi == annotation.poi)) + { + DeleteAugmentationFromStep(actionList[i], anno); + } + + if (action == activityManager.ActiveAction) + { + EventManager.DeactivateObject(annotation); + } + } + + //add the annotation to the selected steps range if already not exist + for (int i = startIndex; i <= endIndex; i++) + { + if (actionList[i].enter.activates.All(p => p.poi != annotation.poi)) + { + actionList[i].enter.activates.Add(annotation); + } + + if (actionList[i].exit.deactivates.All(p => p.poi != annotation.poi)) // also create an exit object (w/out activate options) + { + actionList[i].exit.deactivates.Add(annotation); + } + } + + //the objects of the annotation will be created only for the original step not all steps. + RootObject.Instance.workplaceManager.AddAnnotation(activityManager.ActiveAction, annotation, position); + } + + public void DeleteAugmentation(ToggleObject annotation, Action step = null) + { + var poi = annotation.poi; + + //close all editor before deleting an annotation, some pois like audio throw exception if you delete the file but the editor is open + Object.FindObjectOfType().DisableAllPoiEditors(); + + //delete the annotation form all steps which include the annotation + //annotation does not exist in other step, then delete it and it's files from anywhere + if (step == null) + { + foreach (var actionObj in activityManager.ActionsOfTypeAction) + { + //remove this from triggers + var trigger = actionObj.triggers.Find(t => t.id == poi); + actionObj.triggers.Remove(trigger); + + //remove this from activates + foreach (var anno in actionObj.enter.activates.FindAll(p => p.poi == poi)) + { + DeleteAugmentationFromStep(actionObj, anno); + DeleteAugmentationFile(anno); + RootObject.Instance.workplaceManager.DeleteAugmentation(actionObj, anno); + } + + EventManager.NotifyActionModified(actionObj); + activityManager.SaveData(); //save data(annotations) after deleting additional files like character or models data + EventManager.NotifyAugmentationDeleted(annotation); //All augmentations classes should do whatever should be done on augmentation deletion + } + } + else + { + foreach (var anno in step.enter.activates.FindAll(p => p.poi == poi)) + { + DeleteAugmentationFromStep(step, anno); + } + EventManager.NotifyActionModified(step); + + //save data(annotations) after deleting additional files like character or models data + activityManager.SaveData(); + } + } + + public void DeleteAugmentationFromStep(Action action, ToggleObject annotation) + { + action.enter.activates.Remove(annotation); + action.exit.deactivates.Remove(annotation); + } + + private static void DeleteAugmentationFile(ToggleObject annotation) + { + const string httpPrefix = "http://"; + + var filePath = annotation.url; + if (filePath.StartsWith(httpPrefix)) + { + filePath = filePath.Remove(0, httpPrefix.Length); + } + var localFilePath = Path.Combine(activityManager.ActivityPath, Path.GetFileName(filePath)); + if (File.Exists(localFilePath)) + { + File.Delete(localFilePath); + } + } + } } diff --git a/Assets/MirageXR/Player/Scripts/DebugHelpers/DummyLogic.cs b/Assets/MirageXR/Player/Scripts/DebugHelpers/DummyLogic.cs index 04553479b..1079e3e39 100644 --- a/Assets/MirageXR/Player/Scripts/DebugHelpers/DummyLogic.cs +++ b/Assets/MirageXR/Player/Scripts/DebugHelpers/DummyLogic.cs @@ -1,8 +1,6 @@ -using System.Collections; -using System.Threading.Tasks; -using UnityEngine; +using System.Threading.Tasks; using MirageXR; -using TiltBrush; +using UnityEngine; /// /// Just used for MirageXR player testing. @@ -14,17 +12,17 @@ public class DummyLogic : MonoBehaviour [SerializeField] private GameObject SensorState; - private void OnEnable () + private void OnEnable() { EventManager.OnPlayerReset += PlayerReset; } - private void OnDisable () + private void OnDisable() { EventManager.OnPlayerReset -= PlayerReset; } - private void PlayerReset () + private void PlayerReset() { // SensorState.SetActive (false); } @@ -32,18 +30,18 @@ private void PlayerReset () /// /// Load activity file. /// - private Task LoadActivity () + private Task LoadActivity() { // First load. Uses the default activity. - if (string.IsNullOrEmpty (PlayerPrefs.GetString ("activityUrl"))) + if (string.IsNullOrEmpty(PlayerPrefs.GetString("activityUrl"))) { // Save to persistent storage. - PlayerPrefs.SetString ("activityUrl", _activityURL); - PlayerPrefs.Save (); + PlayerPrefs.SetString("activityUrl", _activityURL); + PlayerPrefs.Save(); } // Get the activity url from persistent storage. - var activity = PlayerPrefs.GetString ("activityUrl"); + var activity = PlayerPrefs.GetString("activityUrl"); // For VTT demos that are using the IoT functionality. switch (activity) @@ -51,32 +49,32 @@ private Task LoadActivity () // Enable the sensor state display object for VTT demos. case "resources://vttdemoactivity": case "http://192.168.0.1/activities/new_activity.json": - SensorState.SetActive (true); + SensorState.SetActive(true); break; - + // Disable the sensor state object for all the other activities. default: - SensorState.SetActive (false); + SensorState.SetActive(false); break; } - return activityManager.LoadActivity(PlayerPrefs.GetString ("activityUrl")); + return activityManager.LoadActivity(PlayerPrefs.GetString("activityUrl")); } // Use this for initialization - private void Start () + private void Start() { activityManager.LoadActivity("http://192.168.0.1/activities/AltecTrialActivity.json").AsAsyncVoid(); // LoadActivity (); - + // EventManager.ParseActivity ("resources://scenario0_activity"); - + // EventManager.ParseActivity ("resources://vttdemoactivity"); - + // Start the process by loading an activity file from server... // EventManager.ParseActivity ("https://dl.dropboxusercontent.com/s/vuw23fi2v88wj33/altec_activity.json"); - + // ...or from the inbuilt resources folder. // EventManager.ParseActivity ("resources://ebit_activity"); // EventManager.ParseActivity ("resources://altec_activity"); @@ -91,60 +89,60 @@ private void Start () /// /// Load VTT Demo activity. /// - public void VttDemoMode () + public void VttDemoMode() { // Load the VTT Demo trial activity. - PlayerPrefs.SetString ("activityUrl", "resources://vttdemoactivity"); - PlayerPrefs.Save (); - Maggie.Speak ("Loading VTT Demo Activity"); + PlayerPrefs.SetString("activityUrl", "resources://vttdemoactivity"); + PlayerPrefs.Save(); + Maggie.Speak("Loading VTT Demo Activity"); RootObject.Instance.activityManager.PlayerReset().AsAsyncVoid(); } /// /// Load Lufttransport trial activity. /// - public void LuftTrialMode () + public void LuftTrialMode() { // Load the Lufttransport trial activity. - PlayerPrefs.SetString ("activityUrl", "resources://lt_activity"); - PlayerPrefs.Save (); - Maggie.Speak ("Loading Lufttransport Trial Activity"); + PlayerPrefs.SetString("activityUrl", "resources://lt_activity"); + PlayerPrefs.Save(); + Maggie.Speak("Loading Lufttransport Trial Activity"); RootObject.Instance.activityManager.PlayerReset().AsAsyncVoid(); } /// /// Load ALTEC trial activity. /// - public void AltecTrialMode () + public void AltecTrialMode() { // Load the ALTEC trial activity. - PlayerPrefs.SetString ("activityUrl", "resources://altec_activity"); - PlayerPrefs.Save (); - Maggie.Speak ("Loading ALTEC Trial Activity"); + PlayerPrefs.SetString("activityUrl", "resources://altec_activity"); + PlayerPrefs.Save(); + Maggie.Speak("Loading ALTEC Trial Activity"); RootObject.Instance.activityManager.PlayerReset().AsAsyncVoid(); } /// /// Load Ebit trial activity. /// - public void EbitTrialMode () + public void EbitTrialMode() { // Load the Ebit trial activity. - PlayerPrefs.SetString ("activityUrl", "resources://ebit_activity"); - PlayerPrefs.Save (); - Maggie.Speak ("Loading Ebit Trial Activity"); + PlayerPrefs.SetString("activityUrl", "resources://ebit_activity"); + PlayerPrefs.Save(); + Maggie.Speak("Loading Ebit Trial Activity"); RootObject.Instance.activityManager.PlayerReset().AsAsyncVoid(); } /// /// Load ESA Demo activity. /// - public void EsaDemoActivity () + public void EsaDemoActivity() { // Load the ESA Demo activity. - PlayerPrefs.SetString ("activityUrl", "http://192.168.0.1/activities/new_activity.json"); - PlayerPrefs.Save (); - Maggie.Speak ("Loading ESA Demo Activity"); + PlayerPrefs.SetString("activityUrl", "http://192.168.0.1/activities/new_activity.json"); + PlayerPrefs.Save(); + Maggie.Speak("Loading ESA Demo Activity"); RootObject.Instance.activityManager.PlayerReset().AsAsyncVoid(); } diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/DaimonManager.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/DaimonManager.cs index ce204b997..c034313c5 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/DaimonManager.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/DaimonManager.cs @@ -5,21 +5,23 @@ public class DaimonManager : MonoBehaviour { + private static MirageXR.ActivityManager activityManager => MirageXR.RootObject.Instance.activityManager; public SpeechInputService mySpeechInputMgr { get; private set; } private SpeechOutputService mySpeechOutputMgr; - public GameObject myCharacter { get; set; } - private Animator myAnimator; - + public GameObject myCharacter { get; set; } + private Animator myAnimator; + public GameObject[] lookTargets { get; private set; } private Dictionary _context = null; private bool _waitingForResponse = true; - public float wait = 0.0f; + public float wait = 0.0f; //currently no wait, may require a fix public bool check = false; public bool play = false; + public bool triggerNext = false; @@ -28,7 +30,7 @@ void Start() { mySpeechInputMgr = GetComponent(); mySpeechOutputMgr = GetComponent(); - myAnimator = myCharacter.GetComponent(); + myAnimator = myCharacter.GetComponent(); } @@ -53,12 +55,18 @@ void Update() } if ((wait < 0f) && (check)) - { + { - //check that clip is not playing - Debug.Log ("-------------------- Speech Output has finished playing, now reactivating SpeechInput."); + //check that clip is not playing + Debug.Log("-------------------- Speech Output has finished playing, now reactivating SpeechInput."); check = false; + if (triggerNext) + { + triggerNext = false; + activityManager.ActivateNextAction(); + } + //Now let's start listening again..... mySpeechInputMgr.Active = true; mySpeechInputMgr.StartRecording(); @@ -69,19 +77,21 @@ void Update() // check for exercise name (from ExerciseController.cs) // and run the according animation (in myAnimator) - public void Animate( string exercise ) { - - switch (exercise) { - case "B12": - myAnimator.Play("BreathingIdle"); - break; + public void Animate(string exercise) + { + + switch (exercise) + { + case "B12": + myAnimator.Play("BreathingIdle"); + break; case "waving": myAnimator.Play("waving"); break; - default: - break; - } - - } - + default: + break; + } + + } + } diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/DialogueService.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/DialogueService.cs index a896592d6..c659d402b 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/DialogueService.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/DialogueService.cs @@ -1,13 +1,11 @@ -using System.Collections; -using UnityEngine; -using UnityEngine.UI; -using IBM.Cloud.SDK.Utilities; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Utilities; using IBM.Watson.Assistant.V2; using IBM.Watson.Assistant.V2.Model; using System; -using System.Linq; -using System; +using System.Collections; +using UnityEngine; +using UnityEngine.UI; public class DialogueService : MonoBehaviour { @@ -16,11 +14,11 @@ public class DialogueService : MonoBehaviour private SpeechOutputService dSpeechOutputMgr; private SpeechInputService dSpeechInputMgr; - private UserProfile dUser; - private ExerciseController dEC; + private UserProfile dUser; + private ExerciseController dEC; private MirageXR.CharacterController _character; - + private static MirageXR.ActivityManager activityManager => MirageXR.RootObject.Instance.activityManager; [Space(10)] // [Tooltip("The IAM apikey.")] @@ -32,12 +30,12 @@ public class DialogueService : MonoBehaviour [Tooltip("The version date with which you would like to use the service in the form YYYY-MM-DD.")] [SerializeField] - private string versionDate = "2019-02-28"; + private string versionDate = "2019-02-28";//"2021-11-27" [Tooltip("The assistantId to run the example.")] [SerializeField] - private string assistantId = "b392e763-cfde-44c4-b24a-275c92fc4f9b"; + private string assistantId = "b392e763-cfde-44c4-b24a-275c92fc4f9b"; private AssistantService service; - private DaimonManager dAImgr; + private DaimonManager dAImgr; private string username; @@ -63,9 +61,9 @@ void Start() LogSystem.InstallDefaultReactors(); dSpeechOutputMgr = GetComponent(); - dAImgr = GetComponent(); - dUser = GetComponent(); - dEC = GetComponent(); + dAImgr = GetComponent(); + dUser = GetComponent(); + dEC = GetComponent(); dSpeechInputMgr = GetComponent(); dSpeechInputMgr.onInputReceived += OnInputReceived; @@ -78,7 +76,7 @@ void Start() private IEnumerator CreateService() { - /* + /* if (string.IsNullOrEmpty(iamApikey)) { throw new IBMException("Please provide IAM ApiKey for the service."); @@ -102,9 +100,9 @@ private IEnumerator CreateService() service = new AssistantService(versionDate); // , credentials); - while (!service.Authenticator.CanAuthenticate()) // .Credentials.HasIamTokenData() + while (!service.Authenticator.CanAuthenticate()) // .Credentials.HasIamTokenData() yield return null; - + Runnable.Run(CreateSession()); // Runnable.Run(Examples()); @@ -112,7 +110,7 @@ private IEnumerator CreateService() private IEnumerator CreateSession() { - Debug.Log("CONNECTING TO ASSISTANT: " + assistantId); + Debug.Log("CONNECTING TO ASSISTANT: " + assistantId); service.CreateSession(OnCreateSession, assistantId); while (!createSessionTested) @@ -151,19 +149,22 @@ public void SendMessageToAssistant(string theText) } - private void MakeDance() + + private void NextStep() { - Debug.LogError(">>> Starting to dance"); - //dAImgr.Animate("Waving"); + + activityManager.ActivateNextAction(); + } private void OnResponseReceived(DetailedResponse response, IBMError error) { - if (response.Result.Output.Generic != null && response.Result.Output.Generic.Count > 0) { - Debug.Log("DialogueService response: " + response.Result.Output.Generic[0].Text); - if (response.Result.Output.Intents.Capacity > 0) Debug.Log(" -> " + response.Result.Output.Intents[0].Intent.ToString()); - } + if (response.Result.Output.Generic != null && response.Result.Output.Generic.Count > 0) + { + Debug.Log("DialogueService response: " + response.Result.Output.Generic[0].Text); + if (response.Result.Output.Intents.Capacity > 0) Debug.Log(" -> " + response.Result.Output.Intents[0].Intent.ToString()); + } // check if Watson was able to make sense of the user input, otherwise ask to repeat the input if (response.Result.Output.Intents == null && response.Result.Output.Actions == null) @@ -171,17 +172,17 @@ private void OnResponseReceived(DetailedResponse response, IBME Debug.Log("I did not understand"); dSpeechOutputMgr.Speak("I don't understand, can you rephrase?"); - } else { + } + else + { if (response.Result.Output.Intents != null && response.Result.Output.Intents.Count > 0) { string answerIntent = response.Result.Output.Intents[0].Intent.ToString(); + // only evaluated if intents are used in dialog switch (answerIntent) { - case "dancing": - MakeDance(); - break; case "S0-GenderMale": // might also be without hashtag? not sure dUser.Gender = UserProfile.gender.male; break; @@ -203,14 +204,14 @@ private void OnResponseReceived(DetailedResponse response, IBME if (response.Result.Output.Actions != null && response.Result.Output.Actions.Count > 0) { - string actionName = response.Result.Output.Actions[0].Name; + Debug.Log("Action Name = " + actionName); // check whether it is really the intent we want to check // (or do we want to know the name of the dialogue step?) switch (actionName) { - case "makeWave": - dAImgr.Animate("waving"); + case "jump to": + Debug.Log("Jump to action recieved"); break; default: break; @@ -220,22 +221,29 @@ private void OnResponseReceived(DetailedResponse response, IBME if (response.Result.Output.Generic != null && response.Result.Output.Generic.Capacity > 0) { - // if the name is char:alla only take alla try { var res = response.Result.Output.Generic[0].Text; - if (!string.IsNullOrEmpty(res) && res.Contains("%%charactername%%")) + if (!string.IsNullOrEmpty(res)) { - var charName = _character.name.Contains(":") ? _character.name.Split(':')[1] : _character.name; - res = res.Replace("%%charactername%%", charName); + if (res.Contains("%%charactername%%")) + { + var charName = _character.name.Contains(":") ? _character.name.Split(':')[1] : _character.name; + res = res.Replace("%%charactername%%", charName); + } + else if (res.Contains("%%trigger%%")) + { + res = res.Replace("%%trigger%%", " "); + dAImgr.mySpeechInputMgr.Active = false; + dAImgr.triggerNext = true; + } + dSpeechOutputMgr.Speak(res); // + ", " + username } else - dAImgr.check = true; - - if(string.IsNullOrEmpty(res)) + { dSpeechOutputMgr.Speak("Sorry, I don't understand."); - - dSpeechOutputMgr.Speak(res); // + ", " + username + dAImgr.check = true; + } } catch (NullReferenceException e) { @@ -244,82 +252,83 @@ private void OnResponseReceived(DetailedResponse response, IBME Debug.LogError($"Somthing went wrong but the conversiontion will be continued. The error is:\n {e}"); } - } else // no Generic response coming back, so say something diplomatic + } + else // no Generic response coming back, so say something diplomatic { dSpeechOutputMgr.Speak("Sorry, I don't understand."); } - + // now all data has been extracted, so we can run through the list of exclusions UpdateExercises(); - } // Watson did understand the user - - } // end of method OnResponseReceived - - //dSpeechInputMgr.Active = false; - - //myTTS.myVoice = "de-DE_DieterV3Voice"; - //myTTS.Speak(myTranslator.lastTranslationResult); - //myTTS.myVoice = "en-GB_KateV3Voice"; - - - // Convert resp to fsdata - //fsData fsdata = null; - //fsResult r = _serializer.TrySerialize(response.GetType(), response, out fsdata); - //if (!r.Succeeded) - // throw new IBMException(r.FormattedMessages); - - //// Convert fsdata to MessageResponse - //MessageResponse messageResponse = new MessageResponse(); - //object obj = messageResponse; - //r = _serializer.TryDeserialize(fsdata, obj.GetType(), ref obj); - //if (!r.Succeeded) - // throw new IBMException(r.FormattedMessages); - - //object _tempContext = null; - //(resp as Dictionary).TryGetValue("context", out _tempContext); - //if (_tempContext != null) - //{ - - // _tempContext = _tempContext as Dictionary; - //} - //else - //{ - // Log.Debug("ExampleConversation.Dialogue()", "Failed to get context"); - //} - - ////object tempIntentsObj = null; - ////(response as Dictionary).TryGetValue("intents", out tempIntentsObj); - - - //object _tempText = null; - //object _tempTextObj = (_tempText as List)[0]; - //string output = _tempTextObj.ToString(); - //if (output != null) - //{ - // //replace any tags with the value expected by the TTS service - // string replaceActionTags = output.ToString(); - // int pos3 = replaceActionTags.IndexOf(""); - // if (pos3 != -1) - // { - // replaceActionTags = output.Replace("", ""); - // } - // int pos4 = replaceActionTags.IndexOf(""); - // if (pos4 != -1) - // { - // replaceActionTags = output.Replace("", ""); - // } - // int pos5 = replaceActionTags.IndexOf(""); - // if (pos5 != -1) - // { - // replaceActionTags = output.Replace("", ""); - // } - // output = replaceActionTags; - //} - //else - //{ - // Log.Debug("Extract outputText", "Failed to extract outputText and set for speaking"); - //} + } // Watson did understand the user + + } // end of method OnResponseReceived + + //dSpeechInputMgr.Active = false; + + //myTTS.myVoice = "de-DE_DieterV3Voice"; + //myTTS.Speak(myTranslator.lastTranslationResult); + //myTTS.myVoice = "en-GB_KateV3Voice"; + + + // Convert resp to fsdata + //fsData fsdata = null; + //fsResult r = _serializer.TrySerialize(response.GetType(), response, out fsdata); + //if (!r.Succeeded) + // throw new IBMException(r.FormattedMessages); + + //// Convert fsdata to MessageResponse + //MessageResponse messageResponse = new MessageResponse(); + //object obj = messageResponse; + //r = _serializer.TryDeserialize(fsdata, obj.GetType(), ref obj); + //if (!r.Succeeded) + // throw new IBMException(r.FormattedMessages); + + //object _tempContext = null; + //(resp as Dictionary).TryGetValue("context", out _tempContext); + //if (_tempContext != null) + //{ + + // _tempContext = _tempContext as Dictionary; + //} + //else + //{ + // Log.Debug("ExampleConversation.Dialogue()", "Failed to get context"); + //} + + ////object tempIntentsObj = null; + ////(response as Dictionary).TryGetValue("intents", out tempIntentsObj); + + + //object _tempText = null; + //object _tempTextObj = (_tempText as List)[0]; + //string output = _tempTextObj.ToString(); + //if (output != null) + //{ + // //replace any tags with the value expected by the TTS service + // string replaceActionTags = output.ToString(); + // int pos3 = replaceActionTags.IndexOf(""); + // if (pos3 != -1) + // { + // replaceActionTags = output.Replace("", ""); + // } + // int pos4 = replaceActionTags.IndexOf(""); + // if (pos4 != -1) + // { + // replaceActionTags = output.Replace("", ""); + // } + // int pos5 = replaceActionTags.IndexOf(""); + // if (pos5 != -1) + // { + // replaceActionTags = output.Replace("", ""); + // } + // output = replaceActionTags; + //} + //else + //{ + // Log.Debug("Extract outputText", "Failed to extract outputText and set for speaking"); + //} public void UpdateExercises() { @@ -344,7 +353,7 @@ public void UpdateExercises() } - public void OnInputReceived(string text ) + public void OnInputReceived(string text) { //Debug.Log("onInputReceived arrived in DialogueService: '" + text + "'"); ResponseTextField.text = text; diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/LangTransService.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/LangTransService.cs index d7994bbac..a795008c1 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/LangTransService.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/LangTransService.cs @@ -35,7 +35,7 @@ private IEnumerator ConnectToTranslationService() { languageTranslatorService = new LanguageTranslatorService(versionDate); - while (!languageTranslatorService.Authenticator.CanAuthenticate()) yield return null; + while (!languageTranslatorService.Authenticator.CanAuthenticate()) yield return null; //Translate("Where is the library"); } diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechInputService.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechInputService.cs index c9502ed6b..149a412b2 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechInputService.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechInputService.cs @@ -1,6 +1,6 @@ /** * Modified by Fridolin/Xinyu -* +* * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -86,7 +86,7 @@ void Start() private IEnumerator CreateService() { /* - + if (string.IsNullOrEmpty(iamApikey)) { throw new IBMException("Please provide IAM ApiKey for the service."); @@ -108,8 +108,8 @@ private IEnumerator CreateService() yield return null; _service = new SpeechToTextService(credentials); - - */ + + */ _service = new SpeechToTextService(); @@ -223,7 +223,7 @@ private IEnumerator RecordingHandler() } else { - // calculate the number of samples remaining until we ready for a block of audio, + // calculate the number of samples remaining until we ready for a block of audio, // and wait that amount of time it will take to record. int remaining = bFirstBlock ? (midPoint - writePos) : (_recording.samples - writePos); float timeRemaining = (float)remaining / (float)_recordingHZ; diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechOutputService.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechOutputService.cs index c7e796047..2cde25aa3 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechOutputService.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/SpeechOutputService.cs @@ -48,10 +48,10 @@ void Start() StartCoroutine(ConnectToTTSService()); } - + private IEnumerator ConnectToTTSService() { - /* + /* TokenOptions myTokenOptions = new TokenOptions() { IamApiKey = apiKey @@ -62,9 +62,9 @@ private IEnumerator ConnectToTTSService() myService = new TextToSpeechService(myCredentials); */ - - myService = new TextToSpeechService(); - while (!myService.Authenticator.CanAuthenticate()) yield return null; // .Credentials.HasIamTokenData() + + myService = new TextToSpeechService(); + while (!myService.Authenticator.CanAuthenticate()) yield return null; // .Credentials.HasIamTokenData() } public void Speak(string text) @@ -76,10 +76,10 @@ public void Speak(string text) callback: onSynthCompleted, text: text, voice: myVoice, - accept: "audio/wav" - ); + accept: "audio/wav"); - } else + } + else { Debug.Log("WARNING: text to speech: text was empty"); } @@ -88,16 +88,16 @@ public void Speak(string text) public void onSynthCompleted(DetailedResponse response, IBMError error) { - + byte[] synthesizeResponse = null; AudioClip clip = null; synthesizeResponse = response.Result; clip = WaveFile.ParseWAV("myClip", synthesizeResponse); - Debug.Log("before playing: " + clip); + Debug.Log("before playing: " + clip); PlayClip(clip); } - private void PlayClip(AudioClip clip) + private void PlayClip(AudioClip clip) { //Debug.Log("Received audio file from Watson Text To Speech"); @@ -116,7 +116,8 @@ private void PlayClip(AudioClip clip) dDaimonMgr.check = true; Debug.Log("Speech output playing, set DaimonMgr waiting time for SpeechInput to reactivate again (when done) after " + clip.length + " seconds"); - } else + } + else { Debug.Log("ERROR: something is already playing or we did not get a clip."); } diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/ToneService.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/ToneService.cs index 0fbec40b1..16706076c 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/ToneService.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/ToneService.cs @@ -30,7 +30,7 @@ public class ToneService : MonoBehaviour [SerializeField] private Text ResultsAnalysis; - //public MeshRenderer MacKenzieRenderer; // main digital human + //public MeshRenderer MacKenzieRenderer; // main digital human // Over the shoulder emotional spheres [SerializeField] private MeshRenderer sphere_emo_joyRenderer; @@ -65,7 +65,7 @@ void Start() emotion_threshold = 0.75f; // for loose demo - above 75% seems to work well - may vary by signal - + } private void OnGetToneAnalyze(ToneService resp, Dictionary customData) @@ -117,7 +117,7 @@ private void OnGetToneAnalyze(ToneService resp, Dictionary custo // OTHER TEXT - Formatting for On Screen dump - LATER - pretty this up to use standard DESERIALIZE methods and table string RAW = (customData["json"].ToString()); // works but long and cannot read - //RAW = string.Concat("Tone Response \n", RAW); + //RAW = string.Concat("Tone Response \n", RAW); RAW = Regex.Replace(RAW, "tone_categories", " \\\n"); RAW = Regex.Replace(RAW, "}", "} \\\n"); RAW = Regex.Replace(RAW, "tone_id", " "); @@ -133,6 +133,6 @@ private void OnGetToneAnalyze(ToneService resp, Dictionary custo // Update is called once per frame void Update() { - + } } diff --git a/Assets/MirageXR/Player/Scripts/IBMWatson/UserProfile.cs b/Assets/MirageXR/Player/Scripts/IBMWatson/UserProfile.cs index b969cbeaf..8fb645ede 100644 --- a/Assets/MirageXR/Player/Scripts/IBMWatson/UserProfile.cs +++ b/Assets/MirageXR/Player/Scripts/IBMWatson/UserProfile.cs @@ -12,7 +12,11 @@ public class UserProfile : MonoBehaviour [SerializeField] private string Name; - public enum gender { male, female }; + public enum gender + { + male, female + } + public gender Gender; public int Age; @@ -24,39 +28,40 @@ public enum gender { male, female }; public enum cancers { - }; + } public cancers CancerType; - public enum Frequency { + public enum Frequency + { threeMonths, threeToSixMonths - }; + } public Frequency PhysicalExerciseFrequency; public Frequency ExerciseFrequency; - public enum feelings {good, bad}; + public enum feelings { good, bad } public feelings Feeling; - public enum TreatmentTime { }; + public enum TreatmentTime { } public TreatmentTime treated; - public enum CVdiseases { }; + public enum CVdiseases { } public CVdiseases CardiovascularDiseases; - public enum pains { }; + public enum pains { } public pains Pain; - // - - - - - - - - - - - - - - + // - - - - - - - - - - - - - - // Start is called before the first frame update void Start() { - + } // Update is called once per frame void Update() { - + } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityLocalFiles.cs b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityLocalFiles.cs index 04f5045d2..539026f8f 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityLocalFiles.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityLocalFiles.cs @@ -7,7 +7,7 @@ namespace MirageXR public static class ActivityLocalFiles { private const string JSON_NAME_FORMAT = "{0}-activity.json"; - + public static void CleanUp(Activity activity) { var newDirectoryPath = Path.Combine(Application.persistentDataPath, activity.id); @@ -23,6 +23,7 @@ public static void SaveData(Activity activity) var recFilePath = Path.Combine(Application.persistentDataPath, fileName); var json = ActivityParser.Serialize(activity); File.WriteAllText(recFilePath, json); + EventManager.ActivitySaved(); RootObject.Instance.workplaceManager.SaveWorkplace(); } @@ -32,10 +33,10 @@ public static void MoveData(string oldActivityId, string activityId) { throw new ArgumentException(); } - + var oldPath = Path.Combine(Application.persistentDataPath, oldActivityId); var path = Path.Combine(Application.persistentDataPath, activityId); - + if (!Directory.Exists(oldPath)) { Directory.CreateDirectory(oldPath); diff --git a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityManager.cs b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityManager.cs index fb27aaa4d..e4f2ff481 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityManager.cs @@ -9,223 +9,224 @@ namespace MirageXR { - /// - /// ActivityParser. Used for parsing Arlem activity file files - /// and for handling activities defined in the file. - /// - public class ActivityManager - { - private const string SESSION_ID_FORMAT = "session-{0:yyyy-MM-dd_HH-mm-ss}"; - private const string WORKPLACE_ID_FORMAT = "{0}-workplace.json"; - - public Activity Activity => _activity; - public string AbsoluteURL { get; set; } // Id of the currently active action. - public string ActiveActionId => ActiveAction != null ? ActiveAction.id : string.Empty; - public Action ActiveAction { get; private set; } - public string SessionId => Path.GetFileName(ActivityPath); - public bool IsReady { get; private set; } - public List ActionsOfTypeAction => _actionsOfTypeAction; - public string ActivityPath // Path for local files - { - get => _activityPath; - private set - { - if (!Directory.Exists(value)) - { - Directory.CreateDirectory(value); - } - _activityPath = value; - } - } - - private readonly ActivityRestorer _activityRestorer = new ActivityRestorer(); - private List _actionsOfTypeAction = new List(); - private string _activityPath; - private bool _isSwitching = true; // Flag for checking if manager is in the middle of switching an activity. - private string _activityUrl; - private Activity _activity; - private bool _newIdGenerated; - private bool _mustCleanUp; - private bool _editModeActive; - - public bool EditModeActive - { - get => _editModeActive; - set - { - var changed = _editModeActive != value; - _editModeActive = value; + /// + /// ActivityParser. Used for parsing Arlem activity file files + /// and for handling activities defined in the file. + /// + public class ActivityManager + { + private const string SESSION_ID_FORMAT = "session-{0:yyyy-MM-dd_HH-mm-ss}"; + private const string WORKPLACE_ID_FORMAT = "{0}-workplace.json"; + + public Activity Activity => _activity; + public string AbsoluteURL { get; set; } // Id of the currently active action. + public string ActiveActionId => ActiveAction != null ? ActiveAction.id : string.Empty; + public Action ActiveAction { get; private set; } + public string SessionId => Path.GetFileName(ActivityPath); + public bool IsReady { get; private set; } + public List ActionsOfTypeAction => _actionsOfTypeAction; + public string ActivityPath // Path for local files + { + get => _activityPath; + private set + { + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + _activityPath = value; + } + } + + private readonly ActivityRestorer _activityRestorer = new ActivityRestorer(); + private List _actionsOfTypeAction = new List(); + private string _activityPath; + private bool _isSwitching = true; // Flag for checking if manager is in the middle of switching an activity. + private string _activityUrl; + private Activity _activity; + private bool _newIdGenerated; + private bool _mustCleanUp; + private bool _editModeActive; + + public bool EditModeActive + { + get => _editModeActive; + set + { + var changed = _editModeActive != value; + _editModeActive = value; if (_editModeActive) { GenerateNewId(); } if (changed) - { - EventManager.NotifyEditModeChanged(value); - } - } - } - - public void Subscription() - { - EventManager.OnClearAll += Clear; - } - - public void Unsubscribe() - { - EventManager.OnClearAll -= Clear; - } - - public void OnDestroy() - { - if (_activity == null) - { - return; - } - - // TODO: at some point we should implement a way to find out if an activity is resumable - var isResumable = true; - if (ActiveAction == null) - { - PlayerPrefs.SetString(_activity.id, "StartingAction"); - return; - } - - var lastCompleted = ActionsOfTypeAction.IndexOf(ActiveAction) >= ActionsOfTypeAction.Count - 1 && ActiveAction.isCompleted; - - PlayerPrefs.SetString(_activity.id, !isResumable || lastCompleted ? "StartingAction" : ActiveAction.id); - PlayerPrefs.Save(); - - if (_mustCleanUp) - { - ActivityLocalFiles.CleanUp(_activity); - } - } - - private void Clear() - { - _activity = null; - _activityRestorer.Clear(); - } - - /// - /// Reset activity manager when OnPlayerReset event is triggered. - /// - public async Task PlayerReset() - { - _isSwitching = true; - PlayerPrefs.SetString(_activity.id, "StartingAction"); - Clear(); - await LoadActivity(_activityUrl); - EventManager.PlayerReset(); - } - - public void CreateNewActivity() - { - var activity = CreateEmptyActivity(); - _newIdGenerated = false; - EditModeActive = false; - ActivateActivity(activity).AsAsyncVoid(); - } - - private static Activity CreateEmptyActivity() - { - const string cultureInfo = "en-GB"; - - return new Activity - { - name = $"Activity ({DateTime.Now.ToString(new CultureInfo(cultureInfo))})", - version = Application.version, - id = string.Empty - }; - } - - public async Task LoadActivity(string activityId) - { - var activity = string.IsNullOrEmpty(activityId) ? CreateEmptyActivity() : ActivityParser.Parse(activityId); - _activityUrl = activityId; - - //Always load an existing activity in play mode - EditModeActive = false; - - await ActivateActivity(activity); - } - - private async Task ActivateActivity(Activity activity) - { - EventManager.ClearAll(); - await Task.Delay(100); - - _activity = activity; - _actionsOfTypeAction = activity.actions.Where(t => t.type == ActionType.Action).ToList(); - EventManager.InitUi(); - - EventManager.DebugLog($"Activity manager: {_activity.id} parsed."); - - ActivityPath = Path.Combine(Application.persistentDataPath, _activity.id); - - if (IsNeedToRestore(activity, out var restoreId)) - { - _activityRestorer.RestoreActions(activity, restoreId); - } - - await RootObject.Instance.workplaceManager.LoadWorkplace(_activity.workplace); - - await StartActivity(); - IsReady = true; - } - - private static bool IsNeedToRestore(Activity activity, out string restoreId) - { - restoreId = PlayerPrefs.GetString(activity.id); - return !restoreId.Equals("StartingAction") && !string.IsNullOrEmpty(restoreId); - } - - /// - /// Starts the activity when workplace file parsing is completed. - /// - public async Task StartActivity() - { - if (IsNeedToRestore(_activity, out var restoreId) && !restoreId.Equals(_activity.start)) - { - try - { - _activityRestorer.RestoreState(_activity); - } - catch (Exception e) - { - Debug.Log(e); - } - _isSwitching = false; - EventManager.DebugLog($"Activity manager: Starting Activity: {_activity.id}"); - EventManager.ActivityStarted(); - await ActivateAction(restoreId); - } - else - { - try { - if (string.IsNullOrEmpty(_activity.start)) - { - _isSwitching = false; - EventManager.ActivityStarted(); - await AddAction(Vector3.zero); - return; - } - - // Activate the starting action specified in the json file. - foreach (var action in _activity.actions) - { - // Don't go further if the action id doesn't match. - if (action.id != _activity.start) - { - continue; - } - _isSwitching = false; - EventManager.DebugLog($"Activity manager: Starting Activity: {_activity.id}"); - EventManager.ActivityStarted(); - await ActivateAction(action.id); - } + EventManager.NotifyEditModeChanged(value); + } + } + } + + public void Subscription() + { + EventManager.OnClearAll += Clear; + } + + public void Unsubscribe() + { + EventManager.OnClearAll -= Clear; + } + + public void OnDestroy() + { + if (_activity == null) + { + return; + } + + // TODO: at some point we should implement a way to find out if an activity is resumable + var isResumable = true; + if (ActiveAction == null) + { + PlayerPrefs.SetString(_activity.id, "StartingAction"); + return; + } + + var lastCompleted = ActionsOfTypeAction.IndexOf(ActiveAction) >= ActionsOfTypeAction.Count - 1 && ActiveAction.isCompleted; + + PlayerPrefs.SetString(_activity.id, !isResumable || lastCompleted ? "StartingAction" : ActiveAction.id); + PlayerPrefs.Save(); + + if (_mustCleanUp) + { + ActivityLocalFiles.CleanUp(_activity); + } + } + + private void Clear() + { + _activity = null; + _activityRestorer.Clear(); + } + + /// + /// Reset activity manager when OnPlayerReset event is triggered. + /// + public async Task PlayerReset() + { + _isSwitching = true; + PlayerPrefs.SetString(_activity.id, "StartingAction"); + Clear(); + await LoadActivity(_activityUrl); + EventManager.PlayerReset(); + } + + public async Task CreateNewActivity() + { + var activity = CreateEmptyActivity(); + _newIdGenerated = false; + EditModeActive = false; + await ActivateActivity(activity); + } + + private static Activity CreateEmptyActivity() + { + const string cultureInfo = "en-GB"; + + return new Activity + { + name = $"Activity ({DateTime.Now.ToString(new CultureInfo(cultureInfo))})", + version = Application.version, + id = string.Empty + }; + } + + public async Task LoadActivity(string activityId) + { + var activity = string.IsNullOrEmpty(activityId) ? CreateEmptyActivity() : ActivityParser.Parse(activityId); + _activityUrl = activityId; + + //Always load an existing activity in play mode + EditModeActive = false; + + await ActivateActivity(activity); + } + + private async Task ActivateActivity(Activity activity) + { + EventManager.ClearAll(); + await Task.Delay(100); + + _activity = activity; + _actionsOfTypeAction = activity.actions.Where(t => t.type == ActionType.Action).ToList(); + EventManager.InitUi(); + + EventManager.DebugLog($"Activity manager: {_activity.id} parsed."); + + ActivityPath = Path.Combine(Application.persistentDataPath, _activity.id); + + if (IsNeedToRestore(activity, out var restoreId)) + { + _activityRestorer.RestoreActions(activity, restoreId); + } + + await RootObject.Instance.workplaceManager.LoadWorkplace(_activity.workplace); + + await StartActivity(); + IsReady = true; + } + + private static bool IsNeedToRestore(Activity activity, out string restoreId) + { + restoreId = PlayerPrefs.GetString(activity.id); + return !restoreId.Equals("StartingAction") && !string.IsNullOrEmpty(restoreId); + } + + /// + /// Starts the activity when workplace file parsing is completed. + /// + public async Task StartActivity() + { + if (IsNeedToRestore(_activity, out var restoreId) && !restoreId.Equals(_activity.start)) + { + try + { + _activityRestorer.RestoreState(_activity); + } + catch (Exception e) + { + Debug.Log(e); + } + _isSwitching = false; + EventManager.DebugLog($"Activity manager: Starting Activity: {_activity.id}"); + EventManager.ActivityStarted(); + await ActivateAction(restoreId); + } + else + { + try + { + if (string.IsNullOrEmpty(_activity.start)) + { + _isSwitching = false; + + await AddAction(Vector3.zero); + EventManager.ActivityStarted(); + return; + } + + // Activate the starting action specified in the json file. + foreach (var action in _activity.actions) + { + // Don't go further if the action id doesn't match. + if (action.id != _activity.start) + { + continue; + } + _isSwitching = false; + EventManager.DebugLog($"Activity manager: Starting Activity: {_activity.id}"); + EventManager.ActivityStarted(); + await ActivateAction(action.id); + } } catch (Exception e) { @@ -233,613 +234,669 @@ public async Task StartActivity() Debug.LogError(e); } } - } - - public bool IsLastAction(Action action) - { - var last = ActionsOfTypeAction.LastOrDefault(); - return action != null && last == action; - } - - public void MarkCompleted(string id) - { - foreach (var action in _activity.actions) - { - if (action.id.Equals(id)) - { - action.isCompleted = true; - } - } - } - - /// - /// Activates an action. - /// - /// ID of the action to be activated. - private async Task ActivateAction(string id) - { - const string restartKey = "restart"; - - try - { - if (id == restartKey) - { - _isSwitching = true; - await LoadActivity(_activityUrl); - } - else - { - var action = _activity.actions.FirstOrDefault(action => action.id == id); - if (action == null) return; - await ActivateAction(action); - } - } - catch (Exception e) - { - Maggie.Error(); - EventManager.DebugLog($"Error: Activity manager: Couldn't activate action: {id}."); - Debug.LogError(e); - } - } - - private async Task ActivateAction(Action step) - { - const string jsonExtension = ".json"; - - ActiveAction = step; - step.isActive = true; - Trigger.SetupTriggers(step); - - foreach (var content in step.enter.activates) - { - switch (content.type) - { - case ActionType.Action: - case ActionType.Reaction: - { - if (content.id.EndsWith(jsonExtension)) //External activity reference! - { - _isSwitching = true; - await LoadActivity(content.id); - break; - } - - await ActivateAction(step.id, content); - break; - } - default: - { - EventManager.ActivateObject(content); - break; - } - } - if (_isSwitching) - { - break; - } - } - - foreach (var deactivate in step.enter.deactivates) - { - switch (deactivate.type) - { - case ActionType.Action: - case ActionType.Reaction: - { - await DeactivateAction(step.id, deactivate); - break; - } - default: - { - EventManager.DeactivateObject(deactivate); - break; - } - } - } - - var dateStamp = DateTime.UtcNow.ToUniversalTime().ToString(CultureInfo.InvariantCulture); - - EventManager.ActivateAction(step.id); - EventManager.StepActivatedStamp(SystemInfo.deviceUniqueIdentifier, step, dateStamp); - EventManager.DebugLog($"Activity manager: Action {step.id} activated."); - } - - /// - /// Deactivates an action. - /// ID of the action to be deactivated. - /// - public async Task DeactivateAction(string id, bool doNotActivateNextStep = false) - { - if (!_isSwitching) - { - await ActivityDeactivator(id, doNotActivateNextStep); - } - } - - private async Task ActivityDeactivator(string id, bool doNotActivateNextStep) - { - const string restartKey = "restart"; - const string jsonExtension = ".json"; - - // Stop any Maggie messages. - Maggie.Stop(); - - // Get rid of the triggers - Trigger.DeleteTriggersForId(id); - - // Go through all the actions... - foreach (var action in _activity.actions) - { - // Skip the non-matching actions... - if (action.id != id) - { - continue; - } - - // Handle messages. - - ArlemMessage.ReadMessages(action); - - // Exit deactivate loop... - foreach (var deactivate in action.exit.deactivates) - { - switch (deactivate.type) - { - case ActionType.Action: - case ActionType.Reaction: - await DeactivateAction(action.id, deactivate); - break; - - default: - EventManager.DeactivateObject(deactivate); - break; - } - } - - await Task.Yield(); - - //do not activate next step - if (doNotActivateNextStep) - { - return; - } - - // Exit activate loop... - foreach (var activate in action.exit.activates) - { - switch (activate.type) - { - // Handle action logic related stuff here... - case ActionType.Action: - case ActionType.Reaction: - if (activate.id.Equals(restartKey)) - { - _isSwitching = true; - await LoadActivity(_activityUrl); - break; - } - // External activity reference! - if (activate.id.EndsWith(jsonExtension)) - { - _isSwitching = true; - await LoadActivity(activate.id); - break; - } - - await ActivateAction(action.id, activate); - break; - - // All the others are handled outside. - default: - EventManager.ActivateObject(activate); - break; - } - - if (_isSwitching) - { - break; - } - } - - if (_isSwitching) - { - break; - } - - // Mark as completed. Might use a bit smarter way of handling this, but meh... - action.isCompleted = true; - // Send timestamp. - var timeStamp = DateTime.UtcNow.ToUniversalTime().ToString(CultureInfo.InvariantCulture); - EventManager.StepDeactivatedStamp(SystemInfo.deviceUniqueIdentifier, action, timeStamp); - EventManager.DebugLog($"Activity manager: Action {id} deactivated."); - } - } - - /// - /// Activate action. - /// - /// Id of the action calling this method. - /// Action toggle object. - private async Task ActivateAction(string caller, ToggleObject obj) - { - const string restartKey = "restart"; - const string jsonExtension = ".json"; - const string userPrefix ="user:"; - const char splitChar = ':'; - - // Let's check that action really exists... - var counter = 0; - - foreach (var actionObj in _activity.actions) - { - if (actionObj.id == obj.id) - { - counter++; - } - } - - // If not, shame on you for trying! - if (counter == 0 && obj.id != restartKey && !obj.id.EndsWith(jsonExtension)) - { - throw new ArgumentException($"Action {obj.id} not found."); - } - - // Check if activation is user dependent. - if (!string.IsNullOrEmpty(obj.option) && obj.option.StartsWith(userPrefix)) - { - // Extract the user. - var user = obj.option.Split(splitChar)[1]; - - // Activate if conditions are met. - if (obj.id != caller && user == WorkplaceManager.GetUser()) - { - await ActivateAction(obj.id); - } - } - // Normal activation. - else - { - // Like never ending loops? I don't... - if (obj.id != caller) - { - await ActivateAction(obj.id); - } - } - } - - /// - /// Deactivate action. - /// - /// Id of the action calling this method. - /// Action toggle object. - private async Task DeactivateAction(string caller, ToggleObject obj) - { - // Like never ending loops? I don't... - if (obj.id != caller) - { - await DeactivateAction(obj.id); - } - - EventManager.DeactivateAction(caller); - } - - /// - /// Clears out the scene and activates a given action. - /// - /// Action id to be activated. - private async Task BackAction(string id) - { + } + + public bool IsLastAction(Action action) + { + var last = ActionsOfTypeAction.LastOrDefault(); + return action != null && last == action; + } + + public void MarkCompleted(string id) + { + foreach (var action in _activity.actions) + { + if (action.id.Equals(id)) + { + action.isCompleted = true; + } + } + } + + /// + /// Activates an action. + /// + /// ID of the action to be activated. + private async Task ActivateAction(string id) + { + const string restartKey = "restart"; + + try + { + if (id == restartKey) + { + _isSwitching = true; + await LoadActivity(_activityUrl); + } + else + { + var action = _activity.actions.FirstOrDefault(action => action.id == id); + if (action == null) + { + return; + } + + await ActivateAction(action); + } + } + catch (Exception e) + { + Maggie.Error(); + EventManager.DebugLog($"Error: Activity manager: Couldn't activate action: {id}."); + Debug.LogError(e); + } + } + + private async Task ActivateAction(Action step) + { + const string jsonExtension = ".json"; + + ActiveAction = step; + step.isActive = true; + Trigger.SetupTriggers(step); + + foreach (var content in step.enter.activates) + { + switch (content.type) + { + case ActionType.Action: + case ActionType.Reaction: + { + if (content.id.EndsWith(jsonExtension)) //External activity reference! + { + _isSwitching = true; + await LoadActivity(content.id); + break; + } + + await ActivateAction(step.id, content); + break; + } + + default: + { + EventManager.ActivateObject(content); + break; + } + } + + if (_isSwitching) + { + break; + } + } + + foreach (var deactivate in step.enter.deactivates) + { + switch (deactivate.type) + { + case ActionType.Action: + case ActionType.Reaction: + { + await DeactivateAction(step.id, deactivate); + break; + } + default: + { + EventManager.DeactivateObject(deactivate); + break; + } + } + } + + var dateStamp = DateTime.UtcNow.ToUniversalTime().ToString(CultureInfo.InvariantCulture); + + EventManager.ActivateAction(step.id); + EventManager.StepActivatedStamp(SystemInfo.deviceUniqueIdentifier, step, dateStamp); + EventManager.DebugLog($"Activity manager: Action {step.id} activated."); + } + + /// + /// Deactivates an action. + /// ID of the action to be deactivated. + /// + public async Task DeactivateAction(string id, bool doNotActivateNextStep = false) + { + if (!_isSwitching) + { + //Save augmentations extra data(character, pick&place,...) for be carried over to the new action if the augmentation exists in that action + SaveData(); + await ActivityDeactivator(id, doNotActivateNextStep); + } + } + + private async Task ActivityDeactivator(string id, bool doNotActivateNextStep) + { + const string restartKey = "restart"; + const string jsonExtension = ".json"; + + // Stop any Maggie messages. + Maggie.Stop(); + + // Get rid of the triggers + Trigger.DeleteTriggersForId(id); + + // Go through all the actions... + foreach (var action in _activity.actions) + { + // Skip the non-matching actions... + if (action.id != id) + { + continue; + } + + // Handle messages. + + ArlemMessage.ReadMessages(action); + + // Exit deactivate loop... + foreach (var deactivate in action.exit.deactivates) + { + switch (deactivate.type) + { + case ActionType.Action: + case ActionType.Reaction: + await DeactivateAction(action.id, deactivate); + break; + + default: + EventManager.DeactivateObject(deactivate); + break; + } + } + + await Task.Yield(); + + //do not activate next step + if (doNotActivateNextStep) + { + return; + } + + // Exit activate loop... + foreach (var activate in action.exit.activates) + { + switch (activate.type) + { + // Handle action logic related stuff here... + case ActionType.Action: + case ActionType.Reaction: + if (activate.id.Equals(restartKey)) + { + _isSwitching = true; + await LoadActivity(_activityUrl); + break; + } + // External activity reference! + if (activate.id.EndsWith(jsonExtension)) + { + _isSwitching = true; + await LoadActivity(activate.id); + break; + } + + await ActivateAction(action.id, activate); + break; + + // All the others are handled outside. + default: + EventManager.ActivateObject(activate); + break; + } + + if (_isSwitching) + { + break; + } + } + + if (_isSwitching) + { + break; + } + + // Mark as completed. Might use a bit smarter way of handling this, but meh... + action.isCompleted = true; + // Send timestamp. + var timeStamp = DateTime.UtcNow.ToUniversalTime().ToString(CultureInfo.InvariantCulture); + EventManager.StepDeactivatedStamp(SystemInfo.deviceUniqueIdentifier, action, timeStamp); + EventManager.DebugLog($"Activity manager: Action {id} deactivated."); + } + } + + /// + /// Activate action. + /// + /// Id of the action calling this method. + /// Action toggle object. + private async Task ActivateAction(string caller, ToggleObject obj) + { + const string restartKey = "restart"; + const string jsonExtension = ".json"; + const string userPrefix = "user:"; + const char splitChar = ':'; + + // Let's check that action really exists... + var counter = 0; + + foreach (var actionObj in _activity.actions) + { + if (actionObj.id == obj.id) + { + counter++; + } + } + + // If not, shame on you for trying! + if (counter == 0 && obj.id != restartKey && !obj.id.EndsWith(jsonExtension)) + { + throw new ArgumentException($"Action {obj.id} not found."); + } + + // Check if activation is user dependent. + if (!string.IsNullOrEmpty(obj.option) && obj.option.StartsWith(userPrefix)) + { + // Extract the user. + var user = obj.option.Split(splitChar)[1]; + + // Activate if conditions are met. + if (obj.id != caller && user == WorkplaceManager.GetUser()) + { + await ActivateAction(obj.id); + } + } + // Normal activation. + else + { + // Like never ending loops? I don't... + if (obj.id != caller) + { + await ActivateAction(obj.id); + } + } + } + + /// + /// Deactivate action. + /// + /// Id of the action calling this method. + /// Action toggle object. + private async Task DeactivateAction(string caller, ToggleObject obj) + { + // Like never ending loops? I don't... + if (obj.id != caller) + { + await DeactivateAction(obj.id); + } + + EventManager.DeactivateAction(caller); + } + + /// + /// Clears out the scene and activates a given action. + /// + /// Action id to be activated. + private async Task BackAction(string id) + { // First clear out the scene. try { // Get rid of the triggers Trigger.DeleteTriggersForId(id); - // Go through all the actions and try to find the active action... - foreach (var action in _activity.actions) - { - // Skip the non-matching actions... - if (action.id != ActiveActionId) - { - continue; - } - - // Enter activate loop... - foreach (var activate in action.enter.activates) - { - // Do magic based on the activation object type... - switch (activate.type) - { - // Handle action logic related stuff here... - case ActionType.Action: - case ActionType.Reaction: - // We are not interested in activating anything! - break; - - // All the others are handled outside. - default: - // Deactivate everything that is activated! - EventManager.DeactivateObject(activate); - break; - } - } - } - - // Now activate the desired action on the empty slate. - await ActivateAction(id); + // Go through all the actions and try to find the active action... + foreach (var action in _activity.actions) + { + // Skip the non-matching actions... + if (action.id != ActiveActionId) + { + continue; + } + + // Enter activate loop... + foreach (var activate in action.enter.activates) + { + // Do magic based on the activation object type... + switch (activate.type) + { + // Handle action logic related stuff here... + case ActionType.Action: + case ActionType.Reaction: + // We are not interested in activating anything! + break; + + // All the others are handled outside. + default: + // Deactivate everything that is activated! + EventManager.DeactivateObject(activate); + break; + } + } + } + + // Now activate the desired action on the empty slate. + await ActivateAction(id); } catch (Exception e) { - Maggie.Error(); - EventManager.DebugLog($"Error: Activity manager: Couldn't force start action: {id}."); - Debug.Log(e); - throw; - } - } - - public async Task ActivateActionByIndex(int index) - { - await DeactivateAction(ActiveAction.id, true); - await ActivateAction(ActionsOfTypeAction[index].id); - } - - public async Task ActivateNextAction() - { - if (ActiveAction != null) - { - await DeactivateAction(ActiveAction.id); - } - else - { - await ActivateAction(_activity.start); - } - } - - public async Task ActivatePreviousAction() - { - int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); - if (indexOfActivated > 0) - { - await BackAction(ActionsOfTypeAction[indexOfActivated - 1].id); - } - } - - public async Task ActivateFirstAction() - { - int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); - if (indexOfActivated > 0) - { - await ActivateActionByIndex(0); - } - } - - public async Task ActivateLastAction() - { - int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); - int indexOfLastAction = Activity.actions.Count - 1; - if (indexOfActivated < indexOfLastAction) - { - await ActivateActionByIndex(indexOfLastAction); - } - } - - - public async Task AddAction(Vector3 position, bool hasImageMarker = false) - { - // TODO: put back in the warning - //if (taskStationList.Count == 0 && !calibrationMarkerFound) - //{ - // Maggie.Speak("Your workplace is not calibrated. Recordings cannot be played back on other devices or in other workplaces."); - //} - - // create a new arlem action representing the task station - // (must be done before instantiating the object) - var newAction = CreateAction(); - - // create a new workplace place - await RootObject.Instance.workplaceManager.AddPlace(newAction, position); - - int indexOfActive = -1; - - // update the exit-activate ARLEM section of previous TS to point to the new one - if (_activity.actions.Count > 0) - { - // if no active action is set, use the last action as active action - ActiveAction ??= _activity.actions[_activity.actions.Count - 1]; - - indexOfActive = _activity.actions.IndexOf(ActiveAction); - - // update the exit-activate ARLEM section of previous TS to point to the new one - if (indexOfActive >= 0) - { - var exitActivateElement = new ToggleObject - { - id = newAction.id, - viewport = newAction.viewport, - type = newAction.type - }; - - if (_activity.actions[indexOfActive].exit.activates.Count > 0) - { - newAction.exit.activates.Add(_activity.actions[indexOfActive].exit.activates[0]); - _activity.actions[indexOfActive].exit.activates[0] = exitActivateElement; - } - else - { - _activity.actions[indexOfActive].exit.activates.Add(exitActivateElement); - } - } - else - { - Debug.LogError("Could not identify the active action"); - } - - //Save augmentations extra data(character, pick&place,...) for be carried over to the new action if the augmentation exists in that action - SaveData(); - } - else - { - _activity.start = newAction.id; - } - - _activity.actions.Insert(indexOfActive + 1, newAction); - - Debug.Log($"Added {newAction.id} to list of task stations"); - - RegenerateActionsList(); - await ActivateNextAction(); - await ActivateAction(newAction); - await Task.Yield(); - EventManager.NotifyActionCreated(newAction); - } - - private Action CreateAction() - { - var taskStationId = Guid.NewGuid(); - var taskStationName = $"TS-{taskStationId}"; - - var action = new Action - { - id = taskStationName, - viewport = "actions", - type = ActionType.Action, - instruction = new Instruction(), - enter = new Enter(), - exit = new Exit(), - triggers = new List(), - - device = "wekit.one", - location = "here", - predicate = "none", - user = string.Empty - }; - - action.instruction.title = $"Action Step {_activity.actions.Count + 1}"; // Fudge fix: Added +1 to remove "Action Step 0". Need more information if we want to increase thisActionIndex by 1 (Might be it needs the 0) - action.instruction.description = "Add task step description here..."; - - action.AddArlemTrigger(TriggerMode.Voice); - action.AddArlemTrigger(TriggerMode.Click); - - return action; - } - - public void DeleteAction(string idToDelete) - { - int indexToDelete = _activity.actions.IndexOf(_activity.actions.FirstOrDefault(p => p.id.Equals(idToDelete))); - - if (indexToDelete < 0) - { - Debug.LogError($"Could not remove {idToDelete} since the id could not be found in the list of actions"); - return; - } - - int totalNumberOfActions = _activity.actions.Count; - - Debug.Log($"Planning to delete action with index {indexToDelete}"); - - if (indexToDelete == totalNumberOfActions - 1) // if deleting the last action - { - Debug.Log("deleting last action"); - - if (totalNumberOfActions != 1) - { - _activity.actions[indexToDelete - 1].exit.activates.Last().id = string.Empty; - } - } - else if (indexToDelete == 0) // if deleting the first action - { - Debug.Log("deleting first action"); - // update start action with the one that is currently second (prior to deleting the action, in this case) - if (totalNumberOfActions > 1) - { - _activity.start = _activity.actions[1].id; - } - } - else // we are deleting an action that is in the middle - { - _activity.actions[indexToDelete - 1].exit.activates.Last().id = _activity.actions[indexToDelete + 1].id; - } - - //Create a new list of activate to avoid "Collection modified exception" - var enterActivateTempCopy = new List(); - foreach (var item in _activity.actions[indexToDelete].enter.activates) - { - enterActivateTempCopy.Add(item); - } - - var actionToDelete = _activity.actions[indexToDelete]; - - var commonToggleObjects = new List(); - //find all common annotations which exist in action to delete and other actions - foreach (var action in _activity.actions) - { - commonToggleObjects.AddRange(action.enter.activates.Intersect(actionToDelete.enter.activates).ToList()); - } - - foreach (var toggleObject in enterActivateTempCopy) - { - if (!commonToggleObjects.Contains(toggleObject)) - { - RootObject.Instance.augmentationManager.DeleteAugmentation(toggleObject, _activity.actions[indexToDelete]); - } - } - - _activity.actions.RemoveAt(indexToDelete); - - RegenerateActionsList(); - ActiveAction = null; - - EventManager.NotifyActionDeleted(idToDelete); - EventManager.ActivateAction(string.Empty); - } - - private void RegenerateActionsList() - { - _actionsOfTypeAction.Clear(); - _actionsOfTypeAction.AddRange(_activity.actions.Where(action => action.type == ActionType.Action)); - } - - public void SaveData() - { - _mustCleanUp = false; - ActivityLocalFiles.SaveData(_activity); - } - - private void GenerateNewId(bool force = false) - { - if (_newIdGenerated && !force) - { - return; - } - - string id; - if (!string.IsNullOrEmpty(_activity.id) && !force) - { - id = _activity.id; - } - else - { - var oldId = _activity.id; - id = string.Format(SESSION_ID_FORMAT, DateTime.UtcNow); - if (!string.IsNullOrEmpty(oldId)) - { - ActivityLocalFiles.MoveData(oldId, id); - } - _activity.id = id; - _activity.version = Application.version; - ActivityPath = Path.Combine(Application.persistentDataPath, id); - _mustCleanUp = true; // not yet saved; this is used if the user quits without saving so that we can clean up - } - - var workplaceId = string.Format(WORKPLACE_ID_FORMAT, id); - RootObject.Instance.workplaceManager.workplace.id = workplaceId; - _activity.workplace = workplaceId; - _newIdGenerated = true; - } - - public void CloneActivity() - { - GenerateNewId(true); - } - } + Maggie.Error(); + EventManager.DebugLog($"Error: Activity manager: Couldn't force start action: {id}."); + Debug.Log(e); + throw; + } + } + + public async Task ActivateActionByIndex(int index) + { + await DeactivateAction(ActiveAction.id, true); + await ActivateAction(ActionsOfTypeAction[index].id); + } + + public async Task ActivateActionByID(string id) + { + await DeactivateAction(ActiveAction.id, true); + await ActivateAction(id); + } + + public async Task ActivateNextAction() + { + int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); + int indexOfLast = ActionsOfTypeAction.Count - 1; + if (indexOfActivated < indexOfLast) + { + if (ActiveAction != null) + { + await DeactivateAction(ActiveAction.id); + } + else + { + await ActivateAction(_activity.start); + } + } + } + + public async Task ActivatePreviousAction() + { + int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); + if (indexOfActivated > 0) + { + await BackAction(ActionsOfTypeAction[indexOfActivated - 1].id); + } + } + + public async Task ActivateFirstAction() + { + int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); + if (indexOfActivated > 0) + { + await ActivateActionByIndex(0); + } + } + + public async Task ActivateLastAction() + { + int indexOfActivated = ActionsOfTypeAction.IndexOf(ActiveAction); + int indexOfLastAction = Activity.actions.Count - 1; + if (indexOfActivated < indexOfLastAction) + { + await ActivateActionByIndex(indexOfLastAction); + } + } + +/* + public void SwapActions(Action action1, Action action2) + { + var index1 = _activity.actions.IndexOf(action1); + var index2 = _activity.actions.IndexOf(action2); + + if (index1 == -1 || index2 == -1) + { + Debug.LogError($"Could not find the {action1.id} or {action2.id} actions"); + return; + } + + _activity.actions[index1] = action2; + _activity.actions[index2] = action1; + } +*/ + + public async Task AddActionToBegin(Vector3 position, bool hasImageMarker = false) + { + var newAction = CreateAction(); + await RootObject.Instance.workplaceManager.AddPlace(newAction, position); + + _activity.start = newAction.id; + _activity.actions.Insert(0, newAction); + + Debug.Log($"Added {newAction.id} to list of task stations"); + + RegenerateActionsList(); + await ActivateNextAction(); + await ActivateAction(newAction); + await Task.Yield(); + EventManager.NotifyActionCreated(newAction); + } + + public async Task AddAction(Vector3 position, bool hasImageMarker = false) + { + // TODO: put back in the warning + //if (taskStationList.Count == 0 && !calibrationMarkerFound) + //{ + // Maggie.Speak("Your workplace is not calibrated. Recordings cannot be played back on other devices or in other workplaces."); + //} + + // create a new arlem action representing the task station + // (must be done before instantiating the object) + var newAction = CreateAction(); + + // create a new workplace place + await RootObject.Instance.workplaceManager.AddPlace(newAction, position); + + int indexOfActive = -1; + + // update the exit-activate ARLEM section of previous TS to point to the new one + if (_activity.actions.Count > 0) + { + // if no active action is set, use the last action as active action + ActiveAction ??= _activity.actions[_activity.actions.Count - 1]; + + indexOfActive = _activity.actions.IndexOf(ActiveAction); + + // update the exit-activate ARLEM section of previous TS to point to the new one + if (indexOfActive >= 0) + { + var exitActivateElement = new ToggleObject + { + id = newAction.id, + viewport = newAction.viewport, + type = newAction.type + }; + + if (_activity.actions[indexOfActive].exit.activates.Count > 0) + { + newAction.exit.activates.Add(_activity.actions[indexOfActive].exit.activates[0]); + _activity.actions[indexOfActive].exit.activates[0] = exitActivateElement; + } + else + { + _activity.actions[indexOfActive].exit.activates.Add(exitActivateElement); + } + } + else + { + Debug.LogError("Could not identify the active action"); + + } + } + else + { + _activity.start = newAction.id; + } + + _activity.actions.Insert(indexOfActive + 1, newAction); + + Debug.Log($"Added {newAction.id} to list of task stations"); + + RegenerateActionsList(); + await ActivateNextAction(); + await ActivateAction(newAction); + await Task.Yield(); + EventManager.NotifyActionCreated(newAction); + } + + private Action CreateAction() + { + var taskStationId = Guid.NewGuid(); + var taskStationName = $"TS-{taskStationId}"; + + var action = new Action + { + id = taskStationName, + viewport = "actions", + type = ActionType.Action, + instruction = new Instruction(), + enter = new Enter(), + exit = new Exit(), + triggers = new List(), + + device = "wekit.one", + location = "here", + predicate = "none", + user = string.Empty + }; + + action.instruction.title = $"Action Step {_activity.actions.Count + 1}"; // Fudge fix: Added +1 to remove "Action Step 0". Need more information if we want to increase thisActionIndex by 1 (Might be it needs the 0) + action.instruction.description = "Add task step description here..."; + + action.AddArlemTrigger(TriggerMode.Voice); + action.AddArlemTrigger(TriggerMode.Click); + + return action; + } + + public void DeleteAction(string idToDelete) + { + int indexToDelete = _activity.actions.IndexOf(_activity.actions.FirstOrDefault(p => p.id.Equals(idToDelete))); + + if (indexToDelete < 0) + { + Debug.LogError($"Could not remove {idToDelete} since the id could not be found in the list of actions"); + return; + } + + int totalNumberOfActions = _activity.actions.Count; + + Debug.Log($"Planning to delete action with index {indexToDelete}"); + + if (indexToDelete == totalNumberOfActions - 1) // if deleting the last action + { + Debug.Log("deleting last action"); + + if (totalNumberOfActions != 1) + { + if (_activity.actions[indexToDelete - 1].exit.activates.Count > 0) + { + _activity.actions[indexToDelete - 1].exit.activates.Last().id = string.Empty; + } + } + } + else if (indexToDelete == 0) // if deleting the first action + { + Debug.Log("deleting first action"); + // update start action with the one that is currently second (prior to deleting the action, in this case) + if (totalNumberOfActions > 1) + { + _activity.start = _activity.actions[1].id; + } + } + else // we are deleting an action that is in the middle + { + _activity.actions[indexToDelete - 1].exit.activates.Last().id = _activity.actions[indexToDelete + 1].id; + } + + //Create a new list of activate to avoid "Collection modified exception" + var enterActivateTempCopy = new List(); + foreach (var item in _activity.actions[indexToDelete].enter.activates) + { + enterActivateTempCopy.Add(item); + } + + var actionToDelete = _activity.actions[indexToDelete]; + + var commonToggleObjects = new List(); + //find all common annotations which exist in action to delete and other actions + foreach (var action in _activity.actions) + { + commonToggleObjects.AddRange(action.enter.activates.Intersect(actionToDelete.enter.activates).ToList()); + } + + foreach (var toggleObject in enterActivateTempCopy) + { + if (!commonToggleObjects.Contains(toggleObject)) + { + RootObject.Instance.augmentationManager.DeleteAugmentation(toggleObject, _activity.actions[indexToDelete]); + } + } + + _activity.actions.RemoveAt(indexToDelete); + + RegenerateActionsList(); + + EventManager.NotifyActionDeleted(idToDelete); + + if (ActiveAction.id == idToDelete) + { + ActivateNextAction(); + } + } + + private void RegenerateActionsList() + { + _actionsOfTypeAction.Clear(); + _actionsOfTypeAction.AddRange(_activity.actions.Where(action => action.type == ActionType.Action)); + } + + public void SaveData() + { + _mustCleanUp = false; + ActivityLocalFiles.SaveData(_activity); + } + + private void GenerateNewId(bool force = false) + { + if (_newIdGenerated && !force) + { + return; + } + + string id; + if (!string.IsNullOrEmpty(_activity.id) && !force) + { + id = _activity.id; + } + else + { + var oldId = _activity.id; + id = string.Format(SESSION_ID_FORMAT, DateTime.UtcNow); + if (!string.IsNullOrEmpty(oldId)) + { + ActivityLocalFiles.MoveData(oldId, id); + } + _activity.id = id; + _activity.version = Application.version; + ActivityPath = Path.Combine(Application.persistentDataPath, id); + _mustCleanUp = true; // not yet saved; this is used if the user quits without saving so that we can clean up + } + + var workplaceId = string.Format(WORKPLACE_ID_FORMAT, id); + RootObject.Instance.workplaceManager.workplace.id = workplaceId; + _activity.workplace = workplaceId; + _newIdGenerated = true; + } + + public void CloneActivity() + { + GenerateNewId(true); + } + } } \ No newline at end of file diff --git a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityParser.cs b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityParser.cs index beb18bbc5..b5492a0de 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityParser.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityParser.cs @@ -4,46 +4,46 @@ namespace MirageXR { - public static class ActivityParser - { - private const string RESOURCES_PREFIX = "resources://"; - private const string HTTP_PREFIX = "http"; - private const string JSON_EXCEPTION = ".json"; - private const char SLASH_CHAR = '/'; + public static class ActivityParser + { + private const string RESOURCES_PREFIX = "resources://"; + private const string HTTP_PREFIX = "http"; + private const string JSON_EXCEPTION = ".json"; + private const char SLASH_CHAR = '/'; - public static Activity Parse(string activityId) - { - var json = GetActivityJson(activityId); - return JsonConvert.DeserializeObject(json); - } + public static Activity Parse(string activityId) + { + var json = GetActivityJson(activityId); + return JsonConvert.DeserializeObject(json); + } - public static string Serialize(Activity activity) - { - return JsonConvert.SerializeObject(activity); - } + public static string Serialize(Activity activity) + { + return JsonConvert.SerializeObject(activity); + } - private static string GetActivityJson(string activityId) - { - if (activityId.StartsWith(RESOURCES_PREFIX)) - { - var filePath = activityId.Replace(RESOURCES_PREFIX, string.Empty); - var textAsset = Resources.Load(filePath) as TextAsset; - return textAsset ? textAsset.text : null; - } + private static string GetActivityJson(string activityId) + { + if (activityId.StartsWith(RESOURCES_PREFIX)) + { + var filePath = activityId.Replace(RESOURCES_PREFIX, string.Empty); + var textAsset = Resources.Load(filePath) as TextAsset; + return textAsset ? textAsset.text : null; + } - if (activityId.StartsWith(HTTP_PREFIX)) - { - var fullname = activityId.Split(SLASH_CHAR); - activityId = fullname[fullname.Length - 1]; - } + if (activityId.StartsWith(HTTP_PREFIX)) + { + var fullname = activityId.Split(SLASH_CHAR); + activityId = fullname[fullname.Length - 1]; + } - if (!activityId.EndsWith(JSON_EXCEPTION)) - { - activityId += JSON_EXCEPTION; - } + if (!activityId.EndsWith(JSON_EXCEPTION)) + { + activityId += JSON_EXCEPTION; + } - var path = Path.Combine(Application.persistentDataPath, activityId); - return File.Exists(path) ? File.ReadAllText(path) : null; - } + var path = Path.Combine(Application.persistentDataPath, activityId); + return File.Exists(path) ? File.ReadAllText(path) : null; + } } } \ No newline at end of file diff --git a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityRestorer.cs b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityRestorer.cs index 1435e5f10..52e69bd46 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityRestorer.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Activity/ActivityRestorer.cs @@ -2,187 +2,187 @@ namespace MirageXR { - public class ActivityRestorer - { - private readonly List _actionsToRestore = new List(); - private readonly List _objectsToRestore = new List(); - - public void RestoreState(Activity activity) - { - var reactionsToRestore = new List(); - foreach (var restoreAction in _actionsToRestore) - { - foreach (var action in activity.actions) - { - if (action.id.Equals(restoreAction)) - { - foreach (var activate in action.enter.activates) - { - switch (activate.type) - { - case ActionType.Action: break; - case ActionType.Reaction: - reactionsToRestore.Add(activate.id); - break; - default: - _objectsToRestore.Add(activate); - break; - } - } - - foreach (var activate in action.exit.activates) - { - switch (activate.type) - { - case ActionType.Action: break; - case ActionType.Reaction: - reactionsToRestore.Add(activate.id); - break; - default: - _objectsToRestore.Add(activate); - break; - } - } - - foreach (var deactivate in action.enter.deactivates) - { - switch (deactivate.type) - { - case ActionType.Action: break; - case ActionType.Reaction: - if (reactionsToRestore.Contains(deactivate.id)) - { - reactionsToRestore.Remove(deactivate.id); - } - - break; - default: - RemoveObjectFromRestoreList(deactivate); - break; - } - } - - foreach (var deactivate in action.exit.deactivates) - { - switch (deactivate.type) - { - case ActionType.Action: break; - case ActionType.Reaction: - if (reactionsToRestore.Contains(deactivate.id)) - { - reactionsToRestore.Remove(deactivate.id); - } - - break; - default: - RemoveObjectFromRestoreList(deactivate); - break; - } - } - } - } - } - - foreach (var restoreObject in _objectsToRestore) - { - EventManager.ActivateObject(restoreObject); - } - - foreach (var reaction in reactionsToRestore) - { - foreach (var action in activity.actions) - { - if (action.type != ActionType.Reaction) - continue; - - if (action.id.Equals(reaction)) - { - Trigger.SetupTriggers(action); - } - } - } - } - - public void RestoreActions(Activity activity, string restoreId) - { - if (!string.IsNullOrEmpty(activity.start)) - { - _actionsToRestore.Add(activity.start); - } - - foreach (var action in activity.actions) - { - // Continue only until restore step is reached. - if (action.id.Equals(restoreId)) - { - break; - } - - foreach (var activate in action.enter.activates) - { - switch (activate.type) - { - case ActionType.Action: - if (!activate.id.Equals(restoreId)) - { - _actionsToRestore.Add(activate.id); - } - - break; - case ActionType.Reaction: break; - } - } - - foreach (var activate in action.exit.activates) - { - switch (activate.type) - { - case ActionType.Action: - if (!activate.id.Equals(restoreId)) - { - _actionsToRestore.Add(activate.id); - } - - break; - case ActionType.Reaction: break; - } - } - } - - foreach (var restoreAction in _actionsToRestore) - { - foreach (var action in activity.actions) - { - if (action.id.Equals(restoreAction)) - { - action.isCompleted = true; - } - } - } - } - - private void RemoveObjectFromRestoreList(ToggleObject obj) - { - for (int i = _objectsToRestore.Count - 1; i >= 0; i--) - { - var item = _objectsToRestore[i]; - if (!item.id.Equals(obj.id) || - !item.poi.Equals(obj.poi) || - !item.position.Equals(obj.position) || - !item.rotation.Equals(obj.rotation) || - !item.predicate.Equals(obj.predicate)) continue; - - if (string.IsNullOrEmpty(item.url) || item.url.Equals(obj.url)) - { - _objectsToRestore.Remove(item); - } - } - } - - public void Clear() - { - _actionsToRestore.Clear(); - _objectsToRestore.Clear(); - } - } + public class ActivityRestorer + { + private readonly List _actionsToRestore = new List(); + private readonly List _objectsToRestore = new List(); + + public void RestoreState(Activity activity) + { + var reactionsToRestore = new List(); + foreach (var restoreAction in _actionsToRestore) + { + foreach (var action in activity.actions) + { + if (action.id.Equals(restoreAction)) + { + foreach (var activate in action.enter.activates) + { + switch (activate.type) + { + case ActionType.Action: break; + case ActionType.Reaction: + reactionsToRestore.Add(activate.id); + break; + default: + _objectsToRestore.Add(activate); + break; + } + } + + foreach (var activate in action.exit.activates) + { + switch (activate.type) + { + case ActionType.Action: break; + case ActionType.Reaction: + reactionsToRestore.Add(activate.id); + break; + default: + _objectsToRestore.Add(activate); + break; + } + } + + foreach (var deactivate in action.enter.deactivates) + { + switch (deactivate.type) + { + case ActionType.Action: break; + case ActionType.Reaction: + if (reactionsToRestore.Contains(deactivate.id)) + { + reactionsToRestore.Remove(deactivate.id); + } + + break; + default: + RemoveObjectFromRestoreList(deactivate); + break; + } + } + + foreach (var deactivate in action.exit.deactivates) + { + switch (deactivate.type) + { + case ActionType.Action: break; + case ActionType.Reaction: + if (reactionsToRestore.Contains(deactivate.id)) + { + reactionsToRestore.Remove(deactivate.id); + } + + break; + default: + RemoveObjectFromRestoreList(deactivate); + break; + } + } + } + } + } + + foreach (var restoreObject in _objectsToRestore) + { + EventManager.ActivateObject(restoreObject); + } + + foreach (var reaction in reactionsToRestore) + { + foreach (var action in activity.actions) + { + if (action.type != ActionType.Reaction) + continue; + + if (action.id.Equals(reaction)) + { + Trigger.SetupTriggers(action); + } + } + } + } + + public void RestoreActions(Activity activity, string restoreId) + { + if (!string.IsNullOrEmpty(activity.start)) + { + _actionsToRestore.Add(activity.start); + } + + foreach (var action in activity.actions) + { + // Continue only until restore step is reached. + if (action.id.Equals(restoreId)) + { + break; + } + + foreach (var activate in action.enter.activates) + { + switch (activate.type) + { + case ActionType.Action: + if (!activate.id.Equals(restoreId)) + { + _actionsToRestore.Add(activate.id); + } + + break; + case ActionType.Reaction: break; + } + } + + foreach (var activate in action.exit.activates) + { + switch (activate.type) + { + case ActionType.Action: + if (!activate.id.Equals(restoreId)) + { + _actionsToRestore.Add(activate.id); + } + + break; + case ActionType.Reaction: break; + } + } + } + + foreach (var restoreAction in _actionsToRestore) + { + foreach (var action in activity.actions) + { + if (action.id.Equals(restoreAction)) + { + action.isCompleted = true; + } + } + } + } + + private void RemoveObjectFromRestoreList(ToggleObject obj) + { + for (int i = _objectsToRestore.Count - 1; i >= 0; i--) + { + var item = _objectsToRestore[i]; + if (!item.id.Equals(obj.id) || + !item.poi.Equals(obj.poi) || + !item.position.Equals(obj.position) || + !item.rotation.Equals(obj.rotation) || + !item.predicate.Equals(obj.predicate)) continue; + + if (string.IsNullOrEmpty(item.url) || item.url.Equals(obj.url)) + { + _objectsToRestore.Remove(item); + } + } + } + + public void Clear() + { + _actionsToRestore.Clear(); + _objectsToRestore.Clear(); + } + } } \ No newline at end of file diff --git a/Assets/MirageXR/Player/Scripts/Managers/BrandCustomizer.cs b/Assets/MirageXR/Player/Scripts/Managers/BrandCustomizer.cs index 2f53d5061..61657d59b 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/BrandCustomizer.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/BrandCustomizer.cs @@ -62,6 +62,6 @@ IEnumerator Init() if (name == "floorTarget" && GetComponent()) GetComponent().color = BrandManager.Instance.GetTaskStationColor(); - } + } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/BrandManager.cs b/Assets/MirageXR/Player/Scripts/Managers/BrandManager.cs index 45cf021fc..5693862b9 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/BrandManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/BrandManager.cs @@ -18,7 +18,7 @@ public class BrandManager : MonoBehaviour [SerializeField] private Color defaultNextPathColor; public static BrandManager Instance { get; private set; } - + private Color newPrimaryColor; private Color newSecondaryColor; private Color newTextColor; @@ -94,7 +94,7 @@ public string[] GetListOfAugmentations() } // if the file is empty return the default array - if(listOfAugmentations.Length == 0 || (listOfAugmentations.Length == 1 && listOfAugmentations[0] == "")) + if (listOfAugmentations.Length == 0 || (listOfAugmentations.Length == 1 && listOfAugmentations[0] == "")) { return spareListOfAugmentations; } @@ -182,12 +182,12 @@ public Color GetPrimaryColor() public Color GetSecondaryColor() { - return !prefabsOriginalColors ? newSecondaryColor: defaultSecondaryColor; + return !prefabsOriginalColors ? newSecondaryColor : defaultSecondaryColor; } public Color GetTextColor() { - return !prefabsOriginalColors ? newTextColor: defaultTextColor; + return !prefabsOriginalColors ? newTextColor : defaultTextColor; } public Color GetIconColor() @@ -197,7 +197,7 @@ public Color GetIconColor() public Color GetTaskStationColor() { - return !prefabsOriginalColors ? newTaskStationColor: defaultSecondaryColor; + return !prefabsOriginalColors ? newTaskStationColor : defaultSecondaryColor; } public Color GetUIPathColor() diff --git a/Assets/MirageXR/Player/Scripts/Managers/DebugManager.cs b/Assets/MirageXR/Player/Scripts/Managers/DebugManager.cs index 9996de05c..1905c87e7 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/DebugManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/DebugManager.cs @@ -5,35 +5,35 @@ namespace MirageXR { public class DebugManager : MonoBehaviour { - [Tooltip ("Drag debug text object here.")] + [Tooltip("Drag debug text object here.")] [SerializeField] private Text DebugText; - [Tooltip ("Drag device info text here.")] + [Tooltip("Drag device info text here.")] [SerializeField] private Text DeviceInfo; - private void OnEnable () + private void OnEnable() { // Register to event manager events. EventManager.OnDebugLog += DebugLog; } - private void OnDisable () + private void OnDisable() { // Unregister from event manager events. EventManager.OnDebugLog -= DebugLog; } // Use this for initialization. - private void Start () + private void Start() { if (DebugText == null) { - Debug.Log ("Debug manager error: Debug text not found. Please add one in editor."); + Debug.Log("Debug manager error: Debug text not found. Please add one in editor."); } if (DeviceInfo == null) { - Debug.Log ("Debug manager error: Device info text not found. Please add one in editor."); + Debug.Log("Debug manager error: Device info text not found. Please add one in editor."); } DeviceInfo.text = SystemInfo.deviceUniqueIdentifier; @@ -43,7 +43,7 @@ private void Start () /// Add debug message to debug console. /// /// Debug message. - private void DebugLog (string debug) + private void DebugLog(string debug) { DebugText.text = debug + "\n" + DebugText.text; } @@ -51,7 +51,7 @@ private void DebugLog (string debug) /// /// Clear debug console. Called from UiManager. /// - private void ClearDebug () + private void ClearDebug() { DebugText.text = ""; } diff --git a/Assets/MirageXR/Player/Scripts/Managers/EventManager.cs b/Assets/MirageXR/Player/Scripts/Managers/EventManager.cs index ccd496db0..ea83ac7ed 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/EventManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/EventManager.cs @@ -709,13 +709,6 @@ public static void NotifyOnTaskStationEditorEnabled() TaskStationEditorEnabled?.Invoke(); } - public delegate void ActivityRenamedDelegate(); - public static event ActivityRenamedDelegate ActivityRenamed; - public static void NotifyOnActivityRenamed() - { - ActivityRenamed?.Invoke(); - } - // TODO: Give comment summary for all events. public delegate void AddAugmentationButtonClickedDelegate(); @@ -755,6 +748,13 @@ public static void NotifyOnActivityUploadButtonClicked() ActivityUploadButtonClicked?.Invoke(); } + public delegate void ActivityRenamedDelegate(); + public static event ActivityRenamedDelegate ActivityRenamed; + public static void NotifyOnActivityRenamed() + { + ActivityRenamed?.Invoke(); + } + public delegate void ActionStepTitleInputChangedDelegate(); public static event ActionStepTitleInputChangedDelegate ActionStepTitleChanged; public static void NotifyOnActionStepTitleChanged() @@ -819,11 +819,27 @@ public static void NotifyOnMobileAddStepContentPressed() } - public delegate void xAPIChangedDelegate(int option); + public delegate void xAPIChangedDelegate(DBManager.LearningRecordStores option); public static event xAPIChangedDelegate XAPIChanged; - public static void NotifyxAPIChanged(int option) + public static void NotifyxAPIChanged(DBManager.LearningRecordStores option) { XAPIChanged?.Invoke(option); } + + public delegate void MoodleDomainChangedDelegate(); + public static event MoodleDomainChangedDelegate MoodleDomainChanged; + public static void NotifyMoodleDomainChanged() + { + MoodleDomainChanged?.Invoke(); + } + + public delegate void MobileHelpPageChanged(RootView_v2.HelpPage value); + + public static event MobileHelpPageChanged OnMobileHelpPageChanged; + + public static void NotifyMobileHelpPageChanged(RootView_v2.HelpPage value) + { + OnMobileHelpPageChanged?.Invoke(value); + } } } \ No newline at end of file diff --git a/Assets/MirageXR/Player/Scripts/Managers/GhostRecordPlayer.cs b/Assets/MirageXR/Player/Scripts/Managers/GhostRecordPlayer.cs index bce5567ba..71ae6f4b1 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/GhostRecordPlayer.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/GhostRecordPlayer.cs @@ -9,7 +9,7 @@ public class GhostRecordPlayer : MonoBehaviour { private static ActivityManager activityManager => RootObject.Instance.activityManager; [SerializeField] private Transform _head; - + [SerializeField] private Transform _rightHand; [SerializeField] private Transform _leftHand; @@ -17,7 +17,7 @@ public class GhostRecordPlayer : MonoBehaviour [SerializeField] private Transform _lowerSpine; public bool IsPlaying => _isPlaying; - + private bool _isPlaying; private Transform _anchor; private float _cooldown; @@ -50,7 +50,7 @@ public void Play(List ghostFrames, Transform anchor, bool loop, if (anchor == null) throw new ArgumentException("Can't be null", nameof(anchor)); Stop(); - + _forceStop = false; _coroutine = StartCoroutine(PlayIEnumerator(ghostFrames, anchor, loop, cooldown ?? Time.fixedDeltaTime)); } @@ -59,7 +59,7 @@ public void Stop() { _forceStop = true; if (_coroutine == null) return; - + StopCoroutine(_coroutine); _coroutine = null; } @@ -72,15 +72,15 @@ private IEnumerator PlayIEnumerator(IReadOnlyCollection ghostFra var ghostTime = 0f; AudioPlayer audioPlayer = null; - - if (MyToggleObject.option.Contains(":")) - { + + if (MyToggleObject.option.Contains(":")) + { var audioPoi = MyToggleObject.option.Split(':')[1]; var audioAnnotation = activityManager.ActiveAction.enter.activates.Find(a => a.poi == audioPoi); if (audioAnnotation != null) { yield return new WaitForSeconds(0.5f); - // wait for half a second to give the audio object time to spawn + // wait for half a second to give the audio object time to spawn audioPlayer = GameObject.Find(audioAnnotation.poi).GetComponentInChildren(); if (audioPlayer) @@ -103,7 +103,7 @@ private IEnumerator PlayIEnumerator(IReadOnlyCollection ghostFra { SetFrame(ghostFrame, anchor); yield return new WaitForSeconds(framerate); - // if the ghost playback is not behind the audio playback, play the next frame. + // if the ghost playback is not behind the audio playback, play the next frame. } ghostTime += framerate; // Update ghost playback time regardless of whether or not the a frame is played, allows frames to be skiped untill the loop catches up with the audio @@ -123,11 +123,11 @@ private IEnumerator PlayIEnumerator(IReadOnlyCollection ghostFra private void SetFrame(GhostDataFrame ghostFrame, Transform anchor) { - SetPose(_head, ghostFrame.head, anchor); + SetPose(_head, ghostFrame.head, anchor); SetPose(_upperSpine, ghostFrame.upperSpine, anchor); SetPose(_lowerSpine, ghostFrame.lowerSpine, anchor); - SetPose(_rightHand, ghostFrame.rightHand, anchor); - SetPose(_leftHand, ghostFrame.leftHand, anchor); + SetPose(_rightHand, ghostFrame.rightHand, anchor); + SetPose(_leftHand, ghostFrame.leftHand, anchor); } private static void SetPose(Transform obj, Pose pose, Transform anchor) diff --git a/Assets/MirageXR/Player/Scripts/Managers/ObjectFactory.cs b/Assets/MirageXR/Player/Scripts/Managers/ObjectFactory.cs index 3e82a2c49..7c5d9c7bc 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/ObjectFactory.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/ObjectFactory.cs @@ -6,7 +6,7 @@ namespace MirageXR { using BoundsCalculationMethod = Microsoft.MixedReality.Toolkit.UI.BoundsControlTypes.BoundsCalculationMethod; - + public class ObjectFactory : MonoBehaviour { private static ActivityManager activityManager => RootObject.Instance.activityManager; @@ -33,302 +33,302 @@ private static void Toggle(ToggleObject obj, bool isActivating) switch (obj.type) { case ActionType.Tangible: - { - // Check predicate. - switch (obj.predicate) { - // Handle action symbols by default. - default: - if (isActivating) - { - if (obj.id == "ActionsViewport") - { - ActivatePrefab("UiSymbolPrefab", obj); - } - else + // Check predicate. + switch (obj.predicate) + { + // Handle action symbols by default. + default: + if (isActivating) { - // Last minute change for enabling 3D glyph option. - if (obj.predicate.StartsWith("3d:")) - { - obj.option = obj.predicate.Replace("3d:", ""); - - obj.url = "resources://" + obj.predicate; - - ActivatePrefab("Model/ModelPrefab", obj); - } - else if (obj.predicate.StartsWith("act:")) - { - obj.option = obj.predicate.Replace("act:", ""); - - obj.url = "resources://" + obj.predicate; - - var glyphModel = $"Glyphs/{obj.option}"; - ActivatePrefab(glyphModel, obj); - } - else if (obj.predicate.StartsWith("vfx:")) - { - obj.option = obj.predicate.Replace("vfx:", ""); - - obj.url = "resources://" + obj.predicate; - - var vfxModel = $"VFX/{obj.option}"; - ActivatePrefab(vfxModel, obj); - } - else if (obj.predicate.StartsWith("char:")) - { - obj.option = obj.predicate.Replace("char:", ""); - - //obj.predicate = "character"; - obj.url = "resources://" + obj.predicate; - - - var charModel = $"Characters/{obj.option}"; - ActivatePrefab(charModel, obj); - } - else if (obj.predicate.StartsWith("plugin:")) + if (obj.id == "ActionsViewport") { - obj.option = "PluginControllerPrefab"; - - ActivatePrefab(obj.option, obj); + ActivatePrefab("UiSymbolPrefab", obj); } - // True and tested 2D symbols. else { - ActivatePrefab("SymbolPrefab", obj); + // Last minute change for enabling 3D glyph option. + if (obj.predicate.StartsWith("3d:")) + { + obj.option = obj.predicate.Replace("3d:", ""); + + obj.url = "resources://" + obj.predicate; + + ActivatePrefab("Model/ModelPrefab", obj); + } + else if (obj.predicate.StartsWith("act:")) + { + obj.option = obj.predicate.Replace("act:", ""); + + obj.url = "resources://" + obj.predicate; + + var glyphModel = $"Glyphs/{obj.option}"; + ActivatePrefab(glyphModel, obj); + } + else if (obj.predicate.StartsWith("vfx:")) + { + obj.option = obj.predicate.Replace("vfx:", ""); + + obj.url = "resources://" + obj.predicate; + + var vfxModel = $"VFX/{obj.option}"; + ActivatePrefab(vfxModel, obj); + } + else if (obj.predicate.StartsWith("char:")) + { + obj.option = obj.predicate.Replace("char:", ""); + + //obj.predicate = "character"; + obj.url = "resources://" + obj.predicate; + + + var charModel = $"Characters/{obj.option}"; + ActivatePrefab(charModel, obj); + } + else if (obj.predicate.StartsWith("plugin:")) + { + obj.option = "PluginControllerPrefab"; + + ActivatePrefab(obj.option, obj); + } + // True and tested 2D symbols. + else + { + ActivatePrefab("SymbolPrefab", obj); + } } } - } - else - { - if (obj.id == "ActionsViewport") - DestroyPrefab(obj); else { - // Last minute change to enable 3D glyph option. - if (obj.predicate.StartsWith("3d_")) - { - // Let's clean the crap from the name. - obj.option = obj.predicate.Replace("3d_", ""); - - obj.url = "resources://" + obj.predicate; - - obj.predicate = "model"; - - DestroyPrefab(obj); - } - else if (obj.predicate.StartsWith("act:")) - { - obj.option = obj.predicate.Replace("act:", ""); - - //obj.predicate = "glyph"; - obj.url = "resources://" + obj.predicate; - + if (obj.id == "ActionsViewport") DestroyPrefab(obj); - } - else if (obj.predicate.StartsWith("vfx:")) + else { - obj.option = obj.predicate.Replace("vfx:", ""); - - // obj.predicate = "glyph"; - obj.url = "resources:// " + obj.predicate; - - DestroyPrefab(obj); + // Last minute change to enable 3D glyph option. + if (obj.predicate.StartsWith("3d_")) + { + // Let's clean the crap from the name. + obj.option = obj.predicate.Replace("3d_", ""); + + obj.url = "resources://" + obj.predicate; + + obj.predicate = "model"; + + DestroyPrefab(obj); + } + else if (obj.predicate.StartsWith("act:")) + { + obj.option = obj.predicate.Replace("act:", ""); + + //obj.predicate = "glyph"; + obj.url = "resources://" + obj.predicate; + + DestroyPrefab(obj); + } + else if (obj.predicate.StartsWith("vfx:")) + { + obj.option = obj.predicate.Replace("vfx:", ""); + + // obj.predicate = "glyph"; + obj.url = "resources:// " + obj.predicate; + + DestroyPrefab(obj); + } + else if (obj.predicate.StartsWith("char:")) + { + obj.option = obj.predicate.Replace("char:", ""); + + //obj.predicate = "character"; + obj.url = "resources:// " + obj.predicate; + + DestroyPrefab(obj); + } + else if (obj.predicate.StartsWith("plugin:")) + { + DestroyPrefab(obj); + } + // True and tested 2D symbol option. + else + DestroyPrefab(obj); } - else if (obj.predicate.StartsWith("char:")) - { - obj.option = obj.predicate.Replace("char:", ""); - - //obj.predicate = "character"; - obj.url = "resources:// " + obj.predicate; - DestroyPrefab(obj); - } - else if (obj.predicate.StartsWith("plugin:")) - { - DestroyPrefab(obj); - } - // True and tested 2D symbol option. - else - DestroyPrefab(obj); } - } - - break; + break; - // Handle label type. - case "label": - if (isActivating) - { - ActivatePrefab("LabelPrefab", obj); - } - else - { - DestroyPrefab(obj); - } - - break; + // Handle label type. + case "label": + if (isActivating) + { + ActivatePrefab("LabelPrefab", obj); + } + else + { + DestroyPrefab(obj); + } - // Handle detect type. - case "detect": - if (isActivating) - { - ActivatePrefab("DetectPrefab", obj); - } - else - { - DestroyPrefab(obj); - } + break; - break; + // Handle detect type. + case "detect": + if (isActivating) + { + ActivatePrefab("DetectPrefab", obj); + } + else + { + DestroyPrefab(obj); + } - // Audio type. - case "audio": - case "sound": - if (isActivating) - { - ActivatePrefab("AudioPrefab", obj); - } - else - { - DestroyPrefab(obj); - } + break; - break; + // Audio type. + case "audio": + case "sound": + if (isActivating) + { + ActivatePrefab("AudioPrefab", obj); + } + else + { + DestroyPrefab(obj); + } - // Video type. - case "video": - if (isActivating) - { - ActivatePrefab("VideoPrefab", obj); - } - else - { - DestroyPrefab(obj); - } + break; - break; + // Video type. + case "video": + if (isActivating) + { + ActivatePrefab("VideoPrefab", obj); + } + else + { + DestroyPrefab(obj); + } - // Post it label type. - //case "postit": - // if (isActivating) - // ActivatePrefab("PostItPrefab", obj); - // else - // DestroyPrefab(obj); - // break; - - // 3D model type. - case "3dmodel": - case "model": - if (isActivating) - { - ActivatePrefab("ModelPrefab", obj); - } - else - DestroyPrefab(obj); + break; - break; + // Post it label type. + //case "postit": + // if (isActivating) + // ActivatePrefab("PostItPrefab", obj); + // else + // DestroyPrefab(obj); + // break; - // Ghost tracks type. - case "ghosttracks": - if (isActivating) - ActivatePrefab(obj.option.Split(':')[0], obj); - else - DestroyPrefab(obj); - break; + // 3D model type. + case "3dmodel": + case "model": + if (isActivating) + { + ActivatePrefab("ModelPrefab", obj); + } + else + DestroyPrefab(obj); - // Ghost hands type. - case "hands": - if (isActivating) - Debug.Log("hands activated"); - // ActivatePrefab("HandsPrefab", obj); - // else - // DestroyPrefab(obj); - break; + break; - // Image type. - case "image": - if (isActivating) - { - ActivatePrefab("ImagePrefab", obj); - } - else - { - DestroyPrefab(obj); - } + // Ghost tracks type. + case "ghosttracks": + if (isActivating) + ActivatePrefab(obj.option.Split(':')[0], obj); + else + DestroyPrefab(obj); + break; + + // Ghost hands type. + case "hands": + if (isActivating) + Debug.Log("hands activated"); + // ActivatePrefab("HandsPrefab", obj); + // else + // DestroyPrefab(obj); + break; + + // Image type. + case "image": + if (isActivating) + { + ActivatePrefab("ImagePrefab", obj); + } + else + { + DestroyPrefab(obj); + } - break; - // Image type. - case "imagemarker": - if (isActivating) - { - ActivatePrefab("ImageMarkerPrefab", obj); - } - else - { - DestroyPrefab(obj); - } + break; + // Image type. + case "imagemarker": + if (isActivating) + { + ActivatePrefab("ImageMarkerPrefab", obj); + } + else + { + DestroyPrefab(obj); + } - break; + break; - // Potentiometer type. - case "potentiometer": - if (isActivating) - ActivatePrefab("PotentiometerPrefab", obj); - else - DestroyPrefab(obj); - break; + // Potentiometer type. + case "potentiometer": + if (isActivating) + ActivatePrefab("PotentiometerPrefab", obj); + else + DestroyPrefab(obj); + break; - // Show card button type. - case "menutoggle": - if (isActivating) - ActivatePrefab("ShowCardsPrefab", obj); - else - DestroyPrefab(obj); - break; + // Show card button type. + case "menutoggle": + if (isActivating) + ActivatePrefab("ShowCardsPrefab", obj); + else + DestroyPrefab(obj); + break; + + // VTT demo specific hacks. + //case "filterIn": + // if (isActivating) + // ActivatePrefab("FilterIn", obj); + // else + // DestroyPrefab(obj); + // break; + + //case "filterOut": + // if (isActivating) + // ActivatePrefab("FilterOut", obj); + // else + // DestroyPrefab(obj); + // break; + case "pickandplace": + if (isActivating) + ActivatePrefab("pickandplaceprefab", obj); + else + DestroyPrefab(obj); + break; + case "plugin": + if (isActivating) + ActivatePrefab("PluginControllerPrefab", obj); + else + DestroyPrefab(obj); + break; + case "drawing": + if (isActivating) + ActivatePrefab("DrawingPrefab", obj); + else + DestroyPrefab(obj); + break; + } - // VTT demo specific hacks. - //case "filterIn": - // if (isActivating) - // ActivatePrefab("FilterIn", obj); - // else - // DestroyPrefab(obj); - // break; - - //case "filterOut": - // if (isActivating) - // ActivatePrefab("FilterOut", obj); - // else - // DestroyPrefab(obj); - // break; - case "pickandplace": - if (isActivating) - ActivatePrefab("pickandplaceprefab", obj); - else - DestroyPrefab(obj); - break; - case "plugin": - if (isActivating) - ActivatePrefab("PluginControllerPrefab", obj); - else - DestroyPrefab(obj); - break; - case "drawing": - if (isActivating) - ActivatePrefab("DrawingPrefab", obj); - else - DestroyPrefab(obj); - break; + break; } - - break; - } default: - { - EventManager.DebugLog("ObjectFactory: Toggle - Unknown type: " + obj.type); - break; - } + { + EventManager.DebugLog("ObjectFactory: Toggle - Unknown type: " + obj.type); + break; + } } } @@ -395,37 +395,37 @@ private static async void AddExtraComponents(GameObject go, ToggleObject annotat switch (annotationToggleObject.predicate) { case string p when p.Contains("3d"): - { - var obstacle = go.AddComponent(); - obstacle.size = go.transform.localScale / 4; - break; - } - case string p when p.StartsWith("act") || p.StartsWith("vfx") || p.Equals("image") || p.Equals("video"): - { - if (DisableBounding(annotationToggleObject)) return; - var boundingBox = go.AddComponent(); - boundingBox.CustomScaleHandlesConfiguration = Resources.Load("Prefabs/CustomBoundingScaleHandlesConfiguration"); - boundingBox.CustomRotationHandlesConfiguration = Resources.Load("Prefabs/CustomBoundingRotationHandlesConfiguration"); - await boundingBox.AddBoundingBox(annotationToggleObject, BoundsCalculationMethod.RendererOverCollider, false, true, BoundingRotationType.ALL, true); - - // disable rotation for image - if (DisableBoundingRotation(annotationToggleObject)) { - boundingBox.CustomRotationHandlesConfiguration.ShowHandleForX = false; - boundingBox.CustomRotationHandlesConfiguration.ShowHandleForY = false; - boundingBox.CustomRotationHandlesConfiguration.ShowHandleForZ = false; + var obstacle = go.AddComponent(); + obstacle.size = go.transform.localScale / 4; + break; } + case string p when p.StartsWith("act") || p.StartsWith("vfx") || p.Equals("image") || p.Equals("video"): + { + if (DisableBounding(annotationToggleObject)) return; + var boundingBox = go.AddComponent(); + boundingBox.CustomScaleHandlesConfiguration = Resources.Load("Prefabs/CustomBoundingScaleHandlesConfiguration"); + boundingBox.CustomRotationHandlesConfiguration = Resources.Load("Prefabs/CustomBoundingRotationHandlesConfiguration"); + await boundingBox.AddBoundingBox(annotationToggleObject, BoundsCalculationMethod.RendererOverCollider, false, true, BoundingRotationType.ALL, true); + + // disable rotation for image + if (DisableBoundingRotation(annotationToggleObject)) + { + boundingBox.CustomRotationHandlesConfiguration.ShowHandleForX = false; + boundingBox.CustomRotationHandlesConfiguration.ShowHandleForY = false; + boundingBox.CustomRotationHandlesConfiguration.ShowHandleForZ = false; + } - break; - } + break; + } } } - + private static bool DisableBoundingRotation(ToggleObject annotationToggleObject) { return annotationToggleObject.predicate.Equals("image") || annotationToggleObject.predicate.Equals("video"); } - + /// /// If bounding box needs to be disabled for some of the augmentations, add them in this method /// @@ -467,37 +467,37 @@ private static void DestroyPrefab(ToggleObject obj) switch (obj.predicate) { case "label": - { - temp = GameObject.Find($"{path}label_{obj.text.Split(' ')[0]}"); - break; - } + { + temp = GameObject.Find($"{path}label_{obj.text.Split(' ')[0]}"); + break; + } case "3dmodel": case "model": - { - temp = GameObject.Find($"{path}{obj.predicate}_{obj.option}"); - break; - } + { + temp = GameObject.Find($"{path}{obj.predicate}_{obj.option}"); + break; + } case "image": - { - var id = obj.url.Split('/')[obj.url.Split('/').Length - 1]; - temp = GameObject.Find($"{path}{obj.predicate}_{id}"); - break; - } + { + var id = obj.url.Split('/')[obj.url.Split('/').Length - 1]; + temp = GameObject.Find($"{path}{obj.predicate}_{id}"); + break; + } case "imagemarker": - { - GameObject.Find(path).GetComponentInChildren().PlatformOnDestroy(); //TODO: possible NRE - break; - } + { + GameObject.Find(path).GetComponentInChildren().PlatformOnDestroy(); //TODO: possible NRE + break; + } case "pickandplace": - { - temp = GameObject.Find(path + obj.predicate); - break; - } + { + temp = GameObject.Find(path + obj.predicate); + break; + } default: - { - temp = GameObject.Find(path + obj.predicate); - break; - } + { + temp = GameObject.Find(path + obj.predicate); + break; + } } //for all type of glyphs icons diff --git a/Assets/MirageXR/Player/Scripts/Managers/PlatformManager.cs b/Assets/MirageXR/Player/Scripts/Managers/PlatformManager.cs index 2f929989c..80a328dd4 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/PlatformManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/PlatformManager.cs @@ -1,4 +1,4 @@ - using System; +using System; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.XR.ARFoundation; @@ -13,16 +13,16 @@ public class LoadObject public GameObject prefab; public Transform pathToLoad; } - + [Tooltip("If you want to test AR in the editor enable this.")] [SerializeField] bool forceWorldSpaceUi = false; [SerializeField] bool forceToTabletView = false; [SerializeField] private LoadObject[] _worldSpaceObjects; [SerializeField] private LoadObject[] _screenSpaceObjects; - + private float distanceToCamera = 0.5f; private float offsetYFromCamera = 0.5f; - + private bool _worldSpaceUi; private string _playerScene = "Player"; private string _recorderScene = "recorder"; @@ -35,9 +35,6 @@ public class LoadObject public bool WorldSpaceUi => _worldSpaceUi; public string PlayerSceneName => _playerScene; - public string RecorderSceneName => _recorderScene; - - public string CommonSceneName => _commonScene; public string ActivitySelectionScene => _activitySelectionScene; @@ -45,9 +42,13 @@ private void Awake() { //Singleton if (Instance == null) + { Instance = this; + } else if (Instance != this) + { Destroy(gameObject); + } } private void OnDisable() @@ -120,13 +121,6 @@ private static void InstantiateObject(LoadObject loadObject) Instantiate(loadObject.prefab); } } - - public enum DeviceFormat - { - Phone, - Tablet, - Unknown - } public static DeviceFormat GetDeviceFormat() { @@ -134,7 +128,7 @@ public static DeviceFormat GetDeviceFormat() #if UNITY_IOS && !UNITY_EDITOR return UnityEngine.iOS.Device.generation.ToString().Contains("iPad") ? DeviceFormat.Tablet : DeviceFormat.Phone; #elif UNITY_ANDROID && !UNITY_EDITOR - const float minTabletSize = 6.5f; + const float minTabletSize = 7.5f; return GetDeviceDiagonalSizeInInches() > minTabletSize ? DeviceFormat.Tablet : DeviceFormat.Phone; #elif UNITY_WSA && !UNITY_EDITOR return DeviceFormat.Unknown; @@ -143,15 +137,17 @@ public static DeviceFormat GetDeviceFormat() #endif } +#if UNITY_ANDROID && !UNITY_EDITOR private static float GetDeviceDiagonalSizeInInches() { var screenWidth = Screen.width / Screen.dpi; var screenHeight = Screen.height / Screen.dpi; - var diagonalInches = Mathf.Sqrt (Mathf.Pow (screenWidth, 2) + Mathf.Pow (screenHeight, 2)); - - Debug.Log ("Getting device inches: " + diagonalInches); - + var diagonalInches = Mathf.Sqrt(Mathf.Pow(screenWidth, 2) + Mathf.Pow(screenHeight, 2)); + + Debug.Log("Getting device inches: " + diagonalInches); + return diagonalInches; } +#endif } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/ProgressManager.cs b/Assets/MirageXR/Player/Scripts/Managers/ProgressManager.cs index 9e7dafbfa..a7a829a1e 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/ProgressManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/ProgressManager.cs @@ -21,7 +21,7 @@ private void UpdateProgressLine() { var tasks = TaskList.transform.GetComponentsInChildren(); - if (tasks.Length == 0) + if (tasks.Length == 0) return; var counter = 0; @@ -33,10 +33,10 @@ private void UpdateProgressLine() counter++; } - stepStatusLabel.text = "Step " + counter.ToString() + " of " + tasks.Length.ToString() + " is done!"; + stepStatusLabel.text = "Step " + counter.ToString() + " of " + tasks.Length.ToString() + " is done!"; // adjust the progress line if the task list is not empty - progressLine.GetComponent().localScale = new Vector3( (1f / tasks.Length) * counter, 1f, 1f); + progressLine.GetComponent().localScale = new Vector3((1f / tasks.Length) * counter, 1f, 1f); print(counter); } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/TutorialManager.cs b/Assets/MirageXR/Player/Scripts/Managers/TutorialManager.cs index 1dac3d7ab..119d5c29b 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/TutorialManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/TutorialManager.cs @@ -45,8 +45,14 @@ public enum TutorialType /// public bool IsTutorialRunning { get; private set; } - private List steps; - private int currentStepNumber; + private List _steps; + private int _currentStepNumber; + + private List _helpSelections; + private int _currentHelpSelection; + + private Tutorial _mobileTutorial; + private bool _isInEditMode; /// /// TutorialButton on the Hololens UI. @@ -64,12 +70,26 @@ public enum TutorialType /// public TutorialObjectHighlighter MobileHighlighter { get; private set; } - [SerializeField] private TutorialPopup mobilePopup; + [SerializeField] private HelpSelectionPopup _helpSelectionPopup; /// /// The Popup that states the instruction text of a mobile tutorial step. /// Based on the PopupViewer subsystem. /// - public TutorialPopup MobilePopup => mobilePopup; + public HelpSelectionPopup HelpSelectionPopup => _helpSelectionPopup; + + [SerializeField] private HelpPopup _helpPopup; + /// + /// The Popup that states the instruction text of a mobile tutorial step. + /// Based on the PopupViewer subsystem. + /// + public HelpPopup HelpPopup => _helpPopup; + + [SerializeField] private TutorialPopup _mobilePopup; + /// + /// The Popup that states the instruction text of a mobile tutorial step. + /// Based on the PopupViewer subsystem. + /// + public TutorialPopup MobilePopup => _mobilePopup; private void Awake() { @@ -85,8 +105,15 @@ private void Awake() private void Start() { IsTutorialRunning = false; - steps = new List(); + _steps = new List(); + _helpSelections = new List(); MobileHighlighter = new TutorialObjectHighlighter(); + EventManager.OnEditModeChanged += EditModeListener; + } + + private void EditModeListener(bool value) + { + _isInEditMode = value; } /// @@ -108,7 +135,7 @@ public void StartTutorial(TutorialType type) } PopulateStepListForHololens(); - currentStepNumber = -1; + _currentStepNumber = -1; NextStep(); } @@ -117,7 +144,8 @@ public void StartTutorial(TutorialType type) IsTutorialRunning = true; PopulateStepListForMobileEditing(); - currentStepNumber = -1; + + _currentStepNumber = -1; NextStep(); } @@ -126,62 +154,63 @@ public void StartTutorial(TutorialType type) IsTutorialRunning = true; PopulateStepListForMobileViewing(); - currentStepNumber = -1; + _currentStepNumber = -1; NextStep(); } else { Debug.LogError("Tried to start unknown tutorial type."); - } + } } private void PopulateStepListForHololens() { - steps.Clear(); - steps.Add(new StepUnlockActivityMenu()); - steps.Add(new StepDragActivityMenu()); - steps.Add(new StepLockActivityMenu()); - steps.Add(new StepCreateNewActivity()); - steps.Add(new StepDragActionEditor()); - steps.Add(new StepRenameActivity()); - steps.Add(new StepCreateNewActionStep()); - steps.Add(new StepAddActionStepTitle()); - steps.Add(new StepAddActionStepDescription()); + _steps.Clear(); + _steps.Add(new StepUnlockActivityMenu()); + _steps.Add(new StepDragActivityMenu()); + _steps.Add(new StepLockActivityMenu()); + _steps.Add(new StepCreateNewActivity()); + _steps.Add(new StepDragActionEditor()); + _steps.Add(new StepRenameActivity()); + _steps.Add(new StepCreateNewActionStep()); + _steps.Add(new StepAddActionStepTitle()); + _steps.Add(new StepAddActionStepDescription()); //steps.Add(new StepCreateNewAugmentation()); - steps.Add(new StepSelectLabelAugmentation()); - steps.Add(new StepEnterLabelText()); - steps.Add(new StepAddLabelToScene()); - steps.Add(new StepMoveCreatedLabel()); - steps.Add(new StepDeleteActionStep()); - steps.Add(new StepSaveActivity()); - steps.Add(new StepUploadActivity()); + _steps.Add(new StepSelectLabelAugmentation()); + _steps.Add(new StepEnterLabelText()); + _steps.Add(new StepAddLabelToScene()); + _steps.Add(new StepMoveCreatedLabel()); + _steps.Add(new StepDeleteActionStep()); + _steps.Add(new StepSaveActivity()); + _steps.Add(new StepUploadActivity()); } private void PopulateStepListForMobileEditing() { - steps.Clear(); - steps.Add(new MobileStepCreateActivity()); - steps.Add(new MobileStepClickActivityInfo()); - steps.Add(new WaitForMobilePageChangeStep()); - steps.Add(new MobileStepAddActivityName()); - steps.Add(new MobileStepCreateActionStep()); - steps.Add(new MobileStepClickActionStepDetails()); - steps.Add(new WaitForMobilePageChangeStep()); - steps.Add(new MobileStepAddActionStepTitle()); - steps.Add(new MobileStepExpandStepDetails()); - steps.Add(new MobileStepAddActionStepDescription()); - steps.Add(new MobileStepClickAddStepContent()); + _steps.Clear(); + _steps.Add(new MobileStepCreateActivity()); + _steps.Add(new MobileStepClickActivityInfo()); + _steps.Add(new WaitForMobilePageChangeStep()); + _steps.Add(new MobileStepAddActivityName()); + _steps.Add(new MobileStepCreateActionStep()); + _steps.Add(new MobileStepClickActionStepDetails()); + _steps.Add(new WaitForMobilePageChangeStep()); + _steps.Add(new MobileStepAddActionStepTitle()); + _steps.Add(new MobileStepExpandStepDetails()); + _steps.Add(new MobileStepAddActionStepDescription()); + _steps.Add(new MobileStepClickAddStepContent()); string message = "This concludes the tutorial! From here " + "you can choose and add different types of augmentations. " + "Have fun trying them all out."; - steps.Add(new MobileOnlyDialogStep(message)); + _steps.Add(new MobileOnlyDialogStep(message)); } + private void PopulateStepListForMobileViewing() { - steps.Clear(); - steps.Add(new MobileOnlyDialogStep("Coming soon!")); + _steps.Clear(); + _steps.Add(new MobileOnlyDialogStep("Coming soon!")); } /// @@ -191,10 +220,10 @@ private void PopulateStepListForMobileViewing() /// public void NextStep() { - currentStepNumber++; - if (currentStepNumber < steps.Count) + _currentStepNumber++; + if (_currentStepNumber < _steps.Count) { - steps[currentStepNumber].EnterStep(); + _steps[_currentStepNumber].EnterStep(); } else { @@ -207,7 +236,7 @@ public void NextStep() /// public void EndTutorial() { - steps.Clear(); + _steps.Clear(); IsTutorialRunning = false; if (TutorialButton != null) { @@ -224,9 +253,9 @@ public void EndTutorial() /// public void CloseTutorial() { - steps[currentStepNumber].CloseStep(); + _steps[_currentStepNumber].CloseStep(); - steps.Clear(); + _steps.Clear(); IsTutorialRunning = false; if (TutorialButton != null) { @@ -252,5 +281,71 @@ public void ToggleTutorial(TutorialType type) } } + + public void ShowHelpSelection(RootView_v2.HelpPage helpSelection) + { + if (_mobileTutorial == null) + { + _mobileTutorial = RootView_v2.Instance.Tutorial; + } + + bool isEditModeOn = RootObject.Instance.activityManager.EditModeActive; + + var popup = (HelpSelectionPopup)PopupsViewer.Instance.Show(HelpSelectionPopup); + switch (helpSelection) + { + case RootView_v2.HelpPage.Home: + HelpSelectionActivitySelection hsas = new HelpSelectionActivitySelection(); + hsas.Init(popup, _mobileTutorial); + break; + case RootView_v2.HelpPage.ActivitySteps: + HelpSelectionNewActivity hsna = new HelpSelectionNewActivity(); + hsna.Init(popup, _mobileTutorial, isEditModeOn); + break; + case RootView_v2.HelpPage.ActivityInfo: + HelpSelectionActivityInfo hsai = new HelpSelectionActivityInfo(); + hsai.Init(popup, _mobileTutorial); + break; + case RootView_v2.HelpPage.ActivityCalibration: + HelpSelectionActivityCalibration hsac = new HelpSelectionActivityCalibration(); + hsac.Init(popup, _mobileTutorial); + break; + case RootView_v2.HelpPage.ActionAugmentations: + HelpSelectionActionAugmentations hsaa = new HelpSelectionActionAugmentations(); + hsaa.Init(popup, _mobileTutorial, isEditModeOn); + break; + case RootView_v2.HelpPage.ActionInfo: + HelpSelectionActionInfo hsaci = new HelpSelectionActionInfo(); + hsaci.Init(popup, _mobileTutorial); + break; + case RootView_v2.HelpPage.ActionMarker: + // TODO: maybe add something here? + break; + } + } + + public void StartNewMobileEditingTutorial() + { + if (_mobileTutorial == null) + { + _mobileTutorial = RootView_v2.Instance.Tutorial; + } + + var queue = new Queue(); + queue.Enqueue(new TutorialModel { id = "activity_create", message = "Welcome to the MirageXR editing tutorial! To start, let's create a new activity by tapping the plus button below.", btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "activity_info", message = "We should add some info about our activity so it's recognisable. To do this tap the Info tab.", position = TutorialModel.MessagePosition.Middle, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "activity_title", message = "To give our activity a new title, we can tap on the field below.", position = TutorialModel.MessagePosition.Middle, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "activity_description", message = "Activity descriptions help users understand what an activity is about. To add one, we can tap on the field below.", position = TutorialModel.MessagePosition.Middle, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "activity_steps", message = "Now we're going to add some steps to our activity. Tap the Steps tab to continue.", position = TutorialModel.MessagePosition.Middle, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "activity_add_step", message = "Activities consist of steps, which hold content for users to experience. Let's create a new step by tapping the plus button below.", position = TutorialModel.MessagePosition.Top, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "step_edit_step", message = "Empty steps aren't really entertaining. Let's add some content to our step by tapping the Edit Step button.", position = TutorialModel.MessagePosition.Bottom, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "step_info", message = "First let's name and describe our step so users know what to expect. Tap the Info tab to continue.", position = TutorialModel.MessagePosition.Middle, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "step_title", message = "Just like with the Activity, we should add a title...", position = TutorialModel.MessagePosition.Bottom, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "step_description", message = "...and a description to our step.", position = TutorialModel.MessagePosition.Bottom, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "step_augmentations", message = "Finally, lets add some content to our Step. To do so, tap the Augmentations tab.", position = TutorialModel.MessagePosition.Middle, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { id = "step_add_augmentation", message = "Augmentations represent different AR content for our users. A list of possible augmentations can be seen by tapping the plus button.", position = TutorialModel.MessagePosition.Bottom, btnText = "Skip" }); + queue.Enqueue(new TutorialModel { message = "Here you can choose any of the available augmentations to add to the step. More information on each augmentation is available on their info page. This concludes the tutorial, have fun exploring!", position = TutorialModel.MessagePosition.Middle, btnText = "Got it" }); + _mobileTutorial.Show(queue); + } } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/UiManager.cs b/Assets/MirageXR/Player/Scripts/Managers/UiManager.cs index 39ef3c570..7794b9568 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/UiManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/UiManager.cs @@ -9,16 +9,17 @@ namespace MirageXR public class UiManager : MonoBehaviour { private static ActivityManager activityManager => RootObject.Instance.activityManager; + [SerializeField] private bool IsMenuVisible; private bool _inAction; public bool IsFindActive; // Task list location is attached to Hololens main camera. - [Tooltip ("Drag and drop DebugConsole game object here.")] + [Tooltip("Drag and drop DebugConsole game object here.")] public GameObject DebugConsole; - [Tooltip ("Drag and drop Menu game object here.")] + [Tooltip("Drag and drop Menu game object here.")] public GameObject ActionList; public string WelcomeMessage = ""; @@ -32,7 +33,7 @@ private void Awake() Instance = this; } - private void OnEnable () + private void OnEnable() { EventManager.OnPlayerReset += PlayerReset; EventManager.OnMoveActivityList += MoveActivityList; @@ -59,7 +60,7 @@ private void OnEnable () EventManager.OnStartByVoice += StartActivityVoice; } - private void OnDisable () + private void OnDisable() { EventManager.OnPlayerReset -= PlayerReset; EventManager.OnMoveActivityList -= MoveActivityList; @@ -86,13 +87,13 @@ private void OnDisable () EventManager.OnStartByVoice -= StartActivityVoice; } - private void PlayerReset () + private void PlayerReset() { - ClearDebug (); - HideDebug (); + ClearDebug(); + HideDebug(); HideMenu(); - WelcomeMessage = ""; - CalibrationTool.Instance.Reset(); + WelcomeMessage = string.Empty; + CalibrationTool.Instance.isEnabled = false; } private void MoveActivityList() @@ -138,10 +139,10 @@ private void ShowLoading(string activity) HideMenu(); } - private void Start () + private void Start() { // Set default visibility to hidden. - DebugConsole.SetActive (false); + DebugConsole.SetActive(false); //Menu.GetComponent ().alpha = 0; //Menu.GetComponent ().enabled = false; ActionList.gameObject.SetActive(false); @@ -150,25 +151,25 @@ private void Start () /// /// Clear debug console. Called from Hololens keyword manager. /// - public void ClearDebug () + public void ClearDebug() { - DebugConsole.transform.parent.SendMessage ("ClearDebug", SendMessageOptions.DontRequireReceiver); + DebugConsole.transform.parent.SendMessage("ClearDebug", SendMessageOptions.DontRequireReceiver); } /// /// Show debug console. Called from Hololens keyword manager. /// - public void ShowDebug () + public void ShowDebug() { - DebugConsole.SetActive (true); + DebugConsole.SetActive(true); } /// /// Hide debug console. Called from Hololens keyword manager. /// - public void HideDebug () + public void HideDebug() { - DebugConsole.SetActive (false); + DebugConsole.SetActive(false); } /// @@ -197,7 +198,7 @@ public void ShowSelectionPanelTouch() public void HideSelectionPanel() { var ActivitySelectionPanel = FindObjectOfType(); - if(ActivitySelectionPanel != null) + if (ActivitySelectionPanel != null) ActivitySelectionPanel.gameObject.SetActive(false); } @@ -224,8 +225,8 @@ private void CreateCalibrationGuide() // do not create if it is exist already if (!PlatformManager.Instance.WorldSpaceUi || GameObject.Find("CalibrationGuide(Clone)") || GameObject.Find("CalibrationGuide")) return; - - if (IsCalibrated) // create the guild if activity is not calibrated. + + if (IsCalibrated) // create the guild if activity is not calibrated. { var prefab = Resources.Load("Prefabs/Calibration/CalibrationGuide"); var position = PlatformManager.Instance.GetTaskStationPosition() - Vector3.forward * 0.1f; @@ -255,32 +256,32 @@ private async void ShowActivityStart() // Add a small delay just be sure that the message is stopped. await Task.Delay(250); - CalibrationTool.Instance.SetPlayer(); + if (PlatformManager.Instance.WorldSpaceUi) + { + CalibrationTool.Instance.isEnabled = true; + } if (IsCalibrated) { - if (!string.IsNullOrEmpty(WelcomeMessage)) - Maggie.Speak(WelcomeMessage); - else - Maggie.Speak("Activity loaded and ready to be started."); + Maggie.Speak(!string.IsNullOrEmpty(WelcomeMessage) ? WelcomeMessage : "Activity loaded and ready to be started."); } else { // Nag. - //Maggie.Speak("Workplace anchors have not been calibrated. Please run the calibration before starting the activity."); + // Maggie.Speak("Workplace anchors have not been calibrated. Please run the calibration before starting the activity."); CreateCalibrationGuide(); // Hile loading text Loading.Instance.LoadingVisibility(false); } - //EventManager.ActivityLoadedStamp(SystemInfo.deviceUniqueIdentifier, activityManager.Activity.id, System.DateTime.UtcNow.ToUniversalTime().ToString()); + // EventManager.ActivityLoadedStamp(SystemInfo.deviceUniqueIdentifier, activityManager.Activity.id, System.DateTime.UtcNow.ToUniversalTime().ToString()); } private void ActivityStarted() { //WelcomeMessage = activityManager.Activity; - CalibrationTool.Instance.Reset(); + CalibrationTool.Instance.isEnabled = false; switch (PlayerPrefs.GetString("uistyle")) { @@ -291,6 +292,7 @@ private void ActivityStarted() ShowActivityCards(); break; } + _inAction = true; } @@ -302,7 +304,7 @@ private void WorkplaceCalibrated() /// /// Show tasklist. Called from Hololens keyword manager. /// - public void ShowMenu () + public void ShowMenu() { ActionList.gameObject.SetActive(true); @@ -317,7 +319,7 @@ private void ActionListToggleVoice(bool activated) if (!_inAction) return; if (activated) - ShowMenu(); + ShowMenu(); else HideMenu(); } @@ -389,7 +391,7 @@ private void UploadActivityVoice() /// /// Hide tasklist. /// - public void HideMenu () + public void HideMenu() { ActionList.gameObject.SetActive(false); IsMenuVisible = false; @@ -409,7 +411,7 @@ public void HideMenuTouch() /// public void ToggleMenu() { - if(!IsMenuVisible) + if (!IsMenuVisible) ShowMenu(); else HideMenu(); @@ -462,7 +464,7 @@ public void ToggleSensorsTouch() public void ShowActivityCards() { - if(!IsMenuVisible) + if (!IsMenuVisible) ShowMenu(); PlayerPrefs.SetString("uistyle", "cards"); @@ -580,7 +582,7 @@ public void NextVoice() } else { - if(activityManager.IsReady) + if (activityManager.IsReady) StartActivityVoice(); else Maggie.Speak("Please start the activity first."); diff --git a/Assets/MirageXR/Player/Scripts/Managers/WearableManager.cs b/Assets/MirageXR/Player/Scripts/Managers/WearableManager.cs index c466800ba..857f8333f 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/WearableManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/WearableManager.cs @@ -39,11 +39,11 @@ private async void OnDisable() await _mqtt.DisconnectAsync(); } - // Use this for initialization - async void Start () - { - await _mqtt.ConnectAsync(BrokerUrl, BrokerPort); - } + // Use this for initialization + async void Start() + { + await _mqtt.ConnectAsync(BrokerUrl, BrokerPort); + } private async void MqttConnected(bool success) { @@ -100,25 +100,26 @@ private void HandleButton(string state) case "toggle_guides": EventManager.ToggleGuides(); break; - + case "toggle_lock": EventManager.ToggleLock(); break; } } - - // Update is called once per frame - void Update () { - if (!ButtonState.Equals("none") && !ButtonState.Equals(_previousButtonState)) - { - HandleButton(ButtonState); - } - - _previousButtonState = ButtonState; - - if (!Humidity.Equals(0)) - EnvironmentText.text = "Temperature: " + Temperature + " C\n" + "Humidity: " + Humidity + " %"; - else - EnvironmentText.text = ""; - } + + // Update is called once per frame + void Update() + { + if (!ButtonState.Equals("none") && !ButtonState.Equals(_previousButtonState)) + { + HandleButton(ButtonState); + } + + _previousButtonState = ButtonState; + + if (!Humidity.Equals(0)) + EnvironmentText.text = "Temperature: " + Temperature + " C\n" + "Humidity: " + Humidity + " %"; + else + EnvironmentText.text = ""; + } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceManager.cs b/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceManager.cs index b35e426b2..553afae7a 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceManager.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceManager.cs @@ -1,14 +1,9 @@ -using i5.Toolkit.Core.ServiceCore; -using System; -using System.Collections; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Linq; -using System.Reflection; using System.Threading.Tasks; using UnityEngine; -using Vuforia; using Object = UnityEngine.Object; namespace MirageXR @@ -28,7 +23,7 @@ public class WorkplaceManager public Transform sensorContainer { get; private set; } // Device user id. - public static string userID {get; set; } + public static string userID { get; set; } // Frame / configuration pair for anchor calibration. [Serializable] @@ -65,7 +60,7 @@ public void PlayerReset() public async Task LoadWorkplace(string workplaceId) { InitContainers(); - + // empty string => create new workplace if (string.IsNullOrEmpty(workplaceId)) { @@ -103,12 +98,14 @@ private void InitContainers() public static string GetUser() { if (string.IsNullOrEmpty(userID)) + { return "anonymous"; + } return userID; } - - public async Task PerformEditModeCalibration() + + private async Task PerformEditModeCalibration() { Debug.Log("Edit Mode Calibration started.\n"); @@ -141,7 +138,7 @@ public async Task PerformEditModeCalibration() } // here we are writing anchors for calibration pairs that (must) already exist, relative to a calibration origin. - public async Task PerformPlayModeCalibration(Transform calibrationRoot) + private async Task PerformPlayModeCalibration(Transform calibrationRoot) { Debug.Log("Play Mode Calibration started.\n"); @@ -188,7 +185,7 @@ public async Task PerformPlayModeCalibration(Transform calibrationRoot) // Add a small delay just to make sure all the anchors are stored... await Task.Yield(); - //delete calibration animation guide + // delete calibration animation guide var calibrationGuide = GameObject.Find("CalibrationGuide"); if (calibrationGuide) { @@ -221,15 +218,15 @@ public async Task AddPlace(Action newAction, Vector3 targetPosition, bool hasMar Place place = new Place { id = newAction.id, - name = "", + name = string.Empty, detectable = "WA-" + newAction.id.Substring(3), }; Detectable detectable = new Detectable { id = place.detectable, - sensor = "", - url = "", - type = "anchor" + sensor = string.Empty, + url = string.Empty, + type = "anchor", }; if (hasMarker) @@ -241,7 +238,7 @@ public async Task AddPlace(Action newAction, Vector3 targetPosition, bool hasMar workplace.detectables.Add(detectable); workplace.places.Add(place); - //TODO move this to the model + // TODO move this to the model WorkplaceObjectFactory.CreateDetectableObject(detectable, true); await WorkplaceObjectFactory.CreatePlaceObject(place); } @@ -250,34 +247,33 @@ public void AddAnnotation(Action action, ToggleObject toggleObject, Vector3 posi { try { - Place place = GetPlaceFromTaskStationId(action.id); + var place = GetPlaceFromTaskStationId(action.id); - Poi poi = new Poi() + var poi = new Poi { id = toggleObject.poi, x_offset = position.x, y_offset = position.y, z_offset = position.z, offset = $"{position.x.ToString(CultureInfo.InvariantCulture)}, {position.y.ToString(CultureInfo.InvariantCulture)}, {position.z.ToString(CultureInfo.InvariantCulture)}", - rotation = "0, 0, 0" + rotation = "0, 0, 0", }; WorkplaceObjectFactory.CreatePoiObject(poi, GameObject.Find(place.id).transform); place.pois.Add(poi); - }catch (Exception e) + } + catch (Exception e) { Debug.LogError(e); } - } public void DeleteAugmentation(Action action, ToggleObject toggleObject) { - Place place = GetPlaceFromTaskStationId(action.id); + var place = GetPlaceFromTaskStationId(action.id); - - Poi poi = place.pois.Find((item) => item.id == toggleObject.poi); + var poi = place.pois.Find((item) => item.id == toggleObject.poi); if (poi != null) { Object.Destroy(GameObject.Find(poi.id)); @@ -286,12 +282,12 @@ public void DeleteAugmentation(Action action, ToggleObject toggleObject) if (toggleObject.predicate == "imagemarker") { - Detectable detectable = GetDetectable(GetPlaceFromTaskStationId(toggleObject.id)); + var detectable = GetDetectable(GetPlaceFromTaskStationId(toggleObject.id)); - GameObject detectableObj = GameObject.Find(detectable.id); - GameObject detectableParentObj = GameObject.Find("Detectables"); + var detectableObj = GameObject.Find(detectable.id); + var detectableParentObj = GameObject.Find("Detectables"); - //as Vuforia dosent allow image markers to be destroyed at run time the detectable is moved instead leaving the marker still in the scene but removeing its content + // as Vuforia dosent allow image markers to be destroyed at run time the detectable is moved instead leaving the marker still in the scene but removeing its content detectableObj.transform.parent = detectableParentObj.transform; } } @@ -301,9 +297,9 @@ public void DeleteAugmentation(Action action, ToggleObject toggleObject) /// performs changes to the model using the WorkplaceManager's functionality. /// /// Origin transform from the calibration target. - public async Task CalibrateWorkplace(Transform origin) + public async Task CalibrateWorkplace(Transform origin, bool isNewPosition = false) { - if (activityManager.EditModeActive) + if (isNewPosition) { await PerformEditModeCalibration(); } @@ -313,7 +309,7 @@ public async Task CalibrateWorkplace(Transform origin) } await activityManager.StartActivity(); - + EventManager.WorkplaceCalibrated(); Maggie.Speak("Workplace is now calibrated."); } diff --git a/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceObjectFactory.cs b/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceObjectFactory.cs index f7476e814..cbbfa189f 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceObjectFactory.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceObjectFactory.cs @@ -28,11 +28,11 @@ public static async Task CreateDetectablesOrPlaces(List list, string debug { if (element is Detectable) { - CreateDetectableObject((Detectable) (object) element, false); + CreateDetectableObject((Detectable)(object)element, false); } else if (element is Place) { - await CreatePlaceObject( (Place)(object)element ); + await CreatePlaceObject((Place)(object)element); } } catch (Exception e) @@ -455,8 +455,8 @@ public static void CreateDetectableObject(Detectable detectable, bool newObject) // Vuforia image targets. case "image": // Path to local storage. - string[] paths = {Application.persistentDataPath, workplaceManager.workplace.id, "/detectables/", - detectable.id, detectable.id, ".xml"}; + string[] paths = { Application.persistentDataPath, workplaceManager.workplace.id, "/detectables/", + detectable.id, detectable.id, ".xml" }; var path = Path.Combine(paths); Debug.Log("VUFORIA PATH: " + path); @@ -631,46 +631,46 @@ public static async Task CreatePlaceObject(Place place) public static void CreatePoiObject(Poi poi, Transform parent) { - var poiTemp = Utilities.CreateObject(poi.id, parent); - poiTemp.AddComponent().Initialize(poi); - - // If offset not defined as separate values... - if (poi.x_offset.Equals(0) && poi.y_offset.Equals(0) && poi.z_offset.Equals(0)) - { - // Use the CSV format if available. - if (!string.IsNullOrEmpty(poi.offset)) - poiTemp.transform.localPosition = Utilities.ParseStringToVector3(poi.offset); - } - - // Parse offset from separate values. - else - { - poiTemp.transform.localPosition = new Vector3(poi.x_offset, poi.y_offset, poi.z_offset); - } - - if (!string.IsNullOrEmpty(poi.rotation)) - { - if (Utilities.TryParseStringToVector3(poi.rotation, out Vector3 poiVal)) - { - poiTemp.transform.localEulerAngles = poiVal; - } - else - { - Debug.LogError("Problem interpreting rotation value"); - } - } - - if (!string.IsNullOrEmpty(poi.scale)) - { - if (Utilities.TryParseStringToVector3(poi.scale, out Vector3 poiVal)) - { - poiTemp.transform.localScale = poiVal; - } - else - { - Debug.LogError("Problem interpreting poi scale value"); - } - } + var poiTemp = Utilities.CreateObject(poi.id, parent); + poiTemp.AddComponent().Initialize(poi); + + // If offset not defined as separate values... + if (poi.x_offset.Equals(0) && poi.y_offset.Equals(0) && poi.z_offset.Equals(0)) + { + // Use the CSV format if available. + if (!string.IsNullOrEmpty(poi.offset)) + poiTemp.transform.localPosition = Utilities.ParseStringToVector3(poi.offset); + } + + // Parse offset from separate values. + else + { + poiTemp.transform.localPosition = new Vector3(poi.x_offset, poi.y_offset, poi.z_offset); + } + + if (!string.IsNullOrEmpty(poi.rotation)) + { + if (Utilities.TryParseStringToVector3(poi.rotation, out Vector3 poiVal)) + { + poiTemp.transform.localEulerAngles = poiVal; + } + else + { + Debug.LogError("Problem interpreting rotation value"); + } + } + + if (!string.IsNullOrEmpty(poi.scale)) + { + if (Utilities.TryParseStringToVector3(poi.scale, out Vector3 poiVal)) + { + poiTemp.transform.localScale = poiVal; + } + else + { + Debug.LogError("Problem interpreting poi scale value"); + } + } } diff --git a/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceParser.cs b/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceParser.cs index bd0ebda26..1e2dccbc7 100644 --- a/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceParser.cs +++ b/Assets/MirageXR/Player/Scripts/Managers/Workplace/WorkplaceParser.cs @@ -14,7 +14,7 @@ public static class WorkplaceParser public static Workplace Parse(string workplaceId) { var json = GetWorkplaceJson(workplaceId); - return JsonConvert.DeserializeObject(json); + return JsonConvert.DeserializeObject(json); } public static string Serialize(Workplace workplace) diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ActivityListItem.cs b/Assets/MirageXR/Player/Scripts/Mobile/ActivityListItem.cs index fa198a374..d015ecc09 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ActivityListItem.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ActivityListItem.cs @@ -21,12 +21,12 @@ public class ActivityListItem : MonoBehaviour [SerializeField] private Sprite _spriteCloud; [SerializeField] private Sprite _spriteLocal; [SerializeField] private Sprite _spriteDownloaded; - + private SessionContainer _container; private bool _interactable = true; public string activityName => _container.Name; - + public bool interactable { get @@ -41,7 +41,7 @@ public bool interactable _btnEdit.interactable = value; } } - + public void Initialization(SessionContainer container) { _container = container; @@ -57,7 +57,7 @@ private void UpdateView() _txtSize.text = _container.Filesize; _txtDeadline.text = _container.deadline; _txtAuthor.text = _container.author; - + var isLocal = !_container.ExistsRemotely && _container.ExistsLocally && !_container.IsDownloading; var isDownloaded = _container.ExistsRemotely && _container.ExistsLocally && !_container.IsDownloading; var isOnClouds = _container.ExistsRemotely && !_container.ExistsLocally && !_container.IsDownloading; @@ -69,7 +69,7 @@ private void UpdateView() else if (isDownloaded) _imgStatus.sprite = _spriteDownloaded; else if (isOnClouds) _imgStatus.sprite = _spriteCloud; } - + private void OnBtnDelete() { if (_container.ExistsLocally) @@ -80,8 +80,8 @@ private void OnBtnDelete() if (_container.userIsOwner) { - DialogWindow.Instance.Show($"You are trying to delete activity \"{_container.Name}\" from the server. Are you sure?", - new DialogButtonContent("Yes", DeleteFromServer), + DialogWindow.Instance.Show($"You are trying to delete activity \"{_container.Name}\" from the server. Are you sure?", + new DialogButtonContent("Yes", DeleteFromServer), new DialogButtonContent("No")); } } @@ -98,7 +98,7 @@ private async void DeleteFromServer() private void DeleteLocal() { if (_container.Activity == null) return; - + if (LocalFiles.TryDeleteActivity(_container.Activity.id)) { if (_container.ExistsRemotely) @@ -112,7 +112,7 @@ private void DeleteLocal() } } } - + private async void OnBtnMain() { _interactable = false; diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ActivityListView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ActivityListView.cs index b9651e0c1..0da89c9a9 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ActivityListView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ActivityListView.cs @@ -77,10 +77,10 @@ private static async Task> GetContent() } else { - dictionary.Add(t.id, new SessionContainer {Activity = t}); + dictionary.Add(t.id, new SessionContainer { Activity = t }); } }); - + var remoteList = await RootObject.Instance.moodleManager.GetArlemList(); remoteList?.ForEach(t => { @@ -90,7 +90,7 @@ private static async Task> GetContent() } else { - dictionary.Add(t.sessionid, new SessionContainer {Session = t}); + dictionary.Add(t.sessionid, new SessionContainer { Session = t }); } }); @@ -125,7 +125,7 @@ private void OnLoginClick() private void OnHelpClick() { - if(!TutorialManager.Instance.IsTutorialRunning) + if (!TutorialManager.Instance.IsTutorialRunning) { TutorialDialog tDialog = RootView.Instance.TutorialDialog; tDialog.Toggle(); @@ -134,7 +134,7 @@ private void OnHelpClick() { TutorialManager.Instance.CloseTutorial(); } - + } private async void OnAddActivityClick() @@ -142,7 +142,7 @@ private async void OnAddActivityClick() LoadView.Instance.Show(); interactable = false; await RootObject.Instance.editorSceneService.LoadEditorAsync(); - RootObject.Instance.activityManager.CreateNewActivity(); + await RootObject.Instance.activityManager.CreateNewActivity(); interactable = true; LoadView.Instance.Hide(); EventManager.NotifyOnNewActivityCreationButtonPressed(); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/AudioEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/AudioEditorView.cs index 67ebc8c33..e7607799b 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/AudioEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/AudioEditorView.cs @@ -12,16 +12,16 @@ public class AudioEditorView : PopupEditorBase private const float MIN_RANGE = 0.0f; private const float MAX_RANGE = 10.0f; private const float REWIND_VALUE = 10f; - + public override ContentType editorForType => ContentType.AUDIO; - + [SerializeField] private Button _btnRecord; [SerializeField] private Button _btnStop; [SerializeField] private Button _btnPlay; [SerializeField] private Button _btnPause; [SerializeField] private Button _btnRewindBack; [SerializeField] private Button _btnRewindForward; - + [SerializeField] private Toggle _toggleTrigger; [SerializeField] private Toggle _toggle3D; [SerializeField] private Toggle _toggle2D; @@ -29,27 +29,28 @@ public class AudioEditorView : PopupEditorBase [SerializeField] private Slider _sliderRange; [SerializeField] private TMP_Text _txtSliderRangeValue; [SerializeField] private GameObject _panelRange; - + [SerializeField] private TMP_InputField _inputTriggerStepNumber; + [SerializeField] private TMP_Text _txtTimer; [SerializeField] private Slider _sliderPlayer; [SerializeField] private Image _imgRecordingIcon; [SerializeField] private CanvasGroup _groupPlayControls; [SerializeField] private AudioSource _audioSource; - + private AudioClip _audioClip; private string _fileName; private Coroutine _updateSliderPlayerCoroutine; private Coroutine _updateRecordTimerCoroutine; private float _recordStartTime; - + private bool _isRecording; private bool _isPlaying; - - - public override void Init(Action onClose, params object[] args) + + + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); - + base.Initialization(onClose, args); + _toggle3D.isOn = false; _toggleLoop.isOn = false; _sliderRange.minValue = MIN_RANGE; @@ -57,7 +58,7 @@ public override void Init(Action onClose, params object[] args) _sliderRange.value = DEFAULT_RANGE; _txtSliderRangeValue.text = DEFAULT_RANGE.ToString("0"); _panelRange.SetActive(false); - + _btnRecord.onClick.AddListener(OnRecordStarted); _btnStop.onClick.AddListener(OnRecordStopped); _btnPlay.onClick.AddListener(OnPlayingStarted); @@ -68,11 +69,11 @@ public override void Init(Action onClose, params object[] args) _sliderPlayer.minValue = 0; _sliderPlayer.maxValue = 1f; _sliderPlayer.onValueChanged.AddListener(OnSliderPlayerValueChanged); - + _toggleTrigger.onValueChanged.AddListener(OnToggleTriggerValueChanged); _toggle3D.onValueChanged.AddListener(On3DSelected); _sliderRange.onValueChanged.AddListener(OnSliderRangeValueChanged); - + if (_content != null && !string.IsNullOrEmpty(_content.url)) { LoadContent(); @@ -81,6 +82,7 @@ public override void Init(Action onClose, params object[] args) if (trigger != null) { _toggleTrigger.isOn = true; + _inputTriggerStepNumber.text = trigger.value; } } else @@ -88,7 +90,7 @@ public override void Init(Action onClose, params object[] args) _fileName = $"MirageXR_Audio_{DateTime.Now.ToFileTimeUtc()}.wav"; _groupPlayControls.interactable = false; } - + SetPlayerActive(true); UpdateSliderPlayerAndTimer(); } @@ -122,11 +124,11 @@ private void LoadContent() } } } - + private void OnPlayingStarted() { if (!_audioClip) return; - + if (_audioSource.clip && _audioSource.time > 0) { _audioSource.UnPause(); @@ -146,7 +148,7 @@ private static string GetFileName(ToggleObject content) var fileName = content.url.StartsWith(httpPrefix) ? content.url.Remove(0, httpPrefix.Length) : content.url; return fileName; } - + private void OnPlayingPaused() { _audioSource.Pause(); @@ -157,7 +159,7 @@ private void OnRewindBack() _audioSource.time = Mathf.Max(_audioSource.time - REWIND_VALUE, 0); UpdateSliderPlayerAndTimer(); } - + private void OnRewindForward() { _audioSource.time = Mathf.Min(_audioSource.time + REWIND_VALUE, _audioClip.length - 0.1f); @@ -172,14 +174,14 @@ private void OnRecordStarted() Destroy(_audioClip); _audioClip = null; } - + SetPlayerActive(false); _recordStartTime = Time.unscaledTime; AudioRecorder.Start(_fileName); StartUpdateRecordTimer(); } - + private void OnRecordStopped() { _recordStartTime = 0; @@ -204,10 +206,10 @@ private IEnumerator UpdateSliderPlayerAndTimerIEnumerator() } UpdateSliderPlayerAndTimer(); } - + private void UpdateSliderPlayerAndTimer() { - var clip = _audioSource.clip; + var clip = _audioSource.clip; if (clip) { var percent = _audioSource.time / clip.length; @@ -219,7 +221,7 @@ private void UpdateSliderPlayerAndTimer() if (Math.Abs(_audioSource.time - clip.length) <= float.Epsilon) { OnPlayingFinished(); - } + } } else { @@ -241,7 +243,7 @@ private void OnPlayingFinished() StopCoroutine(_updateSliderPlayerCoroutine); } } - + private void ResetPlayerTimer() { _sliderPlayer.onValueChanged.RemoveListener(OnSliderPlayerValueChanged); @@ -249,7 +251,7 @@ private void ResetPlayerTimer() _txtTimer.text = ToTimeFormat(0); _sliderPlayer.onValueChanged.AddListener(OnSliderPlayerValueChanged); } - + private void StartUpdateRecordTimer() { _updateRecordTimerCoroutine = StartCoroutine(UpdateRecordTimerIEnumerator()); @@ -258,7 +260,7 @@ private void StartUpdateRecordTimer() private IEnumerator UpdateRecordTimerIEnumerator() { const float second = 1.0f; - + while (AudioRecorder.IsRecording) { UpdateRecordTimer(); @@ -266,7 +268,7 @@ private IEnumerator UpdateRecordTimerIEnumerator() } UpdateRecordTimer(); } - + private void UpdateRecordTimer() { _txtTimer.text = ToTimeFormat(Time.unscaledTime - _recordStartTime); @@ -285,12 +287,12 @@ private void SetPlayerActive(bool value) _groupPlayControls.gameObject.SetActive(value); _sliderPlayer.gameObject.SetActive(value); } - + private void On3DSelected(bool value) { _panelRange.SetActive(value); } - + private void OnSliderRangeValueChanged(float value) { _txtSliderRangeValue.text = value.ToString("0"); @@ -300,7 +302,7 @@ private void OnSliderPlayerValueChanged(float value) { _audioSource.time = _audioClip.length * value; } - + private void OnToggleTriggerValueChanged(bool value) { if (value && activityManager.IsLastAction(_step)) @@ -312,10 +314,18 @@ private void OnToggleTriggerValueChanged(bool value) return; } - if (value) _toggleLoop.isOn = false; + if (value) + { + _toggleLoop.isOn = false; + _inputTriggerStepNumber.transform.parent.gameObject.SetActive(true); + } + else + { + _inputTriggerStepNumber.transform.parent.gameObject.SetActive(false); + } _toggleLoop.interactable = _toggle3D.isOn && !value; } - + protected override void OnAccept() { if (!_audioClip) @@ -323,12 +333,12 @@ protected override void OnAccept() Toast.Instance.Show("The audio has not been recorded"); return; } - + var filePath = Path.Combine(activityManager.ActivityPath, _fileName); if (_content != null) { _fileName = GetFileName(_content); - + if (File.Exists(filePath) && _audioClip != null) { EventManager.DeactivateObject(_content); @@ -347,17 +357,23 @@ protected override void OnAccept() _content.scale = 0.5f; _content.url = $"http://{_fileName}"; + if (_inputTriggerStepNumber.text == "" && _toggleTrigger.isOn) + { + Toast.Instance.Show("Input field is empty."); + return; + } + if (_toggleTrigger.isOn) { - _step.AddOrReplaceArlemTrigger(TriggerMode.Audio, ActionType.Audio, _content.poi, _audioClip.length, string.Empty); + _step.AddOrReplaceArlemTrigger(TriggerMode.Audio, ActionType.Audio, _content.poi, _audioClip.length, _inputTriggerStepNumber.text); } else { _step.RemoveArlemTrigger(_content); } - + SaveLoadAudioUtilities.Save(filePath, _audioClip); - + EventManager.ActivateObject(_content); EventManager.NotifyActionModified(_step); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/CharacterEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/CharacterEditorView.cs index 34fa643a8..6fa524988 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/CharacterEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/CharacterEditorView.cs @@ -8,20 +8,20 @@ public class CharacterEditorView : PopupEditorBase { public override ContentType editorForType => ContentType.CHARACTER; - + [SerializeField] private Destination _destinationPrefab; [SerializeField] private Transform _contentContainer; [SerializeField] private CharacterListItem _characterListItemPrefab; [SerializeField] private CharacterObject[] _characterObjects; private string _prefabName; - - public override void Init(Action onClose, params object[] args) + + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); UpdateView(); } - + private void UpdateView() { for (int i = _contentContainer.childCount - 1; i >= 0; i--) @@ -29,7 +29,7 @@ private void UpdateView() var child = _contentContainer.GetChild(i); Destroy(child); } - + foreach (var characterObject in _characterObjects) { var item = Instantiate(_characterListItemPrefab, _contentContainer); @@ -40,11 +40,11 @@ private void UpdateView() private async void SetupCharacter() { const string movementType = "followpath"; - + var characterObjectName = $"{_content.id}/{_content.poi}/{_content.predicate}"; var character = GameObject.Find(characterObjectName); // TODO: possible NRE - while(character == null) + while (character == null) { character = GameObject.Find(characterObjectName); // TODO: possible NRE await Task.Delay(10); @@ -53,12 +53,12 @@ private async void SetupCharacter() var characterController = character.GetComponent(); characterController.MovementType = movementType; characterController.AgentReturnAtTheEnd = false; - + var destinations = new List(); var taskStationPosition = TaskStationDetailMenu.Instance.ActiveTaskStation.transform.position; character.transform.position = taskStationPosition; var destination = Instantiate(_destinationPrefab, taskStationPosition - Vector3.up, Quaternion.identity); - destination.transform.rotation *= Quaternion.Euler(0, 180 , 0); + destination.transform.rotation *= Quaternion.Euler(0, 180, 0); destination.MyCharacter = characterController; destination.transform.SetParent(character.transform.parent); destinations.Add(destination.gameObject); @@ -67,13 +67,13 @@ private async void SetupCharacter() characterController.AudioEditorCheck(); characterController.MyAction = _step; } - + private void OnAccept(string prefabName) { _prefabName = prefabName; OnAccept(); } - + protected override void OnAccept() { if (_content != null) diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/DirectLoginPopup.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/DirectLoginPopup.cs index 8a02e3564..61cccacb9 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/DirectLoginPopup.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/DirectLoginPopup.cs @@ -19,9 +19,9 @@ public class DirectLoginPopup : PopupBase private string _clientId; private string _appSecret; - public override void Init(Action onClose, params object[] args) + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); _usernameInputField.SetValidator(IsValidUsername); _passwordInputField.SetValidator(IsValidPassword); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GhostEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GhostEditorView.cs index f76199661..4debe1ea1 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GhostEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GhostEditorView.cs @@ -18,17 +18,17 @@ public class GhostEditorView : PopupEditorBase [SerializeField] private Button _btnStop; private readonly GhostRecorder _ghostRecorder = new GhostRecorder(); - + private string _ghostFileName; private string _audioFileName; private List _ghostFrames; private AudioClip _audioClip; private Transform _anchor; - - public override void Init(Action onClose, params object[] args) + + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); - + base.Initialization(onClose, args); + _btnStart.onClick.AddListener(StartRecording); _btnStop.onClick.AddListener(StopRecording); _toggleMale.isOn = true; @@ -44,10 +44,10 @@ private void StartRecording() { var timeStamp = DateTime.Now.ToFileTimeUtc(); _ghostFileName = $"MirageXR_Ghost_{timeStamp}.xml"; - _audioFileName = $"MirageXR_Audio_{timeStamp}.wav"; + _audioFileName = $"MirageXR_Audio_{timeStamp}.wav"; _anchor = GameObject.Find(_step.id).transform; //TODO: possible NRE. replace with direct ref - + _ghostRecorder.Start(_anchor, Camera.main.transform); if (_toggleAudio.isOn) AudioRecorder.Start(_audioFileName); @@ -68,7 +68,7 @@ private void SetTogglesActive(bool value) _toggleMale.interactable = value; _toggleFemale.interactable = value; } - + protected override void OnAccept() { if (_ghostFrames == null || _ghostFrames.Count == 0) @@ -78,21 +78,22 @@ protected override void OnAccept() } var offset = GetOffset(); - + if (_content != null) { DeactivateContent(_content); } - else { + else + { _content = augmentationManager.AddAugmentation(_step, offset); _content.predicate = editorForType.GetPredicate(); } - + _content.option = _toggleMale.isOn ? MALE_TYPE : FEMALE_TYPE; - + var ghostFilePath = Path.Combine(activityManager.ActivityPath, _ghostFileName); GhostRecorder.ExportToFile(ghostFilePath, _ghostFrames); - + _content.url = HTTP_PREFIX + _ghostFileName; _content.position = _anchor.position.ToString(); _content.rotation = _anchor.rotation.ToString(); @@ -104,7 +105,7 @@ protected override void OnAccept() _content.option += $":{audioContent.poi}"; EventManager.ActivateObject(audioContent); } - + EventManager.ActivateObject(_content); EventManager.NotifyActionModified(_step); Close(); @@ -114,14 +115,14 @@ private ToggleObject SaveAudio(Vector3 offset) { var audioFilePath = Path.Combine(activityManager.ActivityPath, _audioFileName); SaveLoadAudioUtilities.Save(audioFilePath, _audioClip); - + var audioContent = augmentationManager.AddAugmentation(_step, offset); audioContent.predicate = ContentType.AUDIO.GetPredicate(); audioContent.scale = 0.5f; - audioContent.url = HTTP_PREFIX + _audioFileName; + audioContent.url = HTTP_PREFIX + _audioFileName; return audioContent; } - + private static void DeactivateContent(ToggleObject content) { var fileName = content.url.Replace(HTTP_PREFIX, string.Empty); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GlyphEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GlyphEditorView.cs index 9b96fb93f..c7dc75f4b 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GlyphEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/GlyphEditorView.cs @@ -9,9 +9,9 @@ public class GlyphEditorView : PopupEditorBase private const float MIN_SLIDER_VALUE = 1; private const float MAX_SLIDER_VALUE = 10; private const float DEFAULT_SLIDER_VALUE = 3; - + public override ContentType editorForType => ContentType.ACT; - + [SerializeField] private Transform _contentContainer; [SerializeField] private GlyphListItem _glyphListItemPrefab; [SerializeField] private Toggle _toggleTrigger; @@ -26,12 +26,12 @@ public class GlyphEditorView : PopupEditorBase private float _gazeDuration; private int _triggerStepIndex; private string _prefabName; - + private int _maxStepIndex => activityManager.ActionsOfTypeAction.Count - 1; - - public override void Init(Action onClose, params object[] args) + + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); _toggleTrigger.onValueChanged.AddListener(OnTriggerValueChanged); _slider.onValueChanged.AddListener(OnSliderValueChanged); _btnNextStep.onClick.AddListener(OnNextToClick); @@ -39,7 +39,7 @@ public override void Init(Action onClose, params object[] args) UpdateView(); } - + private void UpdateView() { _slider.minValue = MIN_SLIDER_VALUE; @@ -47,19 +47,20 @@ private void UpdateView() _toggleTrigger.isOn = false; _slider.value = DEFAULT_SLIDER_VALUE; - + OnSliderValueChanged(_slider.value); + for (int i = _contentContainer.childCount - 1; i >= 0; i--) { var child = _contentContainer.GetChild(i); Destroy(child); } - + foreach (var actionObject in _actionObjects) { var item = Instantiate(_glyphListItemPrefab, _contentContainer); item.Init(actionObject, OnAccept); } - + _triggerStepIndex = activityManager.ActionsOfTypeAction.IndexOf(_step); var isLastStep = activityManager.IsLastAction(_step); @@ -67,7 +68,7 @@ private void UpdateView() { _triggerStepIndex = isLastStep ? _triggerStepIndex - 1 : _triggerStepIndex + 1; } - + if (_content != null) { _trigger = _step.triggers.Find(tr => tr.id == _content.poi); @@ -92,27 +93,27 @@ private void OnSliderValueChanged(float value) _gazeDuration = value; _txtSliderValue.text = $"{_gazeDuration} sec"; } - + private void OnNextToClick() { if (_triggerStepIndex >= _maxStepIndex) return; _triggerStepIndex++; _txtStep.text = (_triggerStepIndex + 1).ToString(); } - + private void OnPreviousToClick() { if (_triggerStepIndex <= 0) return; _triggerStepIndex--; _txtStep.text = (_triggerStepIndex + 1).ToString(); } - + private void OnAccept(string prefabName) { _prefabName = prefabName; OnAccept(); } - + protected override void OnAccept() { if (_content != null) @@ -125,7 +126,7 @@ protected override void OnAccept() } _content.predicate = $"act:{_prefabName}"; - + if (_toggleTrigger.isOn) { _step.AddOrReplaceArlemTrigger(TriggerMode.Detect, ActionType.Act, _content.poi, _gazeDuration, (_triggerStepIndex + 1).ToString()); @@ -134,7 +135,7 @@ protected override void OnAccept() { _step.RemoveArlemTrigger(_content); } - + EventManager.ActivateObject(_content); EventManager.NotifyActionModified(_step); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageEditorView.cs index a3445c899..cf380a7d6 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageEditorView.cs @@ -9,6 +9,7 @@ public class ImageEditorView : PopupEditorBase { private static ActivityManager activityManager => RootObject.Instance.activityManager; + private static AugmentationManager augmentationManager => RootObject.Instance.augmentationManager; public override ContentType editorForType => ContentType.IMAGE; @@ -24,9 +25,9 @@ public class ImageEditorView : PopupEditorBase private Texture2D _capturedImage; - public override void Init(Action onClose, params object[] args) + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); UpdateView(); _btnCaptureImage.onClick.AddListener(OnCaptureImage); @@ -69,7 +70,6 @@ protected override void OnAccept() _content.key = _orientation ? LANDSCAPE : PORTRAIT; - var saveFileName = $"MirageXR_Image_{DateTime.Now.ToFileTimeUtc()}.jpg"; var outputPath = Path.Combine(activityManager.ActivityPath, saveFileName); File.WriteAllBytes(outputPath, _capturedImage.EncodeToJPG()); @@ -114,13 +114,20 @@ private void CaptureImage() private void OnPictureTaken(bool result, Texture2D texture2D) { VuforiaBehaviour.Instance.enabled = true; - if (!result) return; + if (!result) + { + return; + } + SetPreview(texture2D); } private void SetPreview(Texture2D texture2D) { - if (_capturedImage) Destroy(_capturedImage); + if (_capturedImage) + { + Destroy(_capturedImage); + } _capturedImage = texture2D; var sprite = Utilities.TextureToSprite(_capturedImage); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageMarkerEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageMarkerEditorView.cs index 8e9c49c33..445cf8c60 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageMarkerEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ImageMarkerEditorView.cs @@ -19,9 +19,9 @@ public class ImageMarkerEditorView : PopupEditorBase private Texture2D _capturedImage; - public override void Init(Action onClose, params object[] args) + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); UpdateView(); _btnCaptureImage.onClick.AddListener(OnCaptureImage); } @@ -69,10 +69,10 @@ protected override void OnAccept() var saveFileName = $"MirageXR_Image_{DateTime.Now.ToFileTimeUtc()}.jpg"; var outputPath = Path.Combine(activityManager.ActivityPath, saveFileName); File.WriteAllBytes(outputPath, _capturedImage.EncodeToJPG()); - + _content.url = RESOURCES_PREFIX + saveFileName; _content.scale = size / 100; - + EventManager.ActivateObject(_content); EventManager.NotifyActionModified(_step); Close(); @@ -84,11 +84,11 @@ private void UpdateView() { var originalFileName = Path.GetFileName(_content.url.Remove(0, RESOURCES_PREFIX.Length)); var originalFilePath = Path.Combine(activityManager.ActivityPath, originalFileName); - + if (!File.Exists(originalFilePath)) return; _tmpInputSize.text = (_content.scale * 100).ToString(CultureInfo.InvariantCulture); - + var texture2D = Utilities.LoadTexture(originalFilePath); SetPreview(texture2D); } @@ -104,7 +104,7 @@ private void CaptureImage() VuforiaBehaviour.Instance.enabled = false; NativeCameraController.TakePicture(OnPictureTaken); } - + private void OnPictureTaken(bool result, Texture2D texture2D) { VuforiaBehaviour.Instance.enabled = true; @@ -115,7 +115,7 @@ private void OnPictureTaken(bool result, Texture2D texture2D) private void SetPreview(Texture2D texture2D) { if (_capturedImage) Destroy(_capturedImage); - + _capturedImage = texture2D; var sprite = Utilities.TextureToSprite(_capturedImage); _image.sprite = sprite; @@ -124,7 +124,7 @@ private void SetPreview(Texture2D texture2D) var rtImage = (RectTransform)_image.transform; var height = rtImage.rect.width / _capturedImage.width * _capturedImage.height + (rtImage.sizeDelta.y * -1); rtImageHolder.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height); - + LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)transform); } } \ No newline at end of file diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/LabelEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/LabelEditorView.cs index 92a6707d3..dc3151956 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/LabelEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/LabelEditorView.cs @@ -9,9 +9,9 @@ public class LabelEditorView : PopupEditorBase private const float MIN_SLIDER_VALUE = 1; private const float MAX_SLIDER_VALUE = 10; private const float DEFAULT_SLIDER_VALUE = 3; - + public override ContentType editorForType => ContentType.LABEL; - + [SerializeField] private TMP_InputField _inputField; [SerializeField] private Toggle _toggleTrigger; [SerializeField] private Slider _slider; @@ -23,12 +23,12 @@ public class LabelEditorView : PopupEditorBase private Trigger _trigger; private float _gazeDuration; private int _triggerStepIndex; - + private int _maxStepIndex => activityManager.ActionsOfTypeAction.Count - 1; - - public override void Init(Action onClose, params object[] args) + + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); _toggleTrigger.onValueChanged.AddListener(OnTriggerValueChanged); _slider.onValueChanged.AddListener(OnSliderValueChanged); _btnNextStep.onClick.AddListener(OnNextToClick); @@ -44,7 +44,7 @@ private void UpdateView() _inputField.text = string.Empty; _toggleTrigger.isOn = false; _slider.value = DEFAULT_SLIDER_VALUE; - + _triggerStepIndex = activityManager.ActionsOfTypeAction.IndexOf(_step); var isLastStep = activityManager.IsLastAction(_step); @@ -52,7 +52,7 @@ private void UpdateView() { _triggerStepIndex = isLastStep ? _triggerStepIndex - 1 : _triggerStepIndex + 1; } - + if (_content != null) { _inputField.text = _content.text; @@ -65,7 +65,7 @@ private void UpdateView() OnSliderValueChanged(_trigger.duration); } } - + _txtStep.text = (_triggerStepIndex + 1).ToString(); _slider.interactable = _toggleTrigger.isOn; } @@ -80,14 +80,14 @@ private void OnSliderValueChanged(float value) _gazeDuration = value; _txtSliderValue.text = $"{_gazeDuration} sec"; } - + private void OnNextToClick() { if (_triggerStepIndex >= _maxStepIndex) return; _triggerStepIndex++; _txtStep.text = (_triggerStepIndex + 1).ToString(); } - + private void OnPreviousToClick() { if (_triggerStepIndex <= 0) return; @@ -102,7 +102,7 @@ protected override void OnAccept() Toast.Instance.Show("Input field is empty."); return; } - + if (_content != null) { EventManager.DeactivateObject(_content); diff --git a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ModelEditorView.cs b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ModelEditorView.cs index f12c94c80..ebb952543 100644 --- a/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ModelEditorView.cs +++ b/Assets/MirageXR/Player/Scripts/Mobile/ContentEditors/ModelEditorView.cs @@ -12,9 +12,9 @@ public class ModelEditorView : PopupEditorBase { private const int RESULTS_PER_PAGE = 20; - + public override ContentType editorForType => ContentType.MODEL; - + [SerializeField] private Transform _contentContainer; [SerializeField] private ScrollRect _scroll; [SerializeField] private ModelListItem _modelListItemPrefab; @@ -36,19 +36,19 @@ public class ModelEditorView : PopupEditorBase private int _pageIndex; private readonly List _items = new List(); - - public override void Init(Action onClose, params object[] args) + + public override void Initialization(Action onClose, params object[] args) { - base.Init(onClose, args); + base.Initialization(onClose, args); - if (!CheckAndLoadCredentials()) return; + if (!CheckAndLoadCredentials()) return; _btnSearch.onClick.AddListener(OnSearchClicked); _btnLogout.onClick.AddListener(OnLogoutClicked); _toggleLocal.onValueChanged.AddListener(OnToggleLocalValueChanged); ResetView(); } - + private void ResetView() { _pageIndex = 0; @@ -63,13 +63,13 @@ private void ResetView() else { DialogWindow.Instance.Show("Login to Sketchfab", - new DialogButtonContent("Via the browser", LoginToSketchfab), + //new DialogButtonContent("Via the browser", LoginToSketchfab), new DialogButtonContent("With password", ShowDirectLoginPopup), new DialogButtonContent("Cancel", Close)); } Clear(); } - + private async void RenewToken() { await RenewTokenAsync(); @@ -79,7 +79,7 @@ private async Task RenewTokenAsync() { var clientId = _clientDirectLoginDataObject.clientData.ClientId; var clientSecret = _clientDirectLoginDataObject.clientData.ClientSecret; - + var (result, json) = await MirageXR.Sketchfab.RenewTokenAsync(_renewToken, clientId, clientSecret); var response = JsonConvert.DeserializeObject(json); if (result) @@ -93,7 +93,7 @@ private async Task RenewTokenAsync() } } } - + private bool CheckAndLoadCredentials() { if (_clientDataObject == null) @@ -116,7 +116,7 @@ private bool CheckAndLoadCredentials() return true; } - + private void OnToggleLocalValueChanged(bool value) { _inputSearch.text = string.Empty; @@ -128,8 +128,8 @@ private void OnToggleLocalValueChanged(bool value) { ShowRemoteModels(); } - } - + } + private void ShowLocalModels() { Clear(); @@ -146,13 +146,13 @@ private void ShowRemoteModels() { Clear(); } - + private void AddLoadMoreButton() { _loadMoreObject = Instantiate(_loadMorePrefab, _contentContainer); _loadMoreObject.GetComponentInChildren