/// <summary> /// Requests the specified privileges. This may possibly solicit consent from the end-user. /// </summary> /// <param name="privilegeId">The privilege to request.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.PrivilegeGranted</c> if the privilege is granted. /// MLResult.Result will be <c>MLResult.Code.PrivilegeNotGranted</c> if the privilege is denied. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the privilege system was not started. /// </returns> public static MLResult RequestPrivilege(MLPrivileges.Id privilegeId) { try { if (MLPrivileges.IsValidInstance()) { MLResult.Code requestPrivilegeResult = NativeBindings.MLPrivilegesRequestPrivilege(privilegeId); MLResult result = MLResult.Create(requestPrivilegeResult); if (result.Result != MLResult.Code.PrivilegeGranted) { MLPluginLog.ErrorFormat("MLPrivileges.RequestPrivilege failed to request {0}. Reason: {1}", privilegeId, result); } return(result); } else { MLPluginLog.ErrorFormat("MLPrivileges.RequestPrivilege failed. Reason: No Instance for MLPrivileges."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLPrivileges.RequestPrivilege failed. Reason: No Instance for MLPrivileges.")); } } catch (System.EntryPointNotFoundException) { MLPluginLog.Error("MLPrivileges.RequestPrivilege failed. Reason: API symbols not found"); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLPrivileges.RequestPrivilege failed. Reason: API symbols not found.")); } }
/// <summary> /// Updates the state of the PCF. /// </summary> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if operation completed successfully. /// 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> private MLResult UpdateState() { if (MLPersistentCoordinateFrames.IsValidInstance()) { try { NativeBindings.FrameStateNative nativeState = NativeBindings.FrameStateNative.Create(); MLResult.Code resultCode = NativeBindings.MLPersistentCoordinateFramesGetFrameState(MLPersistentCoordinateFrames._instance.nativeTracker, in this.cfuid, ref nativeState); if (!MLResult.IsOK(resultCode)) { MLPluginLog.ErrorFormat("PCF.UpdateState failed to get frame state. Reason: {0}", MLResult.CodeToString(resultCode)); return(MLResult.Create(resultCode, string.Format("PCF.UpdateState failed to get frame state. Reason: {0}", MLResult.CodeToString(resultCode)))); } this.FrameState = nativeState.Data(); return(MLResult.Create(resultCode)); } catch (EntryPointNotFoundException) { MLPluginLog.Error("PCF.UpdateState failed. Reason: API symbols not found."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "PCF.UpdateState failed. Reason: API symbols not found.")); } } else { MLPluginLog.ErrorFormat("PCF.UpdateState failed. Reason: No Instance for MLPersistentCoordinateFrames."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "PCF.UpdateState failed. Reason: No Instance for MLPersistentCoordinateFrames.")); } }
/// <summary> /// Gets the most recent Head Tracking state. /// </summary> /// <param name="state">Some MLHeadTracking.State object to be filled with current state information.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the head tracking state was successfully received. /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if the outState parameter was not valid (null). /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed to receive head tracking state. /// </returns> public static MLResult GetState(out State state) { state = new State(); if (MLHeadTracking.IsValidInstance()) { try { MLResult.Code resultCode = NativeBindings.MLHeadTrackingGetState(_instance.handle, ref _instance.stateNative); state.Mode = (TrackingMode)_instance.stateNative.Mode; state.Confidence = _instance.stateNative.Confidence; state.Error = (TrackingError)_instance.stateNative.Error; state.Handle = _instance.handle; return(MLResult.Create(resultCode)); } catch (EntryPointNotFoundException) { MLPluginLog.Error("MLHeadTracking.GetState failed. Reason: API symbols not found."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure)); } } else { MLPluginLog.ErrorFormat("MLHeadTracking.GetState failed. Reason: No Instance for MLHeadTracking."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLHeadTracking.GetState failed. Reason: No Instance for MLHeadTracking.")); } }
/// <summary> /// Start tracking hands with all key poses disabled. /// </summary> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed to initialize the native hand tracker. /// </returns> protected override MLResult.Code StartAPI() { this.left = new Hand(MLHandTracking.HandType.Left); this.right = new Hand(MLHandTracking.HandType.Right); // Initialize KeyPoseManager, to register the gesture subsystem. this.keyposeManager = new KeyposeManager(Left, Right); try { // Attempt to start the tracker & validate. NativeBindings.SetHandGesturesEnabled(true); if (!NativeBindings.IsHandGesturesEnabled()) { MLPluginLog.Error("MLHandTracking.StartAPI failed to initialize the native hand tracker."); return(MLResult.Code.UnspecifiedFailure); } } catch (EntryPointNotFoundException) { MLPluginLog.Error("MLHandTracking.StartAPI failed. Reason: API symbols not found."); return(MLResult.Code.UnspecifiedFailure); } return(MLResult.Code.Ok); }
unsafe int NativeReceive(ref UdpCHeader header, void *data, int length, ref network_address address) { #if ENABLE_UNITY_COLLECTIONS_CHECKS if (length <= 0) { throw new ArgumentException("Can't receive into 0 bytes or less of buffer memory"); } #endif var iov = stackalloc network_iovec[2]; fixed(byte *ptr = header.Data) { iov[0].buf = ptr; iov[0].len = UdpCHeader.Length; iov[1].buf = data; iov[1].len = length; } int errorcode = 0; var result = NativeBindings.network_recvmsg(socket, iov, 2, ref address, ref errorcode); if (result == -1) { if (errorcode == 10035 || errorcode == 35 || errorcode == 11) { return(0); } receiver.ReceiveErrorCode = errorcode; } return(result); }
// clean up and close everything void CleanUpAndClose() { // close client if already created // (it's still -1 for a short moment after calling Connect) if (socket != -1) { int error = 0; if (NativeBindings.network_close(socket, ref error) != 0) { Debug.LogError("network_close client failed: " + (NativeError)error); } socket = -1; } // not connected anymore lock (this) { _Connected = false; _Connecting = false; } // reset GetNextMessage helpers lastConnected = false; contentSize = 0; }
/// <summary> /// Gets the result string for a MLResult.Code. Use MLResult.CodeToString(MLResult.Code) to get the string value of any MLResult.Code. /// </summary> /// <param name="result">The MLResult.Code to be requested.</param> /// <returns>A pointer to the result string.</returns> internal static IntPtr GetResultString(MLResult.Code result) { try { if (MLIdentity.IsValidInstance()) { try { return(NativeBindings.MLIdentityGetResultString(result)); } catch (EntryPointNotFoundException) { MLPluginLog.Error("MLIdentity.GetResultString failed. Reason: API symbols not found."); } return(IntPtr.Zero); } else { MLPluginLog.ErrorFormat("MLIdentity.GetResultString failed. Reason: No Instance for MLIdentity."); } } catch (EntryPointNotFoundException) { MLPluginLog.Error("MLIdentity.GetResultString failed. Reason: API symbols not found."); } return(IntPtr.Zero); }
/// <summary> /// Initializes the given AppDefinedVideoSource object. /// </summary> /// <param name="appDefinedVideoSource">The AppDefinedVideoSource object to initialize.</param> /// <param name="result">The MLResult object of the inner platform call(s).</param> /// <returns>An AppDefinedVideoSource object with the given handle.</returns> public static MLResult InitializeLocal(AppDefinedVideoSource appDefinedVideoSource) { MLWebRTC.Instance.localTracks.Add(appDefinedVideoSource); MLResult.Code resultCode = NativeBindings.InitializeAppDefinedVideoSource(appDefinedVideoSource); DidNativeCallSucceed(resultCode, "InitializeAppDefinedVideoSource()"); return(MLResult.Create(resultCode)); }
private MLResult RequestPrivilegeAsyncInternal(MLPrivileges.Id privilegeId, CallbackDelegate callback) { if (callback == null) { return(MLResult.Create(MLResult.Code.InvalidParam, "MLPrivileges.RequestPrivilegeAsync failed. Reason: Must send a valid callback.")); } if (!this.currentRequests.ContainsKey(privilegeId)) { IntPtr newRequest = IntPtr.Zero; MLResult.Code resultCode = NativeBindings.MLPrivilegesRequestPrivilegeAsync(privilegeId, ref newRequest); if (resultCode == MLResult.Code.Ok) { RequestPrivilegeQuery newQuery = new RequestPrivilegeQuery(callback, newRequest, privilegeId); this.currentRequests.Add(privilegeId, newQuery); } return(MLResult.Create(resultCode)); } else { return(MLResult.Create(MLResult.Code.Ok)); } }
/// <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); }
/// <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> /// Helper method that the MLArucoTracker API uses to marshal the results recieved from the device. /// Results are released after being queried for. /// </summary> /// <param name="trackerResults">The array of marker results found by the device.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successfully fetched and returned all detections. /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed to return detection data due to an invalid resultArray. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed to return detections due to an internal error. /// </returns> public static MLResult.Code GetResults(out MLArucoTrackerResultNative[] trackerResultsArray) { MLResult.Code resultCode = (NativeBindings.MLArucoTrackerGetResult(Instance.Handle, out MLArucoTrackerResultArrayNative resultsArray)); if (!MLArucoTracker.DidNativeCallSucceed(resultCode)) { trackerResultsArray = new MLArucoTrackerResultNative[0]; return(resultCode); } trackerResultsArray = new MLArucoTrackerResultNative[resultsArray.Count]; for (int i = 0; i < resultsArray.Count; i++) { IntPtr offsetPtr = Marshal.ReadIntPtr(new IntPtr(resultsArray.Detections.ToInt64() + (Marshal.SizeOf(typeof(IntPtr)) * i))); MLArucoTrackerResultNative trackerResult = (MLArucoTrackerResultNative)Marshal.PtrToStructure(offsetPtr, typeof(MLArucoTrackerResultNative)); trackerResultsArray[i] = trackerResult; } resultCode = NativeBindings.MLArucoTrackerReleaseResult(ref resultsArray); foreach (NativeBindings.MLArucoTrackerResultNative trackerResult in trackerResultsArray) { if (!NativeBindings.MapTrackerResults.ContainsKey(trackerResult.Id)) { NativeBindings.MapTrackerResults.Add(trackerResult.Id, trackerResult); } } if (!MLArucoTracker.DidNativeCallSucceed(resultCode)) { return(resultCode); } return(resultCode); }
public bool Send(int connectionId, ArraySegment <byte> segment) { // respect max message size to avoid allocation attacks. if (segment.Count <= MaxMessageSize) { // find the connection if (clients.TryGetValue(connectionId, out ClientToken token)) { // try to send if (!SendIfNotFull(token.socket, segment)) { // didn't work, time to close the connection // (aka TCP for games. instead of threads, we use huge // send buffers + nonblocking mode. and if buffer is // full, we consider it a timeout) int error = 0; if (NativeBindings.network_close(token.socket, ref error) != 0) { Debug.LogError("network_close client failed: " + (NativeError)error); } token.socket = -1; // note: client will be removed in GetNextMessages // automatically. no need to do it here. return(false); } return(true); } Debug.Log("[Server] Send: invalid connectionId: " + connectionId); return(false); } Debug.LogError("[Server] Send: message too big: " + segment.Count + ". Limit: " + MaxMessageSize); return(false); }
unsafe int NativeReceive(ref UdpCHeader header, void *data, int length, ref NetworkEndPoint address) { #if ENABLE_UNITY_COLLECTIONS_CHECKS if (length <= 0) { Debug.LogError("Can't receive into 0 bytes or less of buffer memory"); return(0); } #endif var iov = stackalloc network_iovec[2]; fixed(byte *ptr = header.Data) { iov[0].buf = ptr; iov[0].len = UdpCHeader.Length; iov[1].buf = data; iov[1].len = length; } var result = NativeBindings.network_recvmsg(socket, iov, 2, ref address); if (result == -1) { int err = Marshal.GetLastWin32Error(); if (err == 10035 || err == 35 || err == 11) { return(0); } Debug.LogError(string.Format("error on receive {0}", err)); throw new SocketException(err); } return(result); }
/// <summary> /// Connects to the MRCamera and prepares it for capturing. /// </summary> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successfully initialized the MR camera. /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to an invalid input parameter. /// MLResult.Result will be <c>MLResult.Code.MediaGenericAlreadyExists</c> if the MR camera was already initialized. /// MLResult.Result will be <c>MLResult.Code.MediaGenericNoInit</c> if the MR camera was not properly initialized. /// </returns> private MLResult.Code SetupMLMRCamera() { if (this.isConnected) { return(MLResult.Code.Ok); } NativeBindings.InputContextNative contextNative = new NativeBindings.InputContextNative(); contextNative.Data = this.inputContext; MLResult.Code resultCode = NativeBindings.MLMRCameraConnect(ref contextNative); if (!MLMRCamera.DidNativeCallSucceed(resultCode, "MLMRCameraConnect")) { return(resultCode); } this.isConnected = true; NativeBindings.CallbacksNative callbacksNative = NativeBindings.CreateCallbacks(); resultCode = NativeBindings.MLMRCameraSetCallbacks(ref callbacksNative, IntPtr.Zero); if (!MLMRCamera.DidNativeCallSucceed(resultCode, "MLMRCameraSetCallbacks")) { return(resultCode); } return(resultCode); }
/// <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> /// 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> /// External call for querying the last known fine location. /// The accuracy field of the MLLocation.Location provides the estimate accuracy radius in meters. /// Returns the last known fine location data on success and returns the last queried fine location data on failure. Latitude and Longitude of /// 0 should be assumed an Invalid Location. /// </summary> /// <param name="fineLocation">Where to store the last known fine location. Only updates when getting the location succeeds. Latitude and Longitude of 0 should be assumed an Invalid Location.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the location was queried successfully. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an internal error. /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if there was an invalid location. /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if there was a lack of privilege(s). /// MLResult.Result will be <c>MLResult.Code.LocationProviderNotFound</c> if there was no provider or an invalid request was made. /// MLResult.Result will be <c>MLResult.Code.LocationNetworkConnection</c> if there was no internet connection. /// MLResult.Result will be <c>MLResult.Code.LocationNoLocation</c> if the location could not be found. /// </returns> public static MLResult GetLastFineLocation(out Location fineLocation) { try { if (MLLocation.IsValidInstance()) { MLResult result = NativeBindings.MLLocationGetLastLocation(out fineLocation, true); if (result.IsOk) { _instance.lastValidFineLocation = fineLocation; } else { MLPluginLog.ErrorFormat("MLLocation.GetLastFineLocation failed to get location. Reason: {0}", result); } return(result); } else { fineLocation = new Location(); MLPluginLog.ErrorFormat("MLLocation.GetLastFineLocation failed. Reason: No Instance for MLLocation."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocation.GetLastFineLocation failed. Reason: No Instance for MLLocation.")); } } catch (System.EntryPointNotFoundException) { fineLocation = new Location(); MLPluginLog.Error("MLLocation.GetLastFineLocation failed. Reason: API symbols not found"); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocation.GetLastFineLocation failed. Reason: API symbols not found.")); } }
// Send ArraySegment for allocation free calls. byte[] can be allocation // free too, but Mirror would require ArraySegment sending for that. public bool Send(ArraySegment <byte> segment) { // only if connected if (Connected) { // respect max message size to avoid allocation attacks. if (segment.Count <= MaxMessageSize) { // try to send if (!SendIfNotFull(socket, segment)) { // didn't work, time to close the connection // (aka TCP for games. instead of threads, we use huge // send buffers + nonblocking mode. and if buffer is // full, we consider it a timeout) int error = 0; if (NativeBindings.network_close(socket, ref error) != 0) { Debug.LogError("network_close client failed: " + (NativeError)error); } socket = -1; return(false); } return(true); } Debug.LogError("[Client] Send: message too big: " + segment.Count + ". Limit: " + MaxMessageSize); return(false); } Debug.LogWarning("[Client] Send: not connected!"); return(false); }
public static void Main() { var key = new Key(); key.bytes = new byte[] { 1, 2, 3, 5, 7, 11, 13, 17 }; var app = new AppInfo(); app.id = 1234; app.name = "Unique-App"; app.key = key; NativeBindings.RegisterApp(app, (result) => { Console.WriteLine("- C#: RegisterApp(): " + result.error); }); // --- NativeBindings.GetAppId(app, (result, res) => { Console.WriteLine("- C#: GetAppId(): " + result.error + ": " + res); }); // --- NativeBindings.GetAppName(app, (result, res) => { Console.WriteLine("- C#: GetAppName(): " + result.error + ": " + res); }); Thread.Sleep(5000); }
public static MLResult GetDefaultSettings(out MLMovementSettings settings) { errorMsg = "MLMovement.GetDefaultSettings failed due to internal error"; MLMovementSettings tempSettings = default; MLResult GetDefaultSettingsFunc() { NativeBindings.SettingsNative internalSettings = NativeBindings.SettingsNative.Create(); MLResult.Code result = NativeBindings.MLMovementGetDefaultSettings(out internalSettings); if (result != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLMovement.GetDefaultSettings failed to get default movement settings. Reason: {0}", result); } else { tempSettings = internalSettings.DataEx; } return(MLResult.Create(result)); } MLResult finalResult = TryExecute(GetDefaultSettingsFunc); settings = tempSettings; return(finalResult); }
/// <summary> /// Gets a managed operation result for a specific operation handle. /// </summary> /// <param name="handle">Handle to a specific operation.</param> /// <param name="result">Managed operation result.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if any of the parameters are invalid. /// MLResult.Result will be <c>MLResult.Code.Pending</c> if the request is still pending. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error. /// MLResult.Result will be <c>MLResult.Code.ContactsCompleted</c> if the request is completed. /// MLResult.Result will be <c>MLResult.Code.ContactsHandleNotFound</c> if the request corresponding to the handle was not found. /// </returns> public static MLResult.Code GetManagedOperationResult(ulong handle, out MLContacts.OperationResult result) { MLResult.Code resultCode = NativeBindings.MLContactsTryGetOperationResult(handle, out IntPtr operationResultPtr); if (resultCode != MLResult.Code.Pending) { if (resultCode != MLResult.Code.ContactsCompleted) { MLPluginLog.ErrorFormat("NativeBindings.GetManagedOperationResult failed to get operation result. Reason: {0}", MLResult.CodeToString(resultCode)); } NativeBindings.OperationResultNative internalResult = (NativeBindings.OperationResultNative)Marshal.PtrToStructure(operationResultPtr, typeof(NativeBindings.OperationResultNative)); NativeBindings.ContactNative internalContact = (NativeBindings.ContactNative)Marshal.PtrToStructure(internalResult.Contact, typeof(NativeBindings.ContactNative)); result = new MLContacts.OperationResult() { Status = internalResult.Status, Contact = internalContact.Data, }; } else { result = new MLContacts.OperationResult(); } return(resultCode); }
/// <summary> /// Get the current adapter state /// </summary> /// <param name="state">Current Adapter State of the device</param> /// <returns>MLResultCode.Ok on success, or failure</returns> public static MLResult GetAdapterState(out AdapterState state) { // Provide a default value state = AdapterState.Off; return(MLResult.Create(NativeBindings.MLBluetoothAdapterGetState(ref state))); }
/// <summary> /// Gets a managed operation result for a specific operation handle. /// </summary> /// <param name="handle">Handle to a specific operation.</param> /// <param name="listResult">Managed operation result.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if any of the parameters are invalid. /// MLResult.Result will be <c>MLResult.Code.Pending</c> if the request is still pending. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error. /// MLResult.Result will be <c>MLResult.Code.ContactsCompleted</c> if the request is completed. /// MLResult.Result will be <c>MLResult.Code.ContactsHandleNotFound</c> if the request corresponding to the handle was not found. /// </returns> public static MLResult.Code GetManagedListResult(ulong handle, out MLContacts.ListResult listResult) { MLResult.Code resultCode = NativeBindings.MLContactsTryGetListResult(handle, out IntPtr operationResultPtr); if (resultCode != MLResult.Code.Pending) { if (resultCode != MLResult.Code.ContactsCompleted) { MLPluginLog.ErrorFormat("NativeBindings.GetManagedListResult failed to get list result. Reason: {0}", MLResult.CodeToString(resultCode)); } NativeBindings.ListResultNative internalListResult = (NativeBindings.ListResultNative)Marshal.PtrToStructure(operationResultPtr, typeof(NativeBindings.ListResultNative)); listResult = new MLContacts.ListResult() { Status = internalListResult.Status, List = internalListResult.List.Data, Offset = Marshal.PtrToStringAnsi(internalListResult.Offset), TotalHits = internalListResult.TotalHits, }; } else { listResult = new MLContacts.ListResult(); } return(resultCode); }
int CreateAndBindSocket(out long socket, network_address address) { socket = -1; int errorcode = 0; int ret = NativeBindings.network_create_and_bind(ref socket, ref address, ref errorcode); if (ret != 0) { return(errorcode); } #if ENABLE_UNITY_COLLECTIONS_CHECKS AllSockets.OpenSockets.Add(socket); #endif if ((ret = NativeBindings.network_set_nonblocking(socket, ref errorcode)) != 0) { return(errorcode); } if ((ret = NativeBindings.network_set_send_buffer_size(socket, ushort.MaxValue, ref errorcode)) != 0) { return(errorcode); } if ((ret = NativeBindings.network_set_receive_buffer_size(socket, ushort.MaxValue, ref errorcode)) != 0) { return(errorcode); } #if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) // Avoid WSAECONNRESET errors when sending to an endpoint which isn't open yet (unclean connect/disconnects) NativeBindings.network_set_connection_reset(socket, 0); #endif return(0); }
/// <summary> /// Reads the country code of the system locale. /// </summary> /// <param name="country">Country code defined in ISO 3166, or an empty string. Valid only if <c>MLResult.Code.Ok</c> is returned, empty string otherwise.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the country code was retrieved successfully. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an unspecified error. /// </returns> public static MLResult GetSystemCountry(out string country) { IntPtr outCountry = IntPtr.Zero; MLResult result; try { MLResult.Code resultCode = NativeBindings.MLLocaleGetSystemCountry(ref outCountry); result = MLResult.Create(resultCode); if (result.IsOk) { country = MLConvert.DecodeUTF8(outCountry); } else { country = string.Empty; MLPluginLog.ErrorFormat("MLLocale.GetSystemCountry failed. Reason: {0}", result); } } catch (System.DllNotFoundException) { MLPluginLog.Error("MLLocale.GetSystemCountry failed. Reason: MLLocale API is currently available only on device."); result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocale.GetSystemCountry failed. Reason: Dll not found."); country = string.Empty; } catch (System.EntryPointNotFoundException) { MLPluginLog.Error("MLLocale.GetSystemCountry failed. Reason: API symbols not found."); result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocale.GetSystemCountry failed. Reason: API symbols not found."); country = string.Empty; } return(result); }
/// <summary> /// Register a unique schema for <c>OAuth</c> redirect handler. The caller needs to ensure that the schema is unique. /// If the schema is already registered the function will return an error. The handler /// will be called once the authorization procedure has been completed. /// The caller should register two schema callbacks. The first will be for /// authorization redirect and the second schema will in case the user cancels /// the authentication. /// </summary> /// <param name="schema">A unique string that will match the redirect uri schema</param> /// <param name="callback">MLDispatch <c>OAuth</c> callback function</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the new schema has been registered correctly. /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if SecureBrowserWindow privilege is denied. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error. /// MLResult.Result will be <c>MLResult.Code.SchemaAlreadyRegistered</c> if the schema already is registered. /// MLResult.Result will be <c>MLResult.Code.Dispatch*</c> if a dispatch specific error occurred. /// </returns> public static MLResult OAuthRegisterSchema(string schema, ref OAuthHandler callback) { try { NativeBindings.OAuthCallbacksNative newSchema = NativeBindings.OAuthCallbacksNative.Create(); newSchema.OnReplyComplete = OAuthOnReplyNative; int newID = uniqueID + 1; MLResult.Code resultCode = NativeBindings.MLDispatchOAuthRegisterSchemaEx(schema, ref newSchema, new IntPtr(newID)); if (MLResult.IsOK(resultCode)) { OAuthPair newEntry = new OAuthPair(schema, callback); oAuthCallbacks.Add(newID, newEntry); uniqueID = newID; } return(MLResult.Create(resultCode)); } catch (System.DllNotFoundException) { MLPluginLog.Error(DllNotFoundExceptionError); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, DllNotFoundExceptionError)); } catch (System.EntryPointNotFoundException) { MLPluginLog.Error("MLDispatch API symbols not found"); return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLDispatch API symbols not found")); } }
/// <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")); } }
/// <summary> /// Starts the HeadTracking API. /// </summary> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if connected to MLContacts successfully. /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if necessary privilege is missing. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error. /// </returns> protected override MLResult StartAPI() { MLResult.Code resultCode = MLResult.Code.UnspecifiedFailure; try { resultCode = NativeBindings.MLHeadTrackingCreate(ref _instance.handle); if (resultCode != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLHeadTracking.StartAPI failed to create native head tracker."); } resultCode = NativeBindings.MLHeadTrackingGetStaticData(_instance.handle, ref _instance.staticDataNative); if (resultCode != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLHeadTracking.StartAPI failed to get static date from the native head tracker."); } } catch (EntryPointNotFoundException) { MLPluginLog.Error("MLHeadTracking.StartAPI failed. Reason: API symbols not found."); return(MLResult.Create(MLResult.Code.UnspecifiedFailure)); } return(MLResult.Create(resultCode)); }
/// <summary> /// Processes the current pending queries and adds them to the completed queries list when finished. /// Queries that are still pending are skipped from being added to the completed queries list until next Update loop. /// </summary> private void ProcessPendingQueries() { foreach (Query query in this.pendingQueries) { MLResult.Code resultCode = NativeBindings.MLHandMeshingGetResult(this.nativeTracker, query.RequestHandle, ref this.handMeshNativeStruct); if (resultCode == MLResult.Code.Pending) { continue; } query.Result = MLResult.Create(resultCode); if (resultCode == MLResult.Code.Ok) { query.HandMesh = this.handMeshNativeStruct.Data; } this.completedQueries.Add(query); ulong requestHandle = query.RequestHandle; resultCode = NativeBindings.MLHandMeshingFreeResource(this.nativeTracker, ref requestHandle); if (resultCode != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLHandMeshing.ProcessPendingQueries failed to free resource. Reason: {0}", resultCode); } } }