Beispiel #1
0
        private MLResult MakePurchaseInternal(string token, Action <MLPurchaseRequest> callback)
        {
            ulong handle = MagicLeapNativeBindings.InvalidHandle;

            MLResult.Code purchaseResult = MLPurchaseNativeBindings.MLPurchaseCreate(ref handle);
            MLResult      result         = MLResult.Create(purchaseResult);

            if (!result.IsOk || !MagicLeapNativeBindings.MLHandleIsValid(handle))
            {
                MLPluginLog.ErrorFormat("MLPurchase.MakePurchaseInternal failed to create purchase request. Reason: {0}", result);
                return(result);
            }

            MLPluginLog.Debug("Purchasing: " + token);
            purchaseResult = MLPurchaseNativeBindings.MLPurchaseSubmit(handle, token);
            result         = MLResult.Create(purchaseResult);
            if (!result.IsOk)
            {
                MLPluginLog.ErrorFormat("MLPurchase.MakePurchaseInternal failed to submit purchase request. Reason: {0}", result);
                DestroyPurchaseRequest(handle);
            }
            else
            {
                _pendingPurchaseRequests.Add(new PurchaseRequestInfo(handle, callback));
            }
            return(result);
        }
Beispiel #2
0
        private MLResult GetItemDetailsInternal(string[] itemIds, Action <MLPurchaseItemDetail> callback)
        {
            // Create handle
            ulong handle = MagicLeapNativeBindings.InvalidHandle;

            MLResult.Code detailsResult = MLPurchaseNativeBindings.MLPurchaseItemDetailsCreate(ref handle);
            MLResult      result        = MLResult.Create(detailsResult);

            if (!result.IsOk || !MagicLeapNativeBindings.MLHandleIsValid(handle))
            {
                MLPluginLog.ErrorFormat("MLPurchase.GetItemDetailsInternal failed, unable to create item details query. Reason: {0}", result);
                return(result);
            }

            result = InitiateItemDetailsQuery(handle, itemIds);

            if (!result.IsOk)
            {
                MLPluginLog.ErrorFormat("MLPurchase.GetItemDetailsInternal failed to submit item details request. Reason: {0}", result);
                DestroyItemDetail(handle);
            }
            else
            {
                _pendingItemDetailQueries.Add(new ItemDetailQueryInfo(handle, callback));
            }
            return(result);
        }
            /// <summary>
            /// Destroys this audio sink object.
            /// </summary>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
            /// </returns>
            public override MLResult Destroy()
            {
#if PLATFORM_LUMIN
                if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                {
                    return(MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid."));
                }

                this.SetStream(null);
                MLResult.Code resultCode = NativeBindings.MLWebRTCAudioSinkDestroy(this.Handle);
                DidNativeCallSucceed(resultCode, "MLWebRTCAudioSinkDestroy()");
                this.InvalidateHandle();

                MLWebRTC.Instance.sinks.Remove(this);
                this.gcHandle.Free();

                nativeRadiation.FreeUnmanagedMemory();
                nativeDistance.FreeUnmanagedMemory();
                nativeSoundLevels.FreeUnmanagedMemory();
                nativeOrientation.FreeUnmanagedMemory();
                nativePosition.FreeUnmanagedMemory();

                return(MLResult.Create(resultCode));
#else
                return(new MLResult());
#endif
            }
        /// <summary>
        /// Begin querying for found objects.
        /// </summary>
        /// <param name="filter">Filter to use for this query.</param>
        /// <param name="callback">Callback used to report query results.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        private MLResult BeginObjectQueryAsync(Query.Filter filter, QueryResultsDelegate callback)
        {
            try
            {
                if (!MagicLeapNativeBindings.MLHandleIsValid(_instance.handle))
                {
                    MLPluginLog.Error("MLFoundObjects.BeginObjectQuery failed to request found objects. Reason: Tracker handle is invalid");
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                NativeBindings.QueryFilterNative nativeQueryFilter = new NativeBindings.QueryFilterNative();
                nativeQueryFilter.Data = filter;

                MLResult.Code resultCode = NativeBindings.MLFoundObjectQuery(_instance.handle, ref nativeQueryFilter, out ulong queryHandle);
                MLResult      result     = MLResult.Create(resultCode);

                if (!result.IsOk)
                {
                    MLPluginLog.ErrorFormat("MLFoundObjects.BeginObjectQuery failed to request objects. Reason: {0}", resultCode);
                    return(result);
                }

                // Add query to the list of pendingQueries.
                Query query = Query.Create(callback, filter);
                MLFoundObjects._instance.pendingQueries.TryAdd(queryHandle, query);

                return(result);
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found"));
            }
        }
Beispiel #5
0
        /// <summary>
        /// Begin querying for found objects.
        /// </summary>
        /// <param name="callback">Callback used to report query results.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        private MLResult BeginObjectQuery(QueryResultsDelegate callback)
        {
            try
            {
                if (!MagicLeapNativeBindings.MLHandleIsValid(_instance.tracker))
                {
                    MLPluginLog.Error("MLFoundObject.BeginObjectQuery failed to request found objects. Reason: Tracker handle is invalid");
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                NativeBindings.QueryFilterNative queryFilter = new NativeBindings.QueryFilterNative();

                MLResult.Code resultCode = NativeBindings.MLFoundObjectQuery(_instance.tracker, ref queryFilter, out ulong queryHandle);
                MLResult      result     = MLResult.Create(resultCode);

                if (!result.IsOk)
                {
                    MLPluginLog.ErrorFormat("MLFoundObject.BeginObjectQuery failed to request objects. Reason: {0}", resultCode);
                    return(result);
                }

                // Create query object to prepresent this newly registered found object query.
                NativeBindings.Query query = new NativeBindings.Query(callback, queryFilter, result);
                MLFoundObjects._instance.pendingQueries.Add(queryHandle, query);

                return(result);
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found"));
            }
        }
            /// <summary>
            /// Queries the video sink for a new frame to broadcast, then builds that frame.
            /// </summary>
            public void UpdateVideoSink()
            {
#if PLATFORM_LUMIN
                if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                {
                    return;
                }

                updateVideoEvent.Reset();
                bool newFrameAvailable = false;
                // Checks for a new frame.
                MLResult.Code resultCode = NativeBindings.MLWebRTCVideoSinkIsNewFrameAvailable(this.Handle, out newFrameAvailable);
                DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkIsNewFrameAvailable()");
                // If one exists, acquire the frame and it's characteristics to send to the YUV converter for rendering.
                if (!newFrameAvailable)
                {
                    return;
                }

                ulong frameHandle = MagicLeapNativeBindings.InvalidHandle;
                resultCode = NativeBindings.MLWebRTCVideoSinkAcquireNextAvailableFrame(this.Handle, out frameHandle);
                if (!DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkAcquireNextAvailableFrame()"))
                {
                    return;
                }

                Frame.NativeBindings.MLWebRTCFrame nativeFrame = Frame.NativeBindings.MLWebRTCFrame.Create();
                resultCode = Frame.NativeBindings.MLWebRTCFrameGetData(frameHandle, ref nativeFrame);
                DidNativeCallSucceed(resultCode, "MLWebRTCFrameGetData()");
                newFrame       = Frame.Create(frameHandle, nativeFrame, imagePlanesBuffer.Get());
                newFrameHandle = frameHandle;

                updateVideoEvent.Set();
#endif
            }
            /// <summary>
            /// Creates an initialized VideoSink object.
            /// </summary>
            /// <param name="result">The MLResult object of the inner platform call(s).</param>
            /// <returns> An initialized VideoSink object.</returns>
            public static VideoSink Create(out MLResult result)
            {
                VideoSink videoSink = null;

#if PLATFORM_LUMIN
                List <MLWebRTC.Sink> sinks = MLWebRTC.Instance.sinks;
                ulong         Handle       = MagicLeapNativeBindings.InvalidHandle;
                MLResult.Code resultCode   = NativeBindings.MLWebRTCVideoSinkCreate(out Handle);
                if (!DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkCreate()"))
                {
                    result = MLResult.Create(resultCode);
                    return(videoSink);
                }

                videoSink = new VideoSink(Handle);
                if (MagicLeapNativeBindings.MLHandleIsValid(videoSink.Handle))
                {
                    sinks.Add(videoSink);
                }

                result = MLResult.Create(resultCode);
#else
                result = new MLResult();
#endif
                return(videoSink);
            }
            /// <summary>
            /// Initializes a new instance of the <see cref="Target" /> class.
            /// </summary>
            /// <param name="name"> Image target's name. </param>
            /// <param name="image"> Texture2D representing the image target. The size of the texture should not be changed. Set the "Non Power of 2" property of Texture2D to none. </param>
            /// <param name="longerDimension"> Longer dimension of the image target in scene units. Default is meters. </param>
            /// <param name="callback"> Tracking result callback for this image target. </param>
            /// <param name="handle"> Handle for the image tracker. </param>
            /// <param name="isStationary"> Set this to true if the position of this image target in the physical world is fixed and its surroundings are planar (ex: walls, floors, tables, etc). </param>
            public Target(string name, Texture2D image, float longerDimension, OnImageResultDelegate callback, ulong handle, bool isStationary = false)
            {
                this.targetSettings       = MLImageTracker.Target.Settings.Create();
                this.targetStaticData     = new NativeBindings.MLImageTrackerTargetStaticDataNative();
                this.nativeTrackingResult = new NativeBindings.MLImageTrackerTargetResultNative();

                // It is assumed that all the parameters are valid as this class should only be used by the MLImageTracker,
                // which already has checks for these values before it creates the MLImageTracker.Target.
                this.targetSettings.Name            = name;
                this.targetSettings.LongerDimension = longerDimension;
                this.targetSettings.IsStationary    = isStationary;
                this.trackerHandle = handle;
                this.OnImageResult = callback;

                this.imageData    = MLTextureUtils.ConvertToByteArray(image, out int numChannels);
                this.targetHandle = MagicLeapNativeBindings.InvalidHandle;

                MLResult.Code result = NativeBindings.MLImageTrackerAddTargetFromArray(this.trackerHandle, ref this.targetSettings, this.imageData, (uint)image.width, (uint)image.height, (numChannels == 4) ? MLImageTracker.ImageFormat.RGBA : MLImageTracker.ImageFormat.RGB, ref this.targetHandle);

                if (result == MLResult.Code.Ok && this.IsValid && MagicLeapNativeBindings.MLHandleIsValid(this.trackerHandle))
                {
                    result = NativeBindings.MLImageTrackerGetTargetStaticData(this.trackerHandle, this.targetHandle, ref this.targetStaticData);
                    if (result != MLResult.Code.Ok)
                    {
                        MLPluginLog.ErrorFormat("MLImageTracker.Target.Target failed to get static data for target. Reason: {0}", result);
                    }
                }
                else
                {
                    MLPluginLog.ErrorFormat("MLImageTracker.Target.Target failed, one or both handles are invalid: Tracker Handle: {0}, Existing Target Handle: {1}. Reason: {2}", this.trackerHandle, this.targetHandle, result);
                }
            }
                /// <summary>
                /// Sets a track to be enabled or disabled.
                /// </summary>
                /// <param name="isEnabled">True if the track should be enabled.</param>
                /// <returns>
                /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
                /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
                /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
                /// </returns>
                public MLResult SetEnabled(bool isEnabled)
                {
#if PLATFORM_LUMIN
                    if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                    {
                        return(MLResult.Create(MLResult.Code.InvalidParam, "Source handle is invalid."));
                    }

                    MLResult result = this.GetEnabled(out bool trackEnabled);
                    if (!result.IsOk)
                    {
                        return(result);
                    }

                    if (trackEnabled != isEnabled)
                    {
                        MLResult.Code resultCode = Source.NativeBindings.MLWebRTCSourceSetEnabled(this.Handle, isEnabled);
                        DidNativeCallSucceed(resultCode, "MLWebRTCSourceSetEnabled");
                        result = MLResult.Create(resultCode);
                    }

                    return(result);
#else
                    return(new MLResult());
#endif
                }
Beispiel #10
0
        /// <summary>
        /// Retrieves the platform API level that the OS supports.
        /// </summary>
        private void GetPlatformLevel()
        {
            try
            {
                uint          level      = 0;
                MLResult.Code resultCode = MagicLeapNativeBindings.MLPlatformGetAPILevel(ref level);
                if (resultCode != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLDevice.GetPlatformLevel failed to get platform level. Reason: {0}", resultCode);
                }
                else
                {
                    this.platformLevel = level;
                }
            }
            catch (DllNotFoundException)
            {
                MLPluginLog.ErrorFormat("MLDevice.GetPlatformLevel failed. Reason: {0} library not found", MagicLeapNativeBindings.MLPlatformDll);
            }

            if (this.platformLevel == null)
            {
                this.platformLevel = 0;
            }
        }
Beispiel #11
0
        private MLResult GetAllPurchaseHistoryInternal(Action <MLPurchaseHistoryQuery> callback)
        {
            ulong handle = MagicLeapNativeBindings.InvalidHandle;

            MLResult.Code historyResult = MLPurchaseNativeBindings.MLPurchaseHistoryQueryCreate(ref handle);
            MLResult      result        = MLResult.Create(historyResult);

            if (!result.IsOk || !MagicLeapNativeBindings.MLHandleIsValid(handle))
            {
                MLPluginLog.ErrorFormat("MLPurchase.GetAllPurchaseHistoryInternal failed to create purchase history query. Reason: {0}", result);
                return(result);
            }

            historyResult = MLPurchaseNativeBindings.MLPurchaseHistoryQueryGetPage(handle, MaxPurchaseHistoryItems);
            result        = MLResult.Create(historyResult);
            if (!result.IsOk)
            {
                MLPluginLog.ErrorFormat("MLPurchase.GetAllPurchaseHistoryInternal failed to submit purchase history query. Reason: {0}", result);
                DestroyPurchaseHistoryQuery(handle);
            }
            else
            {
                _pendingPurchaseHistoryQueries.Add(new PurchaseHistoryQueryInfo(handle, callback));
            }
            return(result);
        }
            /// <summary>
            /// Creates an initialized AudioSink object.
            /// </summary>
            /// <param name="result">The MLResult object of the inner platform call(s).</param>
            /// <returns> An initialized AudioSink object.</returns>
            public static AudioSink Create(out MLResult result, BufferNotifyMode mode = BufferNotifyMode.None)
            {
                AudioSink audioSink = null;

#if PLATFORM_LUMIN
                List <MLWebRTC.Sink> sinks = MLWebRTC.Instance.sinks;
                ulong handle = MagicLeapNativeBindings.InvalidHandle;
                // We have a chicken-and-egg problem here. We need the audioSink object in order to create the
                // userContext ptr from it GCHandle, which will later be used in the audio data callback to
                // invoke the delegate on this particular object.
                // So, create the AudioSink obj with an invalid handle for now, and then update it if the
                // native sink creation is successful.
                audioSink = new AudioSink(handle, mode);

                NativeBindings.MLWebRTCAudioSinkParams sinkParams = new NativeBindings.MLWebRTCAudioSinkParams(audioSink);
                MLResult.Code resultCode = NativeBindings.MLWebRTCAudioSinkCreateEx(ref sinkParams, out handle);
                if (!DidNativeCallSucceed(resultCode, "MLWebRTCAudioSinkCreateEx()"))
                {
                    result = MLResult.Create(resultCode);
                    return(null);
                }

                audioSink.Handle = handle;

                if (MagicLeapNativeBindings.MLHandleIsValid(audioSink.Handle))
                {
                    sinks.Add(audioSink);
                }

                result = MLResult.Create(resultCode);
#else
                result = new MLResult();
#endif
                return(audioSink);
            }
Beispiel #13
0
            /// <summary>
            /// Updates the PCF's pose and state.
            /// </summary>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if operation was successful.
            /// MLResult.Result will be <c>MLResult.Code.SnapshotPoseNotFound</c> if the PCF could not be found in the current map.
            /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to an invalid input parameter.
            /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if there was a lack of privileges.
            /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to other internal error.
            /// MLResult.Result will be <c>MLResult.Code.PassableWorldLowMapQuality</c> if map quality is too low for content persistence. Continue building the map.
            /// MLResult.Result will be <c>MLResult.Code.PassableWorldNotFound</c> if the passed CFUID is not available.
            /// MLResult.Result will be <c>MLResult.Code.PassableWorldUnableToLocalize</c> if currently unable to localize into any map. Continue building the map.
            /// </returns>
            public MLResult Update()
            {
                if (MLPersistentCoordinateFrames.IsValidInstance())
                {
                    if (!MLPersistentCoordinateFrames._instance.mapUpdatedPCFsThisFrame.ContainsKey(this.cfuid))
                    {
                        MLPersistentCoordinateFrames._instance.mapUpdatedPCFsThisFrame.Add(this.cfuid, this);

                        try
                        {
                            MLResult result = MLResult.Create(MLResult.Code.Ok);

                            if (MLPersistentCoordinateFrames.IsLocalized)
                            {
                                if (MagicLeapNativeBindings.UnityMagicLeap_TryGetPose(this.CFUID, out Pose newPose))
                                {
                                    this.Pose = newPose;
                                    result    = this.UpdateState();

                                    if (!result.IsOk)
                                    {
                                        MLPluginLog.ErrorFormat("PCF.Update failed because PCF.UpdateState failed. Reason: {0}", result);
                                        return(MLResult.Create(MLResult.Code.UnspecifiedFailure, string.Format("PCF.Update failed because PCF.UpdateState failed. Reason: {0}", result)));
                                    }

                                    this.CurrentResultCode = MLResult.Code.Ok;
                                }
                                else
                                {
                                    result = MLResult.Create(MLResult.Code.UnspecifiedFailure, string.Format("PCF.Update failed. Reason: No pose could be found for the CFUID {0}", this.cfuid));
                                    this.CurrentResultCode = MLResult.Code.SnapshotPoseNotFound;
                                }
                            }
                            else
                            {
                                this.CurrentResultCode = MLResult.Code.SnapshotPoseNotFound;
                            }

                            return(result);
                        }
                        catch (EntryPointNotFoundException)
                        {
                            MLPluginLog.Error("PCF.Update failed. Reason: API symbols not found.");
                            return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "PCF.Update failed. Reason: API symbols not found."));
                        }
                    }
                    else
                    {
                        return(MLResult.Create(MLResult.Code.Ok));
                    }
                }
                else
                {
                    MLPluginLog.ErrorFormat("PCF.Update failed. Reason: No Instance for MLPersistentCoordinateFrames.");
                    return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "PCF.Update failed. Reason: No Instance for MLPersistentCoordinateFrames."));
                }
            }
Beispiel #14
0
        public static string GetResultString(MLResultCode result)
        {
            // TODO: Support other media results.
            if (result >= MLResultCode.MediaGenericInvalidOperation &&
                result <= MLResultCode.MediaGenericUnexpectedNull)
            {
                return(result.ToString());
            }

            return(MagicLeapNativeBindings.MLGetResultString(result));
        }
Beispiel #15
0
        /// <summary>
        /// Destroys the NLLightingTracking instance.
        /// </summary>
        /// <param name="isSafeToAccessManagedObjects">Indicates if it is safe to destroy the tracker.</param>
        protected override void CleanupAPI(bool isSafeToAccessManagedObjects)
        {
            if (MagicLeapNativeBindings.MLHandleIsValid(this.nativeTracker))
            {
                MLResult.Code result = MLLightingTrackingNativeBindings.MLLightingTrackingDestroy(this.nativeTracker);
                if (result != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLLightingTracking.CleanupAPI failed to destroy the lighting tracker. Reason: {0}", MagicLeapNativeBindings.MLGetResultString(result));
                }

                this.nativeTracker = MagicLeapNativeBindings.InvalidHandle;
            }
        }
Beispiel #16
0
            /// <summary>
            /// Pushes a frame into the defined video source.
            /// </summary>
            /// <param name="frame">The frame to push to the video source.</param>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
            /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if an invalid parameter was passed.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInvalidFrameFormat</c> if an invalid frame format was specified.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInvalidFramePlaneCount</c> if an invalid plane count was specified for the given frame format.
            /// </returns>
            protected async Task <MLResult> PushFrameAsync(MLWebRTC.VideoSink.Frame frame)
            {
                if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                {
                    return(await Task.FromResult(MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.")));
                }
                pushFrameEvent.Reset();

                MLWebRTC.VideoSink.Frame.NativeBindings.MLWebRTCFrame frameNative = MLWebRTC.VideoSink.Frame.NativeBindings.MLWebRTCFrame.Create(frame);
                MLResult.Code resultCode = NativeBindings.MLWebRTCSourceAppDefinedVideoSourcePushFrame(this.Handle, in frameNative);
                DidNativeCallSucceed(resultCode, "MLWebRTCSourceAppDefinedVideoSourcePushFrame()");
                pushFrameEvent.Set();
                return(await Task.FromResult(MLResult.Create(resultCode)));
            }
            /// <summary>
            /// Cleans up unmanaged memory.
            /// </summary>
            private void Cleanup()
            {
                if (this.IsValid && MagicLeapNativeBindings.MLHandleIsValid(this.trackerHandle))
                {
                    MLResult.Code result = NativeBindings.MLImageTrackerRemoveTarget(this.trackerHandle, this.targetHandle);
                    if (result != MLResult.Code.Ok)
                    {
                        MLPluginLog.ErrorFormat("MLImageTracker.Target.Cleanup failed to remove target. Tracker Handle : {0}, Target Name: {1}, Target Handle : {2}. Reason: {3}", this.trackerHandle, this.targetSettings.Name, this.targetHandle, result);
                    }
                }

                // Always invalidate the handles if the user tried to remove this target.
                this.targetHandle  = MagicLeapNativeBindings.InvalidHandle;
                this.trackerHandle = MagicLeapNativeBindings.InvalidHandle;
            }
        /// <summary>
        /// Destroys the native tracker if the handle is valid.
        /// </summary>
        private void DestroyNativeTracker()
        {
            if (!MagicLeapNativeBindings.MLHandleIsValid(this.handle))
            {
                return;
            }

            MLResult.Code result = NativeBindings.MLImageTrackerDestroy(this.handle);
            if (result != MLResult.Code.Ok)
            {
                MLPluginLog.ErrorFormat("MLImageTracker.DestroyNativeTracker failed to destroy image tracker. Reason: {0}", result);
            }

            this.handle = MagicLeapNativeBindings.InvalidHandle;
        }
Beispiel #19
0
        /// <summary>
        /// Destroy the planes native tracker.
        /// </summary>
        private void DestroyNativeTracker()
        {
            if (!MagicLeapNativeBindings.MLHandleIsValid(this.planesTracker))
            {
                return;
            }

            MLResult.Code resultCode = NativeBindings.MLPlanesDestroy(this.planesTracker);
            if (resultCode != MLResult.Code.Ok)
            {
                MLPluginLog.ErrorFormat("MLPlanes.DestroyNativeTracker failed to destroy planes tracker. Reason: {0}", NativeBindings.MLGetResultString(resultCode));
            }

            this.planesTracker = MagicLeapNativeBindings.InvalidHandle;
        }
Beispiel #20
0
        /// <summary>
        /// Destroys the native Hand Meshing client.
        /// </summary>
        private void DestroyNativeTracker()
        {
            if (!MagicLeapNativeBindings.MLHandleIsValid(this.nativeTracker))
            {
                return;
            }

            MLResult.Code result = NativeBindings.MLHandMeshingDestroyClient(ref this.nativeTracker);
            if (!MLResult.IsOK(result))
            {
                MLPluginLog.ErrorFormat("MLHandMeshing.DestroyNativeTracker failed to destroy native hand tracker. Reason: {0}", result);
            }

            this.nativeTracker = MagicLeapNativeBindings.InvalidHandle;
        }
Beispiel #21
0
 /// <summary>
 /// Properly dispose the Item Detail Query handle
 /// </summary>
 /// <param name="handle">Item Detail Query handle to be destroyed</param>
 /// <returns>Retrun true on success, otherwise false</returns>
 private bool DestroyItemDetail(ulong handle)
 {
     if (MagicLeapNativeBindings.MLHandleIsValid(handle))
     {
         MLResult.Code result = MLPurchaseNativeBindings.MLPurchaseItemDetailsDestroy(handle);
         if (result == MLResult.Code.Ok)
         {
             return(true);
         }
         MLPluginLog.ErrorFormat("MLPurchase.DestroyItemDetail failed, unable to free item details handle. Reason: {0}", GetResultString(result));
         return(false);
     }
     MLPluginLog.ErrorFormat("MLPurchase.DestroyItemDetail failed, handle is invalid.");
     return(false);
 }
Beispiel #22
0
 private bool DestroyPurchaseHistoryQuery(ulong handle)
 {
     if (MagicLeapNativeBindings.MLHandleIsValid(handle))
     {
         MLResult.Code result = MLPurchaseNativeBindings.MLPurchaseHistoryQueryDestroy(handle);
         if (result == MLResult.Code.Ok)
         {
             return(true);
         }
         MLPluginLog.ErrorFormat("MLPurchase.DestroyPurchaseHistoryQuery failed to free purchase history query handle. Reason: {0}", GetResultString(result));
         return(false);
     }
     MLPluginLog.Error("MLPurchase.DestroyPurchaseHistoryQuery failed, handle is invalid.");
     return(false);
 }
            /// <summary>
            /// Invokes the OnNewFrame event and releases the unmanaged frame.
            /// </summary>
            internal void InvokeOnNewFrame()
            {
#if PLATFORM_LUMIN
                if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                {
                    return;
                }

                if (MagicLeapNativeBindings.MLHandleIsValid(newFrameHandle))
                {
                    this.OnNewFrame?.Invoke(newFrame);
                    DidNativeCallSucceed(NativeBindings.MLWebRTCVideoSinkReleaseFrame(Handle, newFrameHandle), "MLWebRTCVideoSinkReleaseFrame()");
                    newFrameHandle = MagicLeapNativeBindings.InvalidHandle;
                }
#endif
            }
Beispiel #24
0
        /// <summary>
        /// Update loop used to process any connection events.
        /// </summary>
        protected override void Update()
        {
            for (int i = 0; i < Instance.connections.Count; ++i)
            {
                MLWebRTC.PeerConnection connection = Instance.connections[i];
                if (MagicLeapNativeBindings.MLHandleIsValid(connection.Handle))
                {
                    // Polls for connection events.
                    DidNativeCallSucceed(MLWebRTC.PeerConnection.NativeBindings.MLWebRTCConnectionProcessEvents(connection.Handle), "MLWebRTCConnectionProcessEvents()");
                }
            }

            if (!IsProcessingSinks)
            {
                _ = ProcessVideoSinksAsync();
            }
        }
Beispiel #25
0
            /// <summary>
            /// Destroys the data channel object.
            /// </summary>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
            /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
            /// </returns>
            public MLResult Destroy()
            {
                if (this.ParentConnection == null || !MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                {
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                MLResult.Code resultCode = NativeBindings.MLWebRTCDataChannelDestroy(this.ParentConnection.Handle, this.Handle);
                if (DidNativeCallSucceed(resultCode, "MLWebRTCDataChannelDestroy()"))
                {
                    this.Handle           = MagicLeapNativeBindings.InvalidHandle;
                    this.ParentConnection = null;
                }

                this.gcHandle.Free();
                return(MLResult.Create(resultCode));
            }
                /// <summary>
                /// Gets if a track is currently enabled or not.
                /// </summary>
                /// <param name="isEnabled">True if the track is enabled.</param>
                /// <returns>
                /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
                /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
                /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
                /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if an invalid parameter was passed.
                /// </returns>
                public MLResult GetEnabled(out bool isEnabled)
                {
#if PLATFORM_LUMIN
                    if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                    {
                        isEnabled = false;
                        return(MLResult.Create(MLResult.Code.InvalidParam, "Source handle is invalid."));
                    }

                    MLResult.Code resultCode = Source.NativeBindings.MLWebRTCSourceIsEnabled(this.Handle, out isEnabled);
                    DidNativeCallSucceed(resultCode, "MLWebRTCSourceIsEnabled()");
                    return(MLResult.Create(resultCode));
#else
                    isEnabled = false;
                    return(new MLResult());
#endif
                }
            /// <summary>
            /// Updates this image target's tracking data, status, and transforms.
            /// OnImageResult is called with the updated result.
            /// </summary>
            public void UpdateTrackingData()
            {
                bool success = false;

                if (MagicLeapNativeBindings.MLHandleIsValid(this.trackerHandle) && this.IsValid)
                {
                    MLResult.Code result = NativeBindings.MLImageTrackerGetTargetResult(this.trackerHandle, this.targetHandle, ref this.nativeTrackingResult);
                    if (result != MLResult.Code.Ok)
                    {
                        MLPluginLog.ErrorFormat("MLImageTracker.Target.UpdateTrackingData failed getting image tracker target result. Reason: {0}", result);
                    }
                    else
                    {
                        this.lastTrackingResult.Status = (TrackingStatus)this.nativeTrackingResult.Status;
                        if (TrackingStatus.NotTracked == this.lastTrackingResult.Status || !MLImageTracker.GetTrackerStatus())
                        {
                            // If the target is not being tracked then there is no need to query for the transform.
                            success = true;
                        }
                        else
                        {
                            if (MagicLeapNativeBindings.UnityMagicLeap_TryGetPose(this.targetStaticData.CoordFrameTarget, out Pose outputPose))
                            {
                                this.lastTrackingResult.Position  = outputPose.position;
                                this.lastTrackingResult.Rotation  = outputPose.rotation;
                                this.lastTrackingResult.Rotation *= Quaternion.Euler(270, 0, 0);
                                success = true;
                            }
                            else
                            {
                                MLPluginLog.Error("MLImageTracker.Target.UpdateTrackingData failed getting target transforms.");
                            }
                        }
                    }

                    if (success)
                    {
                        this.OnImageResult?.Invoke(this, this.lastTrackingResult);
                    }
                }
                else
                {
                    MLPluginLog.ErrorFormat("MLImageTracker.Target.UpdateTrackingData failed. Reason: Handle was not valid: Tracker Handle: {0}, Existing Target Handle: {1}.", this.trackerHandle, this.targetHandle);
                }
            }
        /// <summary>
        /// Create a new planes native tracker.
        /// </summary>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        private MLResult CreatePlanesTracker()
        {
            try
            {
                MLResult.Code resultCode = NativeBindings.MLPlanesCreate(ref _instance.planesTracker);
                if (resultCode != MLResult.Code.Ok || !MagicLeapNativeBindings.MLHandleIsValid(_instance.planesTracker))
                {
                    MLResult result = MLResult.Create(resultCode);
                    MLPluginLog.ErrorFormat("MLPlanes.CreatePlanesTracker failed to initialize native planes tracking. Reason: {0}", result);
                }

                return(MLResult.Create(MLResult.Code.Ok));
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLPlanes.CreatePlanesTracker failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLPlanes.CreatePlanesTracker failed. Reason: API symbols not found"));
            }
        }
            /// <summary>
            /// Sets the marker's status, reprojection error, and updates it's pose data.
            /// </summary>
            internal void UpdateMarker(TrackingStatus status, float reprojectionError)
            {
#if PLATFORM_LUMIN
                TrackingStatus previousStatus = this.Status;

                this.status            = status;
                this.reprojectionError = reprojectionError;

                if (this.Status == TrackingStatus.Tracked)
                {
                    MagicLeapNativeBindings.UnityMagicLeap_TryGetPose(this.cfuid, out this.pose);
                }

                if (previousStatus != this.Status)
                {
                    OnStatusChange(this, this.Status);
                }
#endif
            }
Beispiel #30
0
        /// <summary>
        /// Creates a new ray cast tracker.
        /// </summary>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        protected override MLResult StartAPI()
        {
            _instance.trackerHandle = MagicLeapNativeBindings.InvalidHandle;

            MLResult.Code resultCode = NativeBindings.MLRaycastCreate(ref _instance.trackerHandle);
            if (resultCode != MLResult.Code.Ok)
            {
                MLResult result = MLResult.Create(resultCode);
                MLPluginLog.ErrorFormat("MLRaycast.StartAPI failed to create input tracker. Reason: {0}", result);
                return(result);
            }

            if (!MagicLeapNativeBindings.MLHandleIsValid(_instance.trackerHandle))
            {
                MLPluginLog.Error("MLRaycast.StartAPI failed. Reason: Invalid handle returned when initializing an instance of MLRaycast");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure));
            }

            return(MLResult.Create(MLResult.Code.Ok));
        }