void Awake()
    {
        MLResult result = MLWorldPlanes.Start();

        if (!result.IsOk)
        {
            Debug.LogError("Error Planes starting MLWorldPlanes, disabling script.");
            enabled = false;
            return;
        }
        var queryParams = new MLWorldPlanesQueryParams();
        var queryFlags  = MLWorldPlanesQueryFlags.Horizontal;

        queryParams.Flags          = queryFlags;
        queryParams.MaxResults     = MAX_RESULTS;
        queryParams.BoundsCenter   = BBoxTransform.position;
        queryParams.BoundsRotation = BBoxTransform.rotation;
        queryParams.BoundsExtents  = BBoxExtents;
        MLWorldPlanes.GetPlanes(queryParams, HandleOnReceivedPlanes);
    }
        /// <summary>
        /// Starts APIs, registers to MLInput events, and restores content.
        /// </summary>
        void Start()
        {
            #if PLATFORM_LUMIN
            MLResult result = MLPersistentCoordinateFrames.Start();
            if (!result.IsOk)
            {
                Debug.LogErrorFormat("Error: PCFExample failed starting MLPersistentCoordinateFrames, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            PCFVisualizer.OnFindAllPCFs += HandleOnFindAllPCFs;
            MLPersistentCoordinateFrames.OnLocalized += HandleOnLocalized;

            MLInput.OnControllerButtonDown              += HandleControllerButtonDown;
            MLInput.OnControllerTouchpadGestureStart    += HandleTouchpadGestureStart;
            MLInput.OnControllerTouchpadGestureContinue += HandleTouchpadGestureContinue;
            MLInput.OnControllerTouchpadGestureEnd      += HandleTouchpadGestureEnd;
            #endif
        }
Esempio n. 3
0
        #pragma warning restore 414


        /// <summary>
        /// Starts the MLPersistentCoordinateFrames api and initializes bindings.
        /// </summary>
        void Start()
        {
            #if PLATFORM_LUMIN
            MLResult result = MLPersistentCoordinateFrames.Start();
            if (!result.IsOk)
            {
                Debug.LogErrorFormat("Error: PCFVisual failed starting MLPersistentCoordinateFrames, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            MLPersistentCoordinateFrames.FindClosestPCF(transform.position, out MLPersistentCoordinateFrames.PCF pcf);

            _visualTransformBinding = new TransformBinding(isPersistent: false);
            _visualTransformBinding.Bind(pcf, transform);

            _visualTextBinding = new TextMeshBinding();
            _visualTextBinding.Bind(pcf, _statusText);
            #endif
        }
Esempio n. 4
0
        /// <summary>
        /// Start the API and register callbacks.
        /// </summary>
        private void StartupAPI()
        {
            MLResult result = MLContacts.Start();

            if (!result.IsOk)
            {
                Debug.LogErrorFormat("Error: ContactsExample failed starting MLContacts, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            Log("<color=green>API Started</color>");

            MLContacts.OnContactAdded    += HandleOnContactAdded;
            MLContacts.OnContactUpdated  += HandleOnContactUpdated;
            MLContacts.OnContactDeleted  += HandleOnContactDeleted;
            MLContacts.OnOperationFailed += HandleOnOperationFailed;

            LoadListPage();
        }
Esempio n. 5
0
        /// <summary>
        // Raycast using full QueryParams object
        /// </summary>
        public static MLResult Raycast(MLRaycast.QueryParams parameters, MLRaycast.OnRaycatResultDelegate callback)
        {
            if (MLRaycast.IsStarted)
            {
                _result = MLRaycast.Raycast(parameters, callback);

                if (!_result.IsOk)
                {
                    Debug.LogErrorFormat("Error: MLRaycastStarterKit.Raycast failed. Reason: {0}", _result);
                }
            }

            else
            {
                Debug.LogError("Error: MLRaycastStarterKit.Raycast failed because MLRaycast was not started.");
                _result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLRaycast was not started");
            }

            return(_result);
        }
 /// <summary>
 /// Handler for restoring the bindings. This is called when the content binding
 /// is restored, and if this is successful, the object is rebound to the original
 /// location it was bound to when last saved.
 /// </summary>
 /// <param name="contentBinding">Content binding.</param>
 /// <param name="resultCode">Result code.</param>
 void HandleBindingRestore(MLContentBinding contentBinding, MLResult result)
 {
     if (result.IsOk)
     {
         SetProgress(string.Format(TEXT_RESTORING_OBJECT, contentBinding.GameObject.name, "succeeded"));
         contentBinding.GameObject.SetActive(true);
         Debug.LogFormat("object: {0} - {1} {2} {3} , {4} {5} {6} {7}", contentBinding.GameObject.name,
                         contentBinding.GameObject.transform.position.x,
                         contentBinding.GameObject.transform.position.y,
                         contentBinding.GameObject.transform.position.z,
                         contentBinding.GameObject.transform.rotation.x,
                         contentBinding.GameObject.transform.rotation.y,
                         contentBinding.GameObject.transform.rotation.z,
                         contentBinding.GameObject.transform.rotation.w);
     }
     else
     {
         SetProgress(string.Format(TEXT_RESTORING_OBJECT, contentBinding.GameObject.name, "failed"));
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Connects the MLCamera component and instantiates a new instance
 /// if it was never created.
 /// </summary>
 private void EnableMLCamera()
 {
     #if PLATFORM_LUMIN
     lock (_cameraLockObject)
     {
         MLResult result = MLCamera.Start();
         if (result.IsOk)
         {
             result             = MLCamera.Connect();
             _isCameraConnected = true;
         }
         else
         {
             Debug.LogErrorFormat("Error: ImageCaptureExample failed starting MLCamera, disabling script. Reason: {0}", result);
             enabled = false;
             return;
         }
     }
     #endif
 }
Esempio n. 8
0
        /// <summary>
        /// Stop capturing video.
        /// </summary>
        public void EndCapture(bool captureCanceled = false)
        {
            if (_isCapturing)
            {
                #if PLATFORM_LUMIN
                MLResult result = MLCamera.StopVideoCapture();
                if (result.IsOk)
                {
                    // If we did not record long enough make sure our path is marked as invalid to avoid trying to load invalid file.
                    if (Time.time - _captureStartTime < _minRecordingTime)
                    {
                        _captureFilePath = null;
                    }

                    if (!captureCanceled)
                    {
                        if (_rawVideoCaptureMode)
                        {
                            OnRawVideoCaptureEnded.Invoke();
                        }
                        else
                        {
                            OnVideoCaptureEnded.Invoke(_captureFilePath);
                        }
                    }

                    _isCapturing      = false;
                    _captureStartTime = 0;
                    _captureFilePath  = null;
                }
                else
                {
                    Debug.LogErrorFormat("Error: VideoCaptureExample failed to end video capture. Error Code: {0}", MLCamera.GetErrorCode().ToString());
                }
                #endif
            }
            else
            {
                Debug.LogError("Error: VideoCaptureExample failed to end video capture because the camera is not recording.");
            }
        }
Esempio n. 9
0
    void Awake()
    {
        MLResult hResult  = MLHands.Start();
        MLResult iResult  = MLInput.Start();
        MLResult pResult  = MLWorldPlanes.Start();
        MLResult wrResult = MLWorldRays.Start();

        if (
            !hResult.IsOk ||
            !iResult.IsOk ||
            !pResult.IsOk ||
            !wrResult.IsOk
            )
        {
            Debug.LogError("Error starting ML APIs, disabling script.");
            enabled = false;
            return;
        }

        // HANDS
        var enabledPoses = new MLHandKeyPose[] {
            MLHandKeyPose.Fist,
        };

        MLHands.KeyPoseManager.EnableKeyPoses(enabledPoses, true);

        // INPUT
        _iController = MLInput.GetController(MLInput.Hand.Left);

        // WORLD PLANES
        var queryParams = new MLWorldPlanesQueryParams();
        var queryFlags  = MLWorldPlanesQueryFlags.Horizontal | MLWorldPlanesQueryFlags.SemanticFloor;

        queryParams.Flags      = queryFlags;
        queryParams.MaxResults = WP_MAX_PLANES;
        MLWorldPlanes.GetPlanes(queryParams, HandleOnReceivedPlanes);

        // WORLD RAYS
        _wrBaseHeight      = transform.position.y;
        _wrLastCentimeters = (int)Math.Truncate(_wrBaseHeight * 100);
    }
Esempio n. 10
0
        /// <summary>
        /// Set correct render mode for meshing and update meshing settings.
        /// </summary>
        void Start()
        {
            #if PLATFORM_LUMIN
            // Assure that if the 'WorldReconstruction' privilege is missing, then it is logged for all users.
            MLResult result = MLPrivilegesStarterKit.Start();
            if (result.IsOk)
            {
                result = MLPrivilegesStarterKit.CheckPrivilege(MLPrivileges.Id.WorldReconstruction);
                if (result.Result != MLResult.Code.PrivilegeGranted)
                {
                    Debug.LogErrorFormat("Error: MeshingExample failed to create Mesh Subsystem due to missing 'WorldReconstruction' privilege. Please add to manifest. Disabling script.");
                    enabled = false;
                    return;
                }
                MLPrivilegesStarterKit.Stop();
            }
            else
            {
                Debug.LogErrorFormat("Error: MeshingExample failed starting MLPrivileges, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            result = MLHeadTracking.Start();
            if (result.IsOk)
            {
                MLHeadTracking.RegisterOnHeadTrackingMapEvent(OnHeadTrackingMapEvent);
            }
            else
            {
                Debug.LogError("MeshingExample could not register to head tracking events because MLHeadTracking could not be started.");
            }
            #endif

            _meshingVisualizer.SetRenderers(_renderMode);

            _mlSpatialMapper.gameObject.transform.position   = _camera.gameObject.transform.position;
            _mlSpatialMapper.gameObject.transform.localScale = _bounded ? _boundedExtentsSize : _boundlessExtentsSize;

            _visualBounds.SetActive(_bounded);
        }
Esempio n. 11
0
        /// <summary>
        /// Attempts to start the MLPersistentStore and MLPersistentCoordinateFrames APIs
        /// </summary>
        void StartAPIs()
        {
            _statusText.text = "Status: Starting up Systems";

            MLResult result = MLPersistentStore.Start();

            if (!result.IsOk)
            {
                if (result.Code == MLResultCode.PrivilegeDenied)
                {
                    Instantiate(Resources.Load("PrivilegeDeniedError"));
                }

                Debug.LogErrorFormat("Error: PersistenceExample failed starting MLPersistentStore, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            result = MLPersistentCoordinateFrames.Start();
            if (!result.IsOk)
            {
                if (result.Code == MLResultCode.PrivilegeDenied)
                {
                    Instantiate(Resources.Load("PrivilegeDeniedError"));
                }

                MLPersistentStore.Stop();
                Debug.LogErrorFormat("Error: PersistenceExample failed starting MLPersistentCoordinateFrames, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            if (MLPersistentCoordinateFrames.IsReady)
            {
                PerformStartup();
            }
            else
            {
                MLPersistentCoordinateFrames.OnInitialized += HandleInitialized;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Deletes a contact. Called by ContactListPage.
        /// </summary>
        /// <param name="id">ID of the Contact</param>
        public void DeleteContact(string id)
        {
            Log("Deleting contact");

            ulong requestHandle = 0;

            if (!string.IsNullOrEmpty(id) && _loadedContacts.ContainsKey(id))
            {
                MLResult result = MLContacts.DeleteContact(_loadedContacts[id], out requestHandle);
                if (!result.IsOk)
                {
                    Debug.LogErrorFormat("Error: ContactsExample failed to delete contact. Reason: {0}", result);
                    Log(string.Format("<color=red>Failed to delete contact. {0}</color>", result));
                }
            }
            else
            {
                Debug.LogErrorFormat("Error: ContactsExample failed to delete contact. Reason: Invalid ID {0}", id);
                Log("<color=red>Failed to delete contact.</color>");
            }
        }
Esempio n. 13
0
        // Start is called before the first frame update
        void Start()
        {
            if (!MLInput.IsStarted)
            {
                MLResult inputStartResult = MLInput.Start();
                switch (inputStartResult.Result)
                {
                case MLResult.Code.Ok:
                {
                    print("ActsAsSwipeable -- started");
                }
                break;

                case MLResult.Code.InvalidParam:
                    throw new System.NotImplementedException();

                case MLResult.Code.PrivilegeDenied:
                    throw new System.NotImplementedException();
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Request privileges.
        /// </summary>
        /// <param name="privileges">An array of privileges to request.</param>
        public static MLResult RequestPrivileges(params MLPrivileges.Id[] privileges)
        {
            #if PLATFORM_LUMIN
            foreach (MLPrivileges.Id privilege in privileges)
            {
                _result = CheckPrivilege(privilege);
                if (_result.Result == MLResult.Code.PrivilegeGranted)
                {
                    continue;
                }

                _result = MLPrivileges.RequestPrivilege(privilege);
                if (_result.Result != MLResult.Code.PrivilegeGranted)
                {
                    return(_result);
                }
            }
            #endif

            return(_result);
        }
Esempio n. 15
0
    private void HandleOnReceivedPlanes(MLResult result, MLWorldPlane[] planes, MLWorldPlaneBoundaries[] boundaries)
    {
        GameObject newPlane;

        // Destroy and Remove Old Planes
        for (int i = _planeCache.Count - 1; i >= 0; --i)
        {
            Destroy(_planeCache[i]);
            _planeCache.Remove(_planeCache[i]);
        }

        // Add New Planes to Cache
        for (int i = 0; i < planes.Length; ++i)
        {
            newPlane = Instantiate(PlaneGameObject);
            newPlane.transform.position   = planes[i].Center;
            newPlane.transform.rotation   = planes[i].Rotation;
            newPlane.transform.localScale = new Vector3(planes[i].Width, planes[i].Height, 1f);
            _planeCache.Add(newPlane);
        }
    }
Esempio n. 16
0
    /// <summary>
    /// Worker function to call the API's Capture function
    /// </summary>
    private void CaptureThreadWorker()
    {
        lock (_cameraLockObject)
        {
            if (MLCamera.IsStarted && _isCameraConnected)
            {
                Debug.Log("===============Start Capturing");
                MLResult result = MLCamera.CaptureRawImageAsync();
                Debug.Log("===============Captured result:" + result.Code);

                if (result.IsOk)
                {
                    _isCapturing = true;
                }
                else if (result.Code == MLResultCode.PrivilegeDenied)
                {
                    _doPrivPopup = true;
                }
            }
        }
    }
Esempio n. 17
0
        /// <summary>
        /// Try get controller reference.
        ///
        /// This is because "MLInput.OnControllerConnected" event won't invoke.
        /// I think why Zenject.IInitialize timing is too late to register an event.
        /// So this method try to get a reference cotroller at the initializing.
        /// </summary>
        private void TryGetController()
        {
            if (_inputController != null)
            {
                return;
            }

            if (!MLInput.IsStarted)
            {
                return;
            }

            MLResult result = MLInput.Start();

            if (!result.IsOk)
            {
                return;
            }

            _inputController = MLInput.GetController(0);
        }
Esempio n. 18
0
        /// <summary>
        /// Set the longer dimension of the Image Target.
        /// This method can be used to change the dimension of the image target at runtime.
        /// This should not be called before the image target is added to the tracker system.
        /// </summary>
        /// <param name="longerDimension">longer dimension of the image target in scene units.</param>
        /// <returns/>
        public MLResult SetTargetLongerDimension(float longerDimension)
        {
            MLResult result;

            #if PLATFORM_LUMIN
            if (_imageTarget == null)
            {
                result = MLResult.Create(MLResult.Code.InvalidParam, "Invalid image target");
                Debug.LogErrorFormat("MLImageTrackerBehavior.SetTargetLongerDimension failed to set the longer dimension of the image target. Reason: {0}", result);
                return(result);
            }

            result = _imageTarget.Target.SetTargetLongerDimension(longerDimension);
            if (result.IsOk)
            {
                longerDimensionInSceneUnits = longerDimension;
            }
            #endif

            return(result);
        }
Esempio n. 19
0
        /// <summary>
        /// Connects the MLCamera component and instantiates a new instance
        /// if it was never created.
        /// </summary>
        private void EnableMLCamera()
        {
            MLResult result = MLCamera.Start();

            if (result.IsOk)
            {
                result             = MLCamera.Connect();
                _isCameraConnected = true;
            }
            else
            {
                if (result.Code == MLResultCode.PrivilegeDenied)
                {
                    Instantiate(Resources.Load("PrivilegeDeniedError"));
                }

                Debug.LogErrorFormat("Error: VideoCaptureExample failed starting MLCamera, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }
        }
        //Init:
        private void Start()
        {
            //sets:
            _previousHand = handedness;

            //startup:
            if (!MLInput.IsStarted)
            {
                MLResult result = MLInput.Start();
                if (!result.IsOk)
                {
                    enabled = false;
                }
            }

            GetControl();

            //hooks:
            MLInput.OnControllerConnected    += HandleControlConnected;
            MLInput.OnControllerDisconnected += HandleControlDisconnected;
        }
Esempio n. 21
0
        /// <summary>
        /// Ends the collision matching the id and handle passed.
        /// </summary>
        /// <param name="collisionId">The id of the collider object.</param>
        /// <param name="collisionHandle">The handle for the collision session.</param>
        void EndCollision(CollisionType type, int collisionId, ulong collisionHandle)
        {
            if (type == CollisionType.Hard)
            {
                hardCollisionMap.Remove(collisionId);
            }
            else if (type == CollisionType.Soft)
            {
                softCollisionMap.Remove(collisionId);
            }

            #if PLATFORM_LUMIN
            MLResult result = MLMovement.EndCollision(sessionHandle, collisionHandle);

            if (!result.IsOk)
            {
                Debug.LogErrorFormat("MLMovementBehavior.EndCollision failed to end collision session, disabling script. Reason: {0}", result);
                enabled = false;
            }
            #endif
        }
Esempio n. 22
0
        /// <summary>
        /// Handles the event for trigger down.
        /// </summary>
        /// <param name="controllerId">The id of the controller.</param>
        /// <param name="triggerValue">The value of the trigger.</param>
        private void HandleOnTriggerDown(byte controllerId, float triggerValue)
        {
            if (_hasStarted && MLImageTracker.IsStarted && _controllerConnectionHandler.IsControllerValid(controllerId))
            {
                // The ImageTracker status before it is changed
                bool trackerStatus = MLImageTracker.GetTrackerStatus();

                // Try to change the ImageTracker status
                MLResult result = trackerStatus ? MLImageTracker.Disable() : MLImageTracker.Enable();

                if (!result.IsOk)
                {
                    Debug.LogErrorFormat("Error: Failed to {0} the ImageTracker.", trackerStatus ? "disable" : "enable");
                }

                else
                {
                    _trackerStatusLabel.text = "Tracker Status: " + (trackerStatus ? "Disabled" : "Enabled");
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Starts a new soft collision session given some collider data.
        /// </summary>
        /// <param name="other">The collider data.</param>
        void StartSoftCollision(ref Collider other)
        {
            #if PLATFORM_LUMIN
            ulong collisionHandle = UnityEngine.XR.MagicLeap.Native.MagicLeapNativeBindings.InvalidHandle;

            Vector3 thisCenter       = objectCollider.bounds.center;
            Vector3 otherCenter      = other.bounds.center;
            float   maxDistance      = Vector3.Distance(thisCenter, otherCenter);
            float   closesetDistance = maxDistance * (other.gameObject.GetComponent <MLMovementColliderBehavior>().MaxDepth / 100.0f);

            MLResult result = MLMovement.StartSoftCollision(sessionHandle, otherCenter, closesetDistance, maxDistance, out collisionHandle);
            if (!result.IsOk)
            {
                Debug.LogErrorFormat("MLMovementBehavior.StartSoftCollision failed to start a soft collision, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            softCollisionMap.Add(other.gameObject.GetInstanceID(), collisionHandle);
            #endif
        }
Esempio n. 24
0
    private void OnEnable()
    {
        MLResult result = MLHands.Start();

        if (!result.IsOk)
        {
            Debug.LogError("Error GesturesExample starting MLHands, disabling script.");
            enabled = false;
        }
        else
        {
            MLHandKeyPose[] poseSet = { MLHandKeyPose.Pinch, MLHandKeyPose.C, MLHandKeyPose.L, MLHandKeyPose.Thumb };
            var             status  = MLHands.KeyPoseManager.EnableKeyPoses(poseSet, true, true);
            if (!status)
            {
                Debug.LogError("HandTracking failed during a call to enable tracked KeyPoses.\n"
                               + "Disabling HandTracking component.");
                enabled = false;
            }
        }
    }
Esempio n. 25
0
        /**
         * Returns the GPS location from the paired CompanionApp phone/device.
         */
        public async Task <LocationReply> GetLocation()
        {
            Logger.D(TAG, "GetLocation()");

            if (!MLLocation.IsStarted)
            {
                Logger.D(TAG, "Please start MagicLeap's MLLocation object from a GameObject/MonoBehavior before using this call.");
                // Hm, Debug: return something.
                Logger.D(TAG, "FIXME: Returning a hard coded value...");
                return(new LocationReply
                {
                    longitude = -121.955238,
                    latitude = 37.354107
                });
            }

            MLLocation.Location locData = new MLLocation.Location();
            MLResult            result  = MLLocation.GetLastFineLocation(out locData);

            Logger.D(TAG, "MLLocation result: " + result); // Ensure location is allowed.
            if (!result.Equals(MLResult.Create(MLResult.Code.Ok)))
            {
                // Try coarse instead:
                result = MLLocation.GetLastCoarseLocation(out locData);
                if (!result.Equals(MLResult.Create(MLResult.Code.Ok)))
                {
                    Logger.D(TAG, "Empty location returning");
                    return(new LocationReply {
                        longitude = 0f, latitude = 0f
                    });
                }
            }

            Logger.D(TAG, "New location returning: {" + locData.Longitude + ", " + locData.Latitude + "}");
            return(new LocationReply
            {
                longitude = locData.Longitude,
                latitude = locData.Latitude
            });
        }
Esempio n. 26
0
        /// <summary>
        /// Starts up MLHandTracking.
        /// </summary>
        /// <param name="initializeValues">Bool that determines if MLHandTracking should automatically run with all poses and high filter levels.</param>
        public static MLResult Start(bool initializeValues = false)
        {
            #if PLATFORM_LUMIN
            MLResult _result = MLHandTracking.Start();
            if (!_result.IsOk)
            {
                Debug.LogErrorFormat("Error: MLHandTrackingStarterKit failed starting MLHandTracking. Reason: {0}", _result);
            }

            if (initializeValues)
            {
                bool success = false;

                success = EnableKeyPoses();
                if (!success)
                {
                    MLHandTracking.Stop();
                    _result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLHandTrackingStarterKit failed to start correctly because MLHandTrackingStarterKit.EnablePoses failed because MLHandTracking.KeyPoseManager.EnableKeyPoses failed.");
                }

                success = SetKeyPointsFilterLevel(MLHandTracking.KeyPointFilterLevel.ExtraSmoothed);
                if (!success)
                {
                    MLHandTracking.Stop();
                    _result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLHandTrackingStarterKit failed to start correctly because MLHandTrackingStarterKit.SetKeyPointsFilterLevel failed because MLHandTracking.KeyPoseManager.SetKeyPointsFilterLevel failed.");
                }

                success = SetPoseFilterLevel(MLHandTracking.PoseFilterLevel.ExtraRobust);
                if (!success)
                {
                    MLHandTracking.Stop();
                    _result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLHandTrackingStarterKit failed to start correctly because MLHandTrackingStarterKit.SetPoseFilterLevel failed because MLHandTracking.KeyPoseManager.SetPoseFilterLevel failed.");
                }
            }

            return(_result);
            #else
            return(new MLResult());
            #endif
        }
Esempio n. 27
0
        #pragma warning restore 414

        /// <summary>
        /// Locate tracks, connect provided music service provider, initialize MLMusicService API and setup callbacks.
        /// </summary>
        void Start()
        {
            string[] playlist = new string[StreamingPlaylist.Length];
            for (int i = 0; i < StreamingPlaylist.Length; ++i)
            {
                string streamingPath  = Path.Combine(Path.Combine(Application.streamingAssetsPath, StreamingAssetsLocationFolder), StreamingPlaylist[i]);
                string persistentPath = Path.Combine(Application.persistentDataPath, StreamingPlaylist[i]);
                // The Music Provider will only search for songs correctly in /documents/C1 or /documents/C2 by their filename
                // This allows us to package the songs with the Unity application and deploy them from Streaming Assets.
                if (!File.Exists(persistentPath))
                {
                    File.Copy(streamingPath, persistentPath);
                }
                playlist[i] = "file://" + StreamingPlaylist[i];
            }

            #if PLATFORM_LUMIN
            MLResult result = MLMusicService.Start(MusicServiceProvider);
            if (!result.IsOk)
            {
                Debug.LogErrorFormat("Error: MLMusicServiceBehavior failed starting MLMusicService, disabling script. Reason: {0}", result);
                enabled = false;
                return;
            }

            MLMusicService.OnPlaybackStateChange += HandlePlaybackStateChanged;
            MLMusicService.OnShuffleStateChange  += HandleShuffleStateChanged;
            MLMusicService.OnRepeatStateChange   += HandleRepeatStateChanged;
            MLMusicService.OnMetadataChange      += HandleMetadataChanged;
            MLMusicService.OnPositionChange      += HandlePositionChanged;
            MLMusicService.OnError        += HandleError;
            MLMusicService.OnStatusChange += HandleServiceStatusChanged;

            MLMusicService.RepeatState  = MLMusicService.RepeatStateType.Off;
            MLMusicService.ShuffleState = MLMusicService.ShuffleStateType.Off;

            MLMusicService.SetPlayList(playlist);
            MLMusicService.StartPlayback();
            #endif
        }
Esempio n. 28
0
        /// <summary>
        /// Start this instance.
        /// </summary>
        void Start()
        {
            MLResult result = MLPersistentStore.Start();

            if (!result.IsOk)
            {
                SetError("Failed to start persistent store. Disabling component");
                enabled = false;
                return;
            }
            result = MLPersistentCoordinateFrames.Start();
            if (!result.IsOk)
            {
                MLPersistentStore.Stop();
                SetError("Failed to start coordinate frames system. disabling component");
                enabled = false;
                return;
            }

            if (_representativePrefab == null)
            {
                SetError("Error: _representativePrefab must be set");
                enabled = false;
                return;
            }

            List <MLPCF> pcfList;

            result = MLPersistentCoordinateFrames.GetAllPCFs(out pcfList, int.MaxValue);
            if (!result.IsOk)
            {
                MLPersistentStore.Stop();
                MLPersistentCoordinateFrames.Stop();
                SetError(result.ToString());
                enabled = false;
                return;
            }

            TryShowingAllPCFs(pcfList);
        }
        /// <summary>
        /// Reads all stored persistent bindings.
        /// Each stored binding will contain a PCF object with a CFUID.
        /// Use that stored CFUID to see if the PCF exists in this session, if it does then the stored binding can be regained.
        /// If the binding is regained correctly then the persistent content will retain it's pose from the last known launch.
        /// </summary>
        private void RegainAllStoredBindings()
        {
            #if PLATFORM_LUMIN
            TransformBinding.storage.LoadFromFile();

            List <TransformBinding> allBindings = TransformBinding.storage.Bindings;

            List <TransformBinding> deleteBindings = new List <TransformBinding>();

            foreach (TransformBinding storedBinding in allBindings)
            {
                // Try to find the PCF with the stored CFUID.
                MLResult result = MLPersistentCoordinateFrames.FindPCFByCFUID(storedBinding.PCF.CFUID, (MLResult.Code resultCode, MLPersistentCoordinateFrames.PCF pcf) =>
                {
                    if (pcf != null && MLResult.IsOK(pcf.CurrentResultCode))
                    {
                        GameObject gameObj = Instantiate(_content, Vector3.zero, Quaternion.identity);
                        PersistentBall persistentContent       = gameObj.GetComponent <PersistentBall>();
                        persistentContent.BallTransformBinding = storedBinding;
                        persistentContent.BallTransformBinding.Bind(pcf, gameObj.transform, true);
                        ContentTap contentTap    = persistentContent.GetComponent <ContentTap>();
                        contentTap.OnContentTap += OnContentDestroy;
                        ++numPersistentContentRegained;
                        _persistentContentMap.Add(persistentContent, "Regained");
                    }
                    else
                    {
                        deleteBindings.Add(storedBinding);
                    }
                });
            }

            foreach (TransformBinding storedBinding in deleteBindings)
            {
                storedBinding.UnBind();
            }

            bindingsLoaded = true;
            #endif
        }
Esempio n. 30
0
        /// <summary>
        /// Event handler for the metadata of the track being changed
        /// </summary>
        /// <param name="metaData">Metadata of the track</param>
        void HandleMetadataChanged(MLMusicService.Metadata metaData)
        {
            CurrentTrackMetadata = metaData;
            MLResult result = MLMusicService.GetMetadata(ref previousTrackMetadata, -1);

            if (!result.IsOk)
            {
                Debug.LogErrorFormat("MLMusicServiceBehavior failed to get the metadata of the previous track, disabling script. Reason: {0}.", result);
                enabled = false;
                return;
            }

            result = MLMusicService.GetMetadata(ref nextTrackMetadata, 1);
            if (!result.IsOk)
            {
                Debug.LogErrorFormat("MLMusicServiceBehavior failed to get the metadata of the next track, disabling script. Reason: {0}.", result);
                enabled = false;
                return;
            }

            OnMetadataChanged?.Invoke(metaData);
        }