/// <summary> /// "Recognized" events are fired when the end of utterance was detected by the server /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RecognizedHandler(object sender, SpeechRecognitionEventArgs e) { if (e.Result.Reason == ResultReason.RecognizedSpeech) { UnityEngine.Debug.LogFormat($"RECOGNIZED: Text={e.Result.Text}"); recognizedString = $"You said: {Environment.NewLine}{e.Result.Text}"; UnityDispatcher.InvokeOnAppThread(() => { UpdateUI(); }); // Send the recognized text as input to the bot framework via the DirectLine API SendBotRequestMessage(e.Result.Text); } else if (e.Result.Reason == ResultReason.NoMatch) { UnityEngine.Debug.LogFormat($"NOMATCH: Speech could not be recognized."); } RecognizerCleanup(false); isRecognizing = false; }
protected void OnCloudAnchorLocated(AnchorLocatedEventArgs args) { if (args.Status == LocateAnchorStatus.Located) { currentCloudAnchor = args.Anchor; UnityDispatcher.InvokeOnAppThread(() => { Pose anchorPose = Pose.identity; #if UNITY_ANDROID || UNITY_IOS anchorPose = currentCloudAnchor.GetPose(); #endif // HoloLens: The position will be set based on the unityARUserAnchor that was located. SpawnOrMoveCurrentAnchoredObject(anchorPose.position, anchorPose.rotation); }); } }
protected override void OnCloudAnchorLocated(AnchorLocatedEventArgs args) { base.OnCloudAnchorLocated(args); if (args.Status == LocateAnchorStatus.Located) { currentCloudAnchor = args.Anchor; UnityDispatcher.InvokeOnAppThread(() => { currentAppState = AppState.DemoStepDeleteFoundAnchor; Pose anchorPose = Pose.identity; // HoloLens: The position will be set based on the unityARUserAnchor that was located. SpawnOrMoveCurrentAnchoredObject(anchorPose.position, anchorPose.rotation); }); } }
/// <summary> /// Stops the microphone recording and saves to a WAV file. Used to validate WAV format. /// </summary> public void StopRecording() { Debug.Log("Stopping microphone recording."); UnityDispatcher.InvokeOnAppThread(() => { audiosource.Stop(); Microphone.End(null); if (isRecording) { var audioData = new byte[recordingData.Count]; recordingData.CopyTo(audioData); WriteAudioDataToRiffWAVFile(audioData, "recording.wav"); isRecording = false; isRecognizing = false; } Debug.Log($"Microphone stopped recording at frequency {audiosource.clip.frequency}Hz."); }); }
protected override void OnCloudAnchorLocated(AnchorLocatedEventArgs args) { base.OnCloudAnchorLocated(args); if (args.Status == LocateAnchorStatus.Located) { currentCloudAnchor = args.Anchor; UnityDispatcher.InvokeOnAppThread(() => { Pose anchorPose = Pose.identity; anchorPose = currentCloudAnchor.GetPose(); SpawnOrMoveCurrentAnchoredObject(anchorPose.position, anchorPose.rotation); currentAppState = AppState.DemoStepDeleteFoundAnchor; }); } }
private void Awake() { Assert.IsNull(_instance, "There must be only one instance of Patcher component."); Assert.IsNotNull(ErrorDialog, "ErrorDialog must be set."); _instance = this; UnityDispatcher.Initialize(); Application.runInBackground = true; DebugLogger.LogFormat("patchkit-patcher-unity: {0}", PatcherInfo.GetVersion()); DebugLogger.LogFormat("System version: {0}", EnvironmentInfo.GetSystemVersion()); DebugLogger.LogFormat("Runtime version: {0}", EnvironmentInfo.GetSystemVersion()); CheckEditorAppSecretSecure(); if (_canStartThread) { StartThread(); } }
/// <summary> /// For each anchor located by the spatial anchor manager, instantiate and setup a corresponding GameObject. /// </summary> private void SpatialAnchorManagerAnchorLocated(object sender, AnchorLocatedEventArgs args) { Debug.Log($"Anchor recognized as a possible anchor {args.Identifier} {args.Status}"); if (args.Status == LocateAnchorStatus.Located) { UnityDispatcher.InvokeOnAppThread(() => { CloudSpatialAnchor cloudSpatialAnchor = args.Anchor; Pose anchorPose = cloudSpatialAnchor.GetPose(); GameObject anchorGameObject = Instantiate(m_sampleSpatialAnchorPrefab, anchorPose.position, anchorPose.rotation); anchorGameObject.AddComponent <CloudNativeAnchor>().CloudToNative(cloudSpatialAnchor); anchorGameObject.GetComponent <SampleSpatialAnchor>().Identifier = cloudSpatialAnchor.Identifier; anchorGameObject.GetComponent <SampleSpatialAnchor>().Persisted = true; m_foundOrCreatedAnchorObjects.Add(anchorGameObject); }); } }
private void CloudManagerOnAnchorLocated(object sender, AnchorLocatedEventArgs args) { if (args.Status == LocateAnchorStatus.Located) { feedbackBox.text = $"Found anchor: {args.Anchor.Identifier}"; var currentCloudAnchor = args.Anchor; UnityDispatcher.InvokeOnAppThread(() => { Pose anchorPose = Pose.identity; #if UNITY_ANDROID || UNITY_IOS anchorPose = currentCloudAnchor.GetPose(); #endif // HoloLens: The position will be set based on the unityARUserAnchor that was located. //SpawnOrMoveCurrentAnchoredObject(anchorPose.position, anchorPose.rotation); GameObject spawned = gameObject.GetComponent <ModelSpawnerScript>() .SpawnAnchoredObject(args.Anchor.Identifier, anchorPose.position, anchorPose.rotation); EventTriggered?.Invoke(spawned); }); } }
/// <summary> /// Stops the microphone recording and saves to a WAV file. Used to validate WAV format. /// </summary> public void StopRecording() { Debug.Log("Stopping microphone recording."); UnityDispatcher.InvokeOnAppThread(() => { Debug.Log("Stopped invoke."); audiosource.Stop(); isRecognizing = false; isRecording = false; Microphone.End(null); if (isRecording) { var audioData = new byte[recordingData.Count]; recordingData.CopyTo(audioData); WriteAudioDataToRiffWAVFile(audioData, "recording.wav"); } Debug.Log($"Microphone stopped recording at frequency {audiosource.clip.frequency}Hz."); }); UpdateUICanvasLabel("Recording stopped. Audio saved to file 'recording.wav'.", FontStyle.Normal); }
protected override void OnCloudAnchorLocated(AnchorLocatedEventArgs args) { base.OnCloudAnchorLocated(args); if (args.Status == LocateAnchorStatus.Located) { CloudSpatialAnchor cloudAnchor = args.Anchor; UnityDispatcher.InvokeOnAppThread(() => { Pose anchorPose = Pose.identity; #if UNITY_ANDROID || UNITY_IOS anchorPose = currentCloudAnchor.GetPose(); #endif // HoloLens: The position will be set based on the unityARUserAnchor that was located. GameObject spawnedObject = SpawnNewAnchoredObject(anchorPose.position, anchorPose.rotation, cloudAnchor); allDiscoveredAnchors.Add(spawnedObject); }); } }
protected override void OnCloudAnchorLocated(AnchorLocatedEventArgs args) { base.OnCloudAnchorLocated(args); if (args.Status == LocateAnchorStatus.Located) { UnityDispatcher.InvokeOnAppThread(() => { currentCloudAnchor = args.Anchor; if (!string.IsNullOrEmpty(saveStateController.getNoteText(currentCloudAnchor.Identifier))) { spatialNotesUI.setStatusText("Tap anchor to read note or place a new one."); } else { spatialNotesUI.setStatusText("Found anchor."); } Pose anchorPose = Pose.identity; #if UNITY_ANDROID || UNITY_IOS anchorPose = currentCloudAnchor.GetPose(); #endif // HoloLens: The position will be set based on the unityARUserAnchor that was located. SpawnOrMoveCurrentAnchoredObject(anchorPose.position, anchorPose.rotation); if (!savedCloudAnchorsById.ContainsKey(currentCloudAnchor.Identifier)) { savedCloudAnchorsById[currentCloudAnchor.Identifier] = spawnedObject; } spawnedObject = null; currentCloudAnchor = null; spawnedObjectMat = null; }); } }
public IHttpResponse Get(HttpGetRequest getRequest) { try { _logger.LogDebug("Sending GET request to " + getRequest.Address); if (getRequest.Range != null) { throw new NotImplementedException(); } _logger.LogTrace("timeout = " + getRequest.Timeout); var result = new WWWResult(); var waitHandle = UnityDispatcher.InvokeCoroutine(GetWWW(getRequest, result)); waitHandle.WaitOne(TimeSpan.FromMilliseconds(getRequest.Timeout)); lock (result) { if (!result.IsDone) { throw new WebException("Timeout.", WebExceptionStatus.Timeout); } var statusCode = ReadStatusCode(result); _logger.LogDebug("Successfuly received response."); return(new UnityHttpResponse(result.Text, statusCode, ResponseEncoding)); } } catch (Exception e) { _logger.LogError("Failed to get response.", e); throw; } }
public static string GetVersion() { string patcherVersion = "(unknown)"; UnityDispatcher.Invoke(() => { try { string versionFilePath = Path.Combine(Application.streamingAssetsPath, "patcher.versioninfo"); if (File.Exists(versionFilePath)) { patcherVersion = File.ReadAllText(versionFilePath); } } catch (Exception ex) { patcherVersion = string.Format("(unable to load version because: {0})", ex); } }).WaitOne(); return(patcherVersion); }
protected override void OnCloudAnchorLocated(AnchorLocatedEventArgs args) { base.OnCloudAnchorLocated(args); if (args.Status == LocateAnchorStatus.Located) { UnityDispatcher.InvokeOnAppThread(() => { locatedCount++; currentCloudAnchor = args.Anchor; Pose anchorPose = Pose.identity; #if UNITY_ANDROID || UNITY_IOS anchorPose = currentCloudAnchor.GetPose(); #endif // HoloLens: The position will be set based on the unityARUserAnchor that was located. SpawnOrMoveCurrentAnchoredObject(anchorPose.position, anchorPose.rotation); spawnedObject.transform.localScale += scaleMods[(int)currentAppState]; spawnedObject = null; if (currentAppState == AppState.Graphing) { if (spawnedObjectsInCurrentAppState.Count == anchorIds.Count) { currentAppState = AppState.ReadyToSearch; } } else if (currentAppState == AppState.Searching) { currentAppState = AppState.ReadyToNeighborQuery; } }); } }
/// <summary> /// Sends requests to the Bot Framework via the DirectLine v3 API. /// The specific bot that gets called gets configured via the DirectLine API key /// in the BotService class. This function runs in the background to insure the /// application isn;t blocked whiule we wait for the bot response. /// </summary> /// <param name="message"></param> private async void SendBotRequestMessage(string message) { string result = "I'm sorry, I'm not sure how to answer that"; // sends the message to the bot and awaits a response. if (await tmsBot.SendMessage(message)) { ConversationActitvities messages = await tmsBot.GetMessages(); if (messages.activities.Length > 0) { result = ""; } // Note that attachments (like cards) are still not supported for (int i = 1; i < messages.activities.Length; i++) { // We focus on the speak tag if the bot was speech-enabled. // Otherwise we'll just speak the default text instead. if (messages.activities[i].speak?.Length > 0) { result += (messages.activities[i].speak + " "); } else { result += (messages.activities[i].text + " "); } } } //animator.Play("Happy"); recognizedString = result; // Use Text-to Speech to respond to the user UnityDispatcher.InvokeOnAppThread(() => { UpdateUI(); }); speechTTS.SpeakWithSDKPlugin(result); }
private void AquireRemoteBanner(Data data) { _logger.LogDebug(string.Format("Aquiring the remote banner image from {0}", data.BannerData.ImageUrl)); var coroutine = Threading.StartThreadCoroutine(() => { CancellationTokenSource source = new CancellationTokenSource(); var downloader = new HttpDownloader(data.BannerFilePath, new string[] { data.BannerData.ImageUrl }); try { UnityDispatcher.Invoke(() => { MainAnimator.SetBool(AnimationLoadingParameter, true); }); downloader.Download(source.Token); return(true); } catch (Exception) { return(false); } }, (bool result) => { if (result) { CachedBannerPath = data.BannerFilePath; CachedBannerModificationDate = data.BannerData.ModificationDate; MainAnimator.SetBool(AnimationLoadingParameter, false); MainAnimator.SetTrigger(AnimationSwitchTrigger); LoadBannerImage(data.BannerFilePath, NewImage); } }); StartCoroutine(coroutine); }
public void SetKey(string key) { UnityDispatcher.Invoke(() => KeyInputField.text = key); }
private void ThreadExecuteUserDecision(CancellationToken cancellationToken) { bool displayWarningInsteadOfError = false; try { _warning.Value = string.Empty; DebugLogger.Log(string.Format("Executing user decision {0}...", _userDecision)); switch (_userDecision) { case UserDecision.None: break; case UserDecision.RepairApp: break; case UserDecision.StartAppAutomatically: case UserDecision.StartApp: ThreadStartApp(); break; case UserDecision.InstallAppAutomatically: displayWarningInsteadOfError = _app.IsFullyInstalled(); ThreadUpdateApp(true, cancellationToken); break; case UserDecision.InstallApp: ThreadUpdateApp(false, cancellationToken); break; case UserDecision.CheckForAppUpdatesAutomatically: displayWarningInsteadOfError = _app.IsFullyInstalled(); ThreadUpdateApp(true, cancellationToken); break; case UserDecision.CheckForAppUpdates: ThreadUpdateApp(false, cancellationToken); break; } DebugLogger.Log(string.Format("User decision {0} execution done.", _userDecision)); } catch (OperationCanceledException) { DebugLogger.Log(string.Format("User decision {0} execution cancelled.", _userDecision)); } catch (UnauthorizedAccessException e) { DebugLogger.Log(string.Format("User decision {0} execution issue: permissions failure.", _userDecision)); DebugLogger.LogException(e); if (ThreadTryRestartWithRequestForPermissions()) { UnityDispatcher.Invoke(Quit); } else { ThreadDisplayError(PatcherErrorMessage.NoPermissions(), cancellationToken); } } catch (ApiConnectionException e) { DebugLogger.LogException(e); if (displayWarningInsteadOfError) { _warning.Value = "Unable to check for updates. Please check your internet connection."; } else { ThreadDisplayError(PatcherErrorMessage.NoInternetConnection(), cancellationToken); } } catch (NotEnoughtDiskSpaceException e) { DebugLogger.LogException(e); ThreadDisplayError(PatcherErrorMessage.NotEnoughDiskSpace(e.RequiredSpace - e.AvailableSpace), cancellationToken); } catch (ThreadInterruptedException) { DebugLogger.Log(string.Format( "User decision {0} execution interrupted: thread has been interrupted. Rethrowing exception.", _userDecision)); throw; } catch (ThreadAbortException) { DebugLogger.Log(string.Format( "User decision {0} execution aborted: thread has been aborted. Rethrowing exception.", _userDecision)); throw; } catch (Exception exception) { DebugLogger.LogWarning(string.Format( "Error while executing user decision {0}: an exception has occured.", _userDecision)); DebugLogger.LogException(exception); if (displayWarningInsteadOfError) { _warning.Value = "Unable to check for updates. Please check your internet connection."; } else { ThreadDisplayError(PatcherErrorMessage.Other(), cancellationToken); } } }
private void ThreadLoadPatcherData() { try { DebugLogger.Log("Loading patcher data..."); _state.Value = PatcherState.LoadingPatcherData; #if UNITY_EDITOR UnityDispatcher.Invoke(() => { DebugLogger.Log("Using Unity Editor patcher data."); _data.Value = new PatcherData { AppSecret = EditorAppSecret, AppDataPath = Application.dataPath.Replace("/Assets", string.Format("/Temp/PatcherApp{0}", EditorAppSecret)), OverrideLatestVersionId = EditorOverrideLatestVersionId, IsOnline = null }; }).WaitOne(); #else DebugLogger.Log("Using command line patcher data reader."); var inputArgumentsPatcherDataReader = new InputArgumentsPatcherDataReader(); _data.Value = inputArgumentsPatcherDataReader.Read(); #endif DebugLogger.LogVariable(_data.Value.AppSecret, "Data.AppSecret"); DebugLogger.LogVariable(_data.Value.AppDataPath, "Data.AppDataPath"); DebugLogger.LogVariable(_data.Value.OverrideLatestVersionId, "Data.OverrideLatestVersionId"); DebugLogger.LogVariable(_data.Value.LockFilePath, "Data.LockFilePath"); DebugLogger.LogVariable(_data.Value.IsOnline, "Data.IsOnline"); if (_data.Value.IsOnline.HasValue && !_data.Value.IsOnline.Value) { DebugLogger.Log("Disabling auto-updating because patcher is in offline mode."); _hasAutomaticallyInstalledApp = true; _hasAutomaticallyCheckedForAppUpdate = true; _warning.Value = "Working in offline mode"; } DebugLogger.Log("Patcher data loaded."); } catch (ThreadInterruptedException) { DebugLogger.Log("Loading patcher data interrupted: thread has been interrupted. Rethrowing exception."); throw; } catch (ThreadAbortException) { DebugLogger.Log("Loading patcher data aborted: thread has been aborted. Rethrowing exception."); throw; } catch (Exception) { DebugLogger.LogError("Error while loading patcher data: an exception has occured. Rethrowing exception."); throw; } }
private void ThreadExecution(CancellationToken cancellationToken) { try { _state.Value = PatcherState.None; DebugLogger.Log("Patcher thread started."); try { ThreadLoadPatcherData(); } catch (NonLauncherExecutionException) { try { LauncherUtilities.ExecuteLauncher(); return; } catch (ApplicationException) { ThreadDisplayError(PatcherErrorMessage.NonLauncherExecution(), cancellationToken); return; } finally { Quit(); } } EnsureSingleInstance(); ThreadLoadPatcherConfiguration(); UnityDispatcher.Invoke(() => _app = new App(_data.Value.AppDataPath, _data.Value.AppSecret, _data.Value.OverrideLatestVersionId, _requestTimeoutCalculator)).WaitOne(); PatcherStatistics.TryDispatchSendEvent(PatcherStatistics.Event.PatcherStarted); while (true) { cancellationToken.ThrowIfCancellationRequested(); ThreadWaitForUserDecision(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); ThreadExecuteUserDecision(cancellationToken); } } catch (OperationCanceledException) { DebugLogger.Log("Patcher thread finished: thread has been cancelled."); } catch (ThreadInterruptedException) { DebugLogger.Log("Patcher thread finished: thread has been interrupted."); } catch (ThreadAbortException) { DebugLogger.Log("Patcher thread finished: thread has been aborted."); } catch (MultipleInstancesException exception) { DebugLogger.LogException(exception); Quit(); } catch (Exception exception) { DebugLogger.LogError("Patcher thread failed: an exception has occured."); DebugLogger.LogException(exception); } finally { _state.Value = PatcherState.None; } }
public void Download(CancellationToken cancellationToken) { try { _logger.LogDebug("Downloading..."); _logger.LogTrace("url = " + _url); _logger.LogTrace("bufferSize = " + BufferSize); _logger.LogTrace("bytesRange = " + (_bytesRange.HasValue ? _bytesRange.Value.Start + "-" + _bytesRange.Value.End : "(none)")); _logger.LogTrace("timeout = " + _timeout); Assert.MethodCalledOnlyOnce(ref _downloadHasBeenCalled, "Download"); UnityWebRequest request = null; Exception dataAvailableException = null; DateTime lastDataAvailable = DateTime.Now; UnityDispatcher.Invoke(() => { request = new UnityWebRequest(); request.uri = new Uri(_url); request.timeout = 0; if (_bytesRange.HasValue) { var bytesRangeEndText = _bytesRange.Value.End >= 0L ? _bytesRange.Value.End.ToString() : string.Empty; request.SetRequestHeader( "Range", "bytes=" + _bytesRange.Value.Start + "-" + bytesRangeEndText); } request.downloadHandler = new Handler((data, length) => { lastDataAvailable = DateTime.Now; if (DataAvailable != null && dataAvailableException == null) { try { DataAvailable.Invoke(data, length); } catch (Exception e) { dataAvailableException = e; } } }); }).WaitOne(); using (request) { using (request.downloadHandler) { UnityWebRequestAsyncOperation op = null; UnityDispatcher.Invoke(() => { op = request.SendWebRequest(); }).WaitOne(); bool requestIsDone = false; bool responseCodeHandled = false; while (!requestIsDone) { cancellationToken.ThrowIfCancellationRequested(); if ((DateTime.Now - lastDataAvailable).TotalMilliseconds > _timeout) { throw new ConnectionFailureException("Timeout."); } long requestResponseCode = 0; string requestError = null; UnityDispatcher.Invoke(() => { requestIsDone = request.isDone; requestResponseCode = request.responseCode; requestError = request.error; }).WaitOne(); if (requestError != null) { throw new ConnectionFailureException(requestError); } if (requestResponseCode > 0 && !responseCodeHandled) { _logger.LogDebug("Received response from server."); _logger.LogTrace("statusCode = " + requestResponseCode); if (Is2XXStatus((HttpStatusCode)requestResponseCode)) { _logger.LogDebug("Successful response. Reading response stream..."); } else if (Is4XXStatus((HttpStatusCode)requestResponseCode)) { throw new DataNotAvailableException(string.Format( "Request data for {0} is not available (status: {1})", _url, (HttpStatusCode)request.responseCode)); } else { throw new ServerErrorException(string.Format( "Server has experienced some issues with request for {0} which resulted in {1} status code.", _url, (HttpStatusCode)requestResponseCode)); } responseCodeHandled = true; } if (dataAvailableException != null) { throw dataAvailableException; } System.Threading.Thread.Sleep(100); } if (dataAvailableException != null) { throw dataAvailableException; } _logger.LogDebug("Stream has been read."); } } _logger.LogDebug("Downloading finished."); } catch (WebException webException) { _logger.LogError("Downloading has failed.", webException); throw new ConnectionFailureException( string.Format("Connection to server has failed while requesting {0}", _url), webException); } catch (Exception e) { _logger.LogError("Downloading has failed.", e); throw; } }
public void SetValue(string key, string value) { UnityDispatcher.Invoke(() => PlayerPrefs.SetString(key, value)).WaitOne(); }
public static void DispatchSendEvent(Event ev, OptionalParams?parameters = null) { UnityDispatcher.InvokeCoroutine(PatcherStatistics.SendEvent(ev, parameters)); }
private void Application_logMessageReceivedThreaded(string condition, string stackTrace, LogType type) { UnityDispatcher.InvokeOnAppThread(() => feedbackText.text += $"\nLOG: {condition}."); }
public void Execute(CancellationToken cancellationToken) { DebugLogger.Log("Trying to geolocate current host..."); try { string responseString = null; JToken jToken = null; #if UNITY_STANDALONE var eventWaitHandle = UnityDispatcher.Invoke(() => { var www = new WWW("https://ip2loc.patchkit.net/v1/country"); var stopwatch = new Stopwatch(); stopwatch.Start(); while (!www.isDone) { if (stopwatch.ElapsedMilliseconds >= Timeout) { break; } } if (!www.isDone) { DebugLogger.LogError("Timeout while getting country code"); return; } responseString = www.text; jToken = JToken.Parse(www.text); }); eventWaitHandle.WaitOne(); #else ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; var apiConnectionSettings = new ApiConnectionSettings { CacheServers = new string[0], MainServer = "ip2loc.patchkit.net", Timeout = Timeout, UseHttps = true, Port = 443 }; var apiConnection = new ApiConnection(apiConnectionSettings); DebugLogger.Log("aaa"); ServicePointManager.ServerCertificateValidationCallback += CertificateValidationCallBack; var countryResponse = apiConnection.GetResponse("/v1/country", null); responseString = countryResponse.Body; jToken = countryResponse.GetJson(); #endif if (jToken.Value <string>("country") != null) { CountryCode = jToken.Value <string>("country"); HasCountryCode = !string.IsNullOrEmpty(CountryCode); if (HasCountryCode) { DebugLogger.LogFormat("Geolocation succeeded! Country code: '{0}'", CountryCode); } else { DebugLogger.LogWarning("Geolocation succeeded, but empty country code received."); } } else { DebugLogger.LogErrorFormat("Cannot find 'country' key in response json: {0}", responseString); } } catch (Exception ex) { DebugLogger.LogErrorFormat("Error while trying to geolocate: " + ex.Message); DebugLogger.LogException(ex); } }
private async void CreateAsaAnchor(Transform indicatorTransform) { Debug.Log("\nAnchorManager.CreateAsaAnchor()"); anchorCreationController.StartProgressIndicatorSession(); if (cloudManager.Session == null) { // Creates a new session if one does not exist Debug.Log("await cloudManager.CreateSessionAsync()"); await cloudManager.CreateSessionAsync(); } // Starts the session if not already started Debug.Log("await cloudManager.StartSessionAsync()"); await cloudManager.StartSessionAsync(); var anchorPositionIndicator = Instantiate(anchorPositionPrefab, indicatorTransform.position, indicatorTransform.rotation); // Create native XR anchor at the location of the object anchorPositionIndicator.gameObject.CreateNativeAnchor(); Debug.Log("anchorPosition.gameObject.CreateNativeAnchor()"); // Create local cloud anchor var localCloudAnchor = new CloudSpatialAnchor(); // Set the local cloud anchor's position to the native XR anchor's position localCloudAnchor.LocalAnchor = anchorPositionIndicator.gameObject.FindNativeAnchor().GetPointer(); Debug.Log("anchorPosition.gameObject.FindNativeAnchor().GetPointer()"); // Check to see if we got the local XR anchor pointer if (localCloudAnchor.LocalAnchor == IntPtr.Zero) { Debug.Log("Didn't get the local anchor..."); return; } else { Debug.Log("Local anchor created"); } // Set expiration (when anchor will be deleted from Azure) localCloudAnchor.Expiration = DateTimeOffset.Now.AddDays(7); // Save anchor to cloud while (!cloudManager.IsReadyForCreate) { await Task.Delay(330); var createProgress = cloudManager.SessionStatus.RecommendedForCreateProgress; UnityDispatcher.InvokeOnAppThread(() => Debug.Log($"Move your device to capture more environment data: {createProgress:0%}")); } Debug.Log("cloudManager is ready."); try { // Actually save Debug.Log("await cloudManager.CreateAnchorAsync(localCloudAnchor)"); await cloudManager.CreateAnchorAsync(localCloudAnchor); Debug.Log("Anchor created!"); // Store currentCloudAnchor = localCloudAnchor; // Success? var success = currentCloudAnchor != null; if (success) { Debug.Log($"Azure anchor with ID '{currentCloudAnchor.Identifier}' created successfully"); // Update the current Azure anchor ID Debug.Log($"Current Azure anchor ID updated to '{currentCloudAnchor.Identifier}'"); currentTrackedObject.SpatialAnchorId = currentCloudAnchor.Identifier; activeAnchors.Add(currentTrackedObject.SpatialAnchorId, anchorPositionIndicator); // Notify subscribers Debug.Log("OnCreateAnchorSucceeded?.Invoke(this, currentCloudAnchor.Identifier)"); AppDispatcher.Instance().Enqueue(() => { anchorPositionIndicator.Init(currentTrackedObject); currentTrackedObject = null; OnCreateAnchorSucceeded?.Invoke(this, currentCloudAnchor.Identifier); }); } else { Debug.Log($"Failed to save cloud anchor with ID '{currentCloudAnchor.Identifier}' to Azure"); // Notify subscribers AppDispatcher.Instance().Enqueue(() => { currentTrackedObject = null; Destroy(anchorPositionIndicator.gameObject); OnCreateAnchorFailed?.Invoke(this, EventArgs.Empty); }); } } catch (Exception ex) { Debug.Log(ex.ToString()); } StopAzureSession(); }
public void Display(PatcherError error, CancellationToken cancellationToken) { UnityDispatcher.Invoke(() => UpdateMessage(error)).WaitOne(); Display(cancellationToken); }
private async void CreateAzureAnchor(AnchorPosition anchorPos) { // change the color of the currentAnchor to inprogress anchorPos.AnchorInProgress(); if (cloudManager.Session == null) { // Creates a new session if one does not exist Debug.Log("\ncloudManager.CreateSessionAsync()"); await cloudManager.CreateSessionAsync(); } // Starts the session if not already started Debug.Log("\ncloudManager.StartSessionAsync()"); await cloudManager.StartSessionAsync(); // Notify AnchorFeedbackScript OnCreateAnchorStarted?.Invoke(); // Create local cloud anchor var localCloudAnchor = new CloudSpatialAnchor(); // Create native XR anchor at the location of the object anchorPos.gameObject.CreateNativeAnchor(); Debug.Log("anchorPosition.gameObject.CreateNativeAnchor()"); // create a cloud anchor at the position of the local anchor localCloudAnchor.LocalAnchor = anchorPos.gameObject.FindNativeAnchor().GetPointer(); Debug.Log("anchorPosition.gameObject.FindNativeAnchor().GetPointer()"); // Check to see if we got the local XR anchor pointer if (localCloudAnchor.LocalAnchor == IntPtr.Zero) { Debug.Log("Didn't get the local anchor..."); return; } else { Debug.Log("Local anchor created"); } // Set expiration (when anchor will be deleted from Azure) localCloudAnchor.Expiration = DateTimeOffset.Now.AddDays(90); // upload cloud anchor to the cloud while (!cloudManager.IsReadyForCreate) { // check with the create progress await Task.Delay(330); var createProgress = cloudManager.SessionStatus.RecommendedForCreateProgress; UnityDispatcher.InvokeOnAppThread(() => Debug.Log($"Move your device to capture more environment data: {createProgress:0%}")); } Debug.Log("cloudManager is ready."); try { // Actually save Debug.Log("await cloudManager.CreateAnchorAsync(localCloudAnchor)"); await cloudManager.CreateAnchorAsync(localCloudAnchor); Debug.Log("Anchor created!"); // Store currentCloudAnchor = localCloudAnchor; localCloudAnchor = null; // Success? var success = currentCloudAnchor != null; if (success) { // update the spaital anchor id of the currentSpatialAnchor Debug.Log($"Azure anchor with ID '{currentCloudAnchor.Identifier}' created successfully"); anchorPos.SpatialAnchorObject.SpatialAnchorId = currentCloudAnchor.Identifier; // Update the current Azure anchor ID Debug.Log($"Current Azure anchor ID updated to '{currentCloudAnchor.Identifier}'"); OnCreateAnchorSucceeded?.Invoke(); } else { Debug.Log($"Failed to save cloud anchor with ID '{currentCloudAnchor.Identifier}' to Azure"); // Notify AnchorFeedbackScript OnCreateAnchorFailed?.Invoke(); } } catch (Exception ex) { Debug.Log(ex.ToString()); } // StopAzureSession(); }