Ejemplo n.º 1
0
        public static unsafe PacketTimers *GetRemotePacketTimer(NativeSlice <byte> sharedBuffer, ushort sequenceId)
        {
            var sharedCtx = (SharedContext *)sharedBuffer.GetUnsafePtr();
            var index     = sequenceId % sharedCtx->WindowSize;
            var timerPtr  = (long)sharedBuffer.GetUnsafePtr() + sharedCtx->RemoteTimerDataOffset + sharedCtx->RemoteTimerDataStride * index;

            return((PacketTimers *)timerPtr);
        }
        public static unsafe void MemCpy <T>(this NativeSlice <T> slice, int destIndex, int sourceIndex, int count)
            where T : unmanaged
        {
            if (destIndex < 0)
            {
                throw new ArgumentOutOfRangeException($"{nameof(destIndex)} must be positive.", nameof(destIndex));
            }
            if (sourceIndex < 0)
            {
                throw new ArgumentOutOfRangeException($"{nameof(sourceIndex)} must be positive.", nameof(sourceIndex));
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException($"{nameof(count)} must be positive.", nameof(count));
            }
            if (destIndex + count > slice.Length)
            {
                throw new ArgumentOutOfRangeException($"{nameof(destIndex)} + {nameof(count)} must be within bounds of slice ({slice.Length}).", nameof(count));
            }
            if (sourceIndex + count > slice.Length)
            {
                throw new ArgumentOutOfRangeException($"{nameof(sourceIndex)} + {nameof(count)} must be within bounds of slice ({slice.Length}).", nameof(count));
            }
            if (count == 0)
            {
                return;
            }
            if (destIndex == sourceIndex)
            {
                return;
            }
            var dataPtr = ((T *)slice.GetUnsafePtr());

            UnsafeUtility.MemCpy(dataPtr + destIndex, dataPtr + sourceIndex, count * sizeof(T));
        }
 /// <summary>
 /// Reads a part of the samples as floats from the sample provider.
 /// </summary>
 /// <param name="destination">The destination buffer that decoded samples are written to.</param>
 /// <returns>The number of samples that could be read. Will be less than the destination size when the end of the sound is reached.</returns>
 public int Read(NativeSlice <float> destination)
 {
     CheckValidAndThrow();
     return(DSPSampleProviderInternal.Internal_ReadFloatFromSampleProviderById(
                ProviderHandle, destination.GetUnsafePtr(),
                destination.Length));
 }
 public unsafe void Execute()
 {
     if (!AddImage(database, validator, image.GetUnsafePtr(), format, width, height, physicalWidth, ref managedReferenceImage))
     {
         managedReferenceImage.Dispose();
     }
 }
Ejemplo n.º 5
0
    static unsafe void GatherExtraStats(NativeSlice <byte> sendBuffer, NativeSlice <byte> sharedBuffer, long timestamp, ref int usedCount, ref int oldestAge, ref int maxRtt, ref int maxProcessingTime)
    {
        var ptr    = (byte *)sendBuffer.GetUnsafePtr();
        var ctx    = (ReliableUtility.Context *)ptr;
        var shared = (ReliableUtility.SharedContext *)sharedBuffer.GetUnsafePtr();

        for (int i = 0; i < shared->WindowSize; i++)
        {
            var seqId = (int *)(ptr + ctx->IndexPtrOffset + i * ctx->IndexStride);
            if (*seqId != -1)
            {
                usedCount++;
                var packetInfo = ReliableUtility.GetPacketInformation(sendBuffer, *seqId);
                oldestAge = Math.Max(oldestAge, (int)(timestamp - packetInfo->SendTime));
            }

            var timingData = ReliableUtility.GetLocalPacketTimer(sharedBuffer, (ushort)i);
            if (timingData->SentTime > 0 && timingData->ReceiveTime > 0)
            {
                maxRtt = Math.Max(maxRtt, (int)(timingData->ReceiveTime - timingData->SentTime - timingData->ProcessingTime));
            }

            maxProcessingTime = Math.Max(maxProcessingTime, timingData->ProcessingTime);
        }
    }
Ejemplo n.º 6
0
        public static unsafe SharedContext InitializeContext(NativeSlice <byte> sharedBuffer, NativeSlice <byte> sendBuffer, NativeSlice <byte> recvBuffer, Parameters param)
        {
            InitializeProcessContext(sendBuffer, param);
            InitializeProcessContext(recvBuffer, param);

            SharedContext *notifier = (SharedContext *)sharedBuffer.GetUnsafePtr();

            *notifier = new SharedContext
            {
                WindowSize  = param.WindowSize,
                SentPackets = new SequenceBufferContext {
                    Acked = NullEntry
                },
                MinimumResendTime = DefaultMinimumResendTime,
                ReceivedPackets   = new SequenceBufferContext {
                    Sequence = NullEntry
                },
                RttInfo = new RTTInfo {
                    SmoothedVariance = 5, SmoothedRtt = 50, ResendTimeout = 50, LastRtt = 50
                },
                TimerDataOffset       = UnsafeUtility.SizeOf <SharedContext>(),
                TimerDataStride       = UnsafeUtility.SizeOf <PacketTimers>(),
                RemoteTimerDataOffset = UnsafeUtility.SizeOf <SharedContext>() + UnsafeUtility.SizeOf <PacketTimers>() * param.WindowSize,
                RemoteTimerDataStride = UnsafeUtility.SizeOf <PacketTimers>()
            };
            return(*notifier);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Write packet, packet header and tracking information to the given buffer space. This buffer
        /// should contain the reliability Context at the front, that contains the capacity of the buffer
        /// and pointer offsets needed to find the slots we can copy the packet to.
        /// </summary>
        /// <param name="self">Buffer space where we can store packets.</param>
        /// <param name="sequence">The sequence ID of the packet, this is used to find a slot inside the buffer.</param>
        /// <param name="header">The packet header which we'll store with the packet payload.</param>
        /// <param name="data">The packet data which we're storing.</param>
        /// <exception cref="OverflowException"></exception>
        public static unsafe void SetHeaderAndPacket(NativeSlice <byte> self, int sequence, PacketHeader header, InboundBufferVec data, long timestamp)
        {
            byte *   ptr       = (byte *)self.GetUnsafePtr();
            Context *ctx       = (Context *)ptr;
            int      totalSize = data.buffer1.Length + data.buffer2.Length;

            if (totalSize > ctx->DataStride)
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            { throw new OverflowException(); }
#else
            { return; }
#endif
            var index = sequence % ctx->Capacity;

            PacketInformation *info = GetPacketInformation(self, sequence);
            info->SequenceId = sequence;
            info->Size       = totalSize;
            info->SendTime   = timestamp;

            Packet *packet = GetPacket(self, sequence);
            packet->Header = header;
            var   offset  = (ctx->DataPtrOffset + (index * ctx->DataStride)) + UnsafeUtility.SizeOf <PacketHeader>();
            void *dataPtr = (ptr + offset);

            if (data.buffer1.Length > 0)
            {
                UnsafeUtility.MemCpy(dataPtr, data.buffer1.GetUnsafeReadOnlyPtr(), data.buffer1.Length);
            }
            if (data.buffer2.Length > 0)
            {
                UnsafeUtility.MemCpy(&dataPtr + data.buffer1.Length, data.buffer2.GetUnsafeReadOnlyPtr(), data.buffer2.Length);
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// バッファをNativeSliceへと書き込む
 /// </summary>
 public unsafe void CopyToNativeSlice <T>(NativeSlice <T> destArray) where T : unmanaged
 {
     fixed(byte *byteArray = Bytes.Array)
     {
         UnsafeUtility.MemCpy((T *)destArray.GetUnsafePtr(), byteArray + Bytes.Offset, Bytes.Count);
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Sends a message using the reliable pipeline, queues message if inflight packet limit is reached.
        /// </summary>
        private unsafe void sendReliableMessage(byte[] msg)
        {
            //DataStreamWriter is needed to send data
            //using statement makes sure DataStreamWriter memory is disposed
            using (var writer = new DataStreamWriter(msg.Length, Allocator.Temp))
            {
                writer.Write(msg); //Write msg byte data

                //Below code copied from documentation here: https://github.com/Unity-Technologies/multiplayer/blob/master/com.unity.transport/Documentation~/pipelines-usage.md

                // Get a reference to the internal state or shared context of the reliability
                NativeSlice <byte> tmpReceiveBuffer     = default;
                NativeSlice <byte> tmpSendBuffer        = default;
                NativeSlice <byte> serverReliableBuffer = default;
                networkDriver.GetPipelineBuffers(typeof(ReliableSequencedPipelineStage), connectionToServer, ref tmpReceiveBuffer, ref tmpSendBuffer, ref serverReliableBuffer);
                var serverReliableCtx = (ReliableUtility.SharedContext *)serverReliableBuffer.GetUnsafePtr();

                connectionToServer.Send(networkDriver, reliablePipeline, writer); //Send msg data to server

                // Failed to send with reliability, error code will be ReliableUtility.ErrorCodes.OutgoingQueueIsFull if no buffer space is left to store the packet
                if (serverReliableCtx->errorCode != 0)
                {
                    messageQueue.Enqueue(new QueuedMessage(msg, true)); //Requeue message
                }
            }
        }
 public static unsafe void NativeInject <T, U>(this List <T> list, NativeSlice <U> nativeSlice)
     where T : struct
     where U : struct
 {
     CheckSameDataType <T, U>();
     NativeInject(list, 0, nativeSlice.GetUnsafePtr(), 0, nativeSlice.Length);
 }
        public unsafe static void ClosePaintElement(VisualElement ve, UIRStylePainter.ClosingInfo closingInfo, RenderChain renderChain, ref ChainBuilderStats stats)
        {
            if (closingInfo.clipperRegisterIndices.Length > 0)
            {
                NativeSlice <Vertex> verts   = new NativeSlice <Vertex>();
                NativeSlice <UInt16> indices = new NativeSlice <UInt16>();
                UInt16 indexOffset           = 0;

                // Due to device Update limitations, we cannot share the vertices of the registration mesh. It would be great
                // if we can just point winding-flipped indices towards the same vertices as the registration mesh.
                // For now, we duplicate the registration mesh entirely, wasting a bit of vertex memory
                UpdateOrAllocate(ref ve.renderChainData.closingData, closingInfo.clipperRegisterVertices.Length, closingInfo.clipperRegisterIndices.Length, renderChain.device, out verts, out indices, out indexOffset, ref stats);
                var job = new CopyClosingMeshJobData
                {
                    vertSrc     = (IntPtr)closingInfo.clipperRegisterVertices.GetUnsafePtr(),
                    vertDst     = (IntPtr)verts.GetUnsafePtr(),
                    vertCount   = verts.Length,
                    indexSrc    = (IntPtr)closingInfo.clipperRegisterIndices.GetUnsafePtr(),
                    indexDst    = (IntPtr)indices.GetUnsafePtr(),
                    indexCount  = indices.Length,
                    indexOffset = indexOffset - closingInfo.clipperRegisterIndexOffset
                };
                renderChain.jobManager.Add(ref job);
                closingInfo.clipUnregisterDrawCommand.mesh       = ve.renderChainData.closingData;
                closingInfo.clipUnregisterDrawCommand.indexCount = indices.Length;
            }
        }
Ejemplo n.º 12
0
        public static unsafe PacketInformation *GetPacketInformation(NativeSlice <byte> self, int sequence)
        {
            byte *   ptr   = (byte *)self.GetUnsafePtr();
            Context *ctx   = (Context *)ptr;
            var      index = sequence % ctx->Capacity;

            return((PacketInformation *)((ptr + ctx->IndexPtrOffset) + (index * ctx->IndexStride)));
        }
Ejemplo n.º 13
0
        static unsafe int GetIndex(NativeSlice <byte> self, int index)
        {
            byte *   ptr = (byte *)self.GetUnsafePtr();
            Context *ctx = (Context *)ptr;

            int *value = (int *)((ptr + ctx->IndexPtrOffset) + (index * ctx->IndexStride));

            return(*value);
        }
Ejemplo n.º 14
0
        static unsafe void SetIndex(NativeSlice <byte> self, int index, int sequence)
        {
            byte *   ptr = (byte *)self.GetUnsafePtr();
            Context *ctx = (Context *)ptr;

            int *value = (int *)((ptr + ctx->IndexPtrOffset) + (index * ctx->IndexStride));

            *value = sequence;
        }
        public static unsafe void Release(NativeSlice <byte> self, int start_sequence, int count)
        {
            Context *ctx = (Context *)self.GetUnsafePtr();

            for (int i = 0; i < count; i++)
            {
                SetIndex(self, (start_sequence + i) % ctx->Capacity, NullEntry);
            }
        }
Ejemplo n.º 16
0
        static unsafe int CurrentResendTime(NativeSlice <byte> sharedBuffer)
        {
            var sharedCtx = (SharedContext *)sharedBuffer.GetUnsafePtr();

            if (sharedCtx->RttInfo.ResendTimeout > MaximumResendTime)
            {
                return(MaximumResendTime);
            }
            return(Math.Max(sharedCtx->RttInfo.ResendTimeout, sharedCtx->MinimumResendTime));
        }
 /// <summary>
 /// Reads a part of the samples as bytes in the specified output format from the sample provider.
 /// </summary>
 /// <param name="destination">The destination buffer that decoded samples are written to.</param>
 /// <param name="format">The destination format that the samples are decoded to.</param>
 /// <returns>The number of samples that could be read. Will be less than the destination size when the end of the sound is reached.</returns>
 public int Read(NativeSlice <byte> destination, NativeFormatType format)
 {
     CheckValidAndThrow();
     // Not doing any format/size checks here. byte is the only valid choice for 8-bits,
     // 24-bits as well as big-endian float. Users may have reasons to want 16-bit samples
     // carried via a buffer-of-bytes, so we're being totally flexible here.
     return(DSPSampleProviderInternal.Internal_ReadUInt8FromSampleProviderById(
                ProviderHandle, (int)format, destination.GetUnsafePtr(),
                destination.Length));
 }
        public unsafe int GetPathResult(NativeSlice <PolygonId> path)
        {
            AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);

            if (!HasNodePool(m_NavMeshQuery))
            {
                throw new InvalidOperationException(k_NoBufferAllocatedErrorMessage);
            }
            return(GetPathResult(m_NavMeshQuery, path.GetUnsafePtr(), path.Length));
        }
        public unsafe void MoveLocationsInSameAreas(NativeSlice <NavMeshLocation> locations, NativeSlice <Vector3> targets, int areaMask = NavMesh.AllAreas)
        {
            if (locations.Length != targets.Length)
            {
                throw new ArgumentException("locations.Length and targets.Length must be equal");
            }

            AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
            MoveLocationsInSameAreas(m_NavMeshQuery, locations.GetUnsafePtr(), targets.GetUnsafeReadOnlyPtr(), locations.Length, areaMask);
        }
Ejemplo n.º 20
0
        public static unsafe Packet *GetPacket(NativeSlice <byte> self, int sequence)
        {
            byte *   ptr   = (byte *)self.GetUnsafePtr();
            Context *ctx   = (Context *)ptr;
            var      index = sequence % ctx->Capacity;

            var offset = ctx->DataPtrOffset + (index * ctx->DataStride);

            return((Packet *)(ptr + offset));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Constructs an ARCollaborationData from a <c>NativeSlice</c> of <c>byte</c>s.
        /// Check <see cref="valid"/> after construction to ensure <paramref name="bytes"/> was successfully deserialized.
        /// </summary>
        /// <param name="bytes">An array of <c>byte</c>s to convert to <see cref="ARCollaborationData"/>.</param>
        /// <exception cref="System.ArgumentException">Thrown if <paramref name="bytes"/> does not refer to valid data.</exception>
        /// <seealso cref="ToSerialized"/>
        public unsafe ARCollaborationData(NativeSlice <byte> bytes)
        {
            void *ptr = bytes.GetUnsafePtr();

            if ((ptr == null) || (bytes.Length == 0))
            {
                throw new ArgumentException("Invalid NativeSlice", nameof(bytes));
            }

            m_NativePtr = ConstructUnchecked(ptr, bytes.Length);
        }
Ejemplo n.º 22
0
 public void InitializeConnection(NativeSlice <byte> sendProcessBuffer, NativeSlice <byte> recvProcessBuffer, NativeSlice <byte> sharedProcessBuffer)
 {
     unsafe
     {
         if (recvProcessBuffer.Length > 0)
         {
             // The receive processing buffer contains the current sequence ID, initialize it to -1 as it will be incremented when used.
             *(int *)recvProcessBuffer.GetUnsafePtr() = -1;
         }
     }
 }
Ejemplo n.º 23
0
            public unsafe void Execute()
            {
                bool success = UnityARKit_ImageDatabase_AddImage(database, image.GetUnsafePtr(), format, width, height, physicalWidth, ref managedReferenceImage);

                if (!success)
                {
                    managedReferenceImage.Dispose();
                }

                UnityARKit_CFRelease(database);
            }
Ejemplo n.º 24
0
        public void MoveLocationsInSameAreas(NativeSlice <NavMeshLocation> locations, NativeSlice <Vector3> targets, int areaMask = -1)
        {
            bool flag = locations.Length != targets.Length;

            if (flag)
            {
                throw new ArgumentException("locations.Length and targets.Length must be equal");
            }
            AtomicSafetyHandle.CheckReadAndThrow(this.m_Safety);
            NavMeshQuery.MoveLocationsInSameAreas(this.m_NavMeshQuery, locations.GetUnsafePtr <NavMeshLocation>(), targets.GetUnsafeReadOnlyPtr <Vector3>(), locations.Length, areaMask);
        }
Ejemplo n.º 25
0
        public int GetPathResult(NativeSlice <PolygonId> path)
        {
            AtomicSafetyHandle.CheckWriteAndThrow(this.m_Safety);
            bool flag = !NavMeshQuery.HasNodePool(this.m_NavMeshQuery);

            if (flag)
            {
                throw new InvalidOperationException("This query has no buffer allocated for pathfinding operations. Create a different NavMeshQuery with an explicit node pool size.");
            }
            return(NavMeshQuery.GetPathResult(this.m_NavMeshQuery, path.GetUnsafePtr <PolygonId>(), path.Length));
        }
Ejemplo n.º 26
0
        public unsafe void Execute(int i)
        {
            var   spriteSkin        = spriteSkinData[i];
            byte *deformedPosOffset = (byte *)vertices.GetUnsafePtr();
            NativeSlice <float3> deformableVerticesFloat3 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <float3>(deformedPosOffset + spriteSkin.deformVerticesStartPos, spriteSkin.spriteVertexStreamSize, spriteSkin.spriteVertexCount);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref deformableVerticesFloat3, NativeSliceUnsafeUtility.GetAtomicSafetyHandle(vertices));
#endif

            bounds[i] = SpriteSkinUtility.CalculateSpriteSkinBounds(deformableVerticesFloat3);
        }
        static unsafe void PrepareNudgeVertices(VisualElement ve, UIRenderDevice device, MeshHandle mesh, out IntPtr src, out IntPtr dst, out int count)
        {
            int vertCount = (int)mesh.allocVerts.size;
            NativeSlice <Vertex> oldVerts = mesh.allocPage.vertices.cpuData.Slice((int)mesh.allocVerts.start, vertCount);
            NativeSlice <Vertex> newVerts;

            device.Update(mesh, (uint)vertCount, out newVerts);

            src   = (IntPtr)oldVerts.GetUnsafePtr();
            dst   = (IntPtr)newVerts.GetUnsafePtr();
            count = vertCount;
        }
Ejemplo n.º 28
0
        public unsafe static T DeserializeUnmanaged <T>(ref NativeSlice <byte> buffer) where T : unmanaged
        {
            int  structSize = UnsafeUtility.SizeOf <T>();
            long ptr        = (long)buffer.GetUnsafePtr();
            long size       = buffer.Length;

            long addr = ptr + size - structSize;

            var data = UnsafeUtility.ReadArrayElement <T>((void *)addr, 0);

            return(data);
        }
        public static void CopyFrom <T>(this NativeSlice <T> dstArray, int dstIndex, ref BlobArray <T> srcArray, int srcIndex, int srcCount) where T : unmanaged
        {
            CheckLengthInRange(srcCount, srcArray.Length);
            CheckLengthInRange(srcCount, dstArray.Length);
            CheckIndexInRangeInc(dstIndex, dstArray.Length - srcCount);
            CheckIndexInRangeInc(srcIndex, srcArray.Length - srcCount);

            var srcPtr = (T *)srcArray.GetUnsafePtr() + srcIndex;
            var dstPtr = (T *)dstArray.GetUnsafePtr() + dstIndex;

            UnsafeUtility.MemCpy(dstPtr, srcPtr, srcCount * UnsafeUtility.SizeOf <T>());
        }
Ejemplo n.º 30
0
        public static unsafe void SetMinimumResendTime(int value, LocalNetworkDriver driver,
                                                       NetworkPipeline pipeline, int stageId, NetworkConnection con)
        {
            NativeSlice <byte> receiveBuffer = default(NativeSlice <byte>);
            NativeSlice <byte> sendBuffer    = default(NativeSlice <byte>);
            NativeSlice <byte> sharedBuffer  = default(NativeSlice <byte>);

            driver.GetPipelineBuffers(pipeline, stageId, con, ref receiveBuffer, ref sendBuffer, ref sharedBuffer);
            var sharedCtx = (ReliableUtility.SharedContext *)sharedBuffer.GetUnsafePtr();

            sharedCtx->MinimumResendTime = value;
        }