public ChunkedMemoryStream(int chunkSize, Allocator allocator)
        {
            if (chunkSize <= 0)
            throw new ArgumentOutOfRangeException("chunkSize", chunkSize, "must be non-zero positive number");
              if (allocator == null)
            throw new ArgumentNullException("allocator");

              this.chain = new ChunkChain(chunkSize, allocator);
        }
Example #2
0
 public void AddRange <TValue, TNode>(TValue *copySource, int length, out TNode *page, out int start, Allocator allocator)
     where TValue : unmanaged
     where TNode : unmanaged
 {
     AddRange(copySource, length, out var _page, out start, allocator);
     page = (TNode *)_page;
 }
Example #3
0
 public void Add <TValue, TNode>(ref TValue copySource, out TNode *page, out int index, Allocator allocator)
     where TValue : unmanaged
     where TNode : unmanaged, ILinkedListNode <TValue, TNode>
 {
     Add(ref copySource, out var _page, out index, allocator);
     page = (TNode *)_page;
 }
        /// <summary>
        /// Implementation for the <c>IRaycaster</c> interface. Raycasts against every point cloud.
        /// </summary>
        /// <param name="rayInSessionSpace">A <c>Ray</c>, in session space.</param>
        /// <param name="trackableTypeMask">The type of trackables to raycast against.
        /// If <c>TrackableType.FeaturePoint</c> is not set, this method returns an empty array.</param>
        /// <param name="allocator">The allocator to use for the returned <c>NativeArray</c>.</param>
        /// <returns>A new <c>NativeArray</c>, allocated using <paramref name="allocator"/>, containing
        /// a list of <c>XRRaycastHit</c>s of points hit by the raycast.</returns>
        public NativeArray <XRRaycastHit> Raycast(
            Ray rayInSessionSpace,
            TrackableType trackableTypeMask,
            Allocator allocator)
        {
            if ((trackableTypeMask & TrackableType.FeaturePoint) == TrackableType.None)
            {
                return(new NativeArray <XRRaycastHit>(0, allocator));
            }

            // TODO: Expose this as a property
            float raycastAngleInRadians = Mathf.Deg2Rad * 5f;

            var trackableCollection = trackables;

            var allHits = new NativeArray <XRRaycastHit>(0, allocator);

            foreach (var pointCloud in trackableCollection)
            {
                var sessionSpacePose = new Pose(
                    pointCloud.transform.localPosition,
                    pointCloud.transform.localRotation);

                var invRotation = Quaternion.Inverse(sessionSpacePose.rotation);

                // Get the ray in "point cloud space", i.e., relative to the point cloud's local transform
                var ray = new Ray(
                    invRotation * (rayInSessionSpace.origin - sessionSpacePose.position),
                    invRotation * rayInSessionSpace.direction);

                // Collect the points in the point cloud
                var points = pointCloud.positions;

                // Perform the raycast against each point
                var infos      = new NativeArray <PointCloudRaycastInfo>(points.Length, Allocator.TempJob);
                var raycastJob = new PointCloudRaycastJob
                {
                    points  = points,
                    ray     = ray,
                    infoOut = infos
                };
                var raycastHandle = raycastJob.Schedule(infos.Length, 1);

                // Collect the hits
                using (var hitBuffer = new NativeArray <XRRaycastHit>(infos.Length, Allocator.TempJob))
                {
                    var collectResultsJob = new PointCloudRaycastCollectResultsJob
                    {
                        points          = points,
                        infos           = infos,
                        hits            = hitBuffer,
                        cosineThreshold = Mathf.Cos(raycastAngleInRadians * .5f),
                        pose            = sessionSpacePose,
                        trackableId     = pointCloud.trackableId,
                        count           = new NativeArray <int>(1, Allocator.TempJob)
                    };
                    var collectResultsHandle = collectResultsJob.Schedule(raycastHandle);

                    // Wait for it to finish
                    collectResultsHandle.Complete();

                    // Read out the count
                    var count = collectResultsJob.count[0];

                    // Done with native arrays
                    infos.Dispose();
                    points.Dispose();
                    collectResultsJob.count.Dispose();

                    // Copy out the results
                    Append(ref allHits, hitBuffer, count, allocator);
                }
            }

            return(allHits);
        }
 public NativeArray <T> ToComponentDataArray <T>(Allocator allocator)
     where T : struct, IComponentData
 {
     throw new NotImplementedException();
 }
 public NativeArray <Entity> ToEntityArray(Allocator allocator, out JobHandle jobhandle)
 {
     throw new NotImplementedException();
 }
 public unsafe BuildChangeSetTask(WorldState beforeState, WorldState afterState, TypeInfoStream typeInfoStream, Allocator allocator)
 {
     m_BeforeState                = beforeState;
     m_AfterState                 = afterState;
     m_TypeInfoStream             = typeInfoStream;
     m_CreatedEntities            = new NativeList <EntityInChunkWithComponent <EntityGuid> >(1, allocator);
     m_ModifiedEntities           = new NativeList <ModifiedEntity>(1, allocator);
     m_DestroyedEntities          = new NativeList <EntityInChunkWithComponent <EntityGuid> >(1, allocator);
     m_PackedEntities             = new PackedCollection <EntityGuid>(1, allocator);
     m_PackedStableTypeHashes     = new PackedCollection <ComponentTypeHash>(1, allocator);
     m_AddComponents              = new NativeList <PackedComponent>(1, allocator);
     m_RemoveComponents           = new NativeList <PackedComponent>(1, allocator);
     m_ComponentDataStream        = new ComponentDataStream(allocator);
     m_EntityReference            = new NativeList <EntityReferenceChange>(1, allocator);
     m_LinkedEntityGroupAdditions = new NativeList <LinkedEntityGroupChange>(1, allocator);
     m_LinkedEntityGroupRemovals  = new NativeList <LinkedEntityGroupChange>(1, allocator);
     m_BeforeEntityToEntityGuid   = new EntityToComponentMap <EntityGuid>(m_BeforeState.EntityComponentStore, allocator);
     m_AfterEntityToEntityGuid    = new EntityToComponentMap <EntityGuid>(m_AfterState.EntityComponentStore, allocator);
     IsCreated = true;
 }
Example #8
0
 private static void* __CopyValue(Allocator.__Internal native)
 {
     var ret = Marshal.AllocHGlobal(0);
     *(Allocator.__Internal*) ret = native;
     return ret.ToPointer();
 }
Example #9
0
        public unsafe static void DeallocateQueue(NativeQueueData *data, NativeQueueBlockPoolData *pool, Allocator allocation)
        {
            NativeQueueBlockHeader *firstBlock = (NativeQueueBlockHeader *)data->m_FirstBlock;

            while (firstBlock != null)
            {
                NativeQueueBlockHeader *next = firstBlock->m_NextBlock;
                pool->FreeBlock(firstBlock);
                firstBlock = next;
            }

            UnsafeUtility.Free(data, allocation);
        }
Example #10
0
 /// <summary>
 /// Constructs a new container with the specified initial capacity and type of memory allocation.
 /// </summary>
 /// <param name="capacity">The initial capacity of the container. If the list grows larger than its capacity,
 /// the internal array is copied to a new, larger array.</param>
 /// <param name="allocator">A member of the
 /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
 public NativeMultiHashMap(int capacity, Allocator allocator)
     : this(capacity, allocator, 2)
 {
 }
Example #11
0
 /// <summary>
 /// Returns arrays populated with keys and values.
 /// </summary>
 /// <param name="allocator">A member of the
 /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
 /// <returns>Array of keys-values.</returns>
 public NativeKeyValueArrays <TKey, TValue> GetKeyValueArrays(Allocator allocator)
 {
     CheckRead();
     return(m_MultiHashMapData.GetKeyValueArrays(allocator));
 }
Example #12
0
 /// <summary>
 /// Returns array populated with values.
 /// </summary>
 /// <param name="allocator">A member of the
 /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
 /// <returns>Array of values.</returns>
 public NativeArray <TValue> GetValueArray(Allocator allocator)
 {
     CheckRead();
     return(m_MultiHashMapData.GetValueArray(allocator));
 }
Example #13
0
 public NativeArray(NativeArray <T> array, Allocator allocator)
 {
     Allocate(array.Length, allocator, out this);
     Copy(array, this);
 }
Example #14
0
        /// Internal method used typically by other systems to provide a view on them.
        /// The caller is still the owner of the data.
        public static unsafe NativeArray <T> ConvertExistingDataToNativeArray <T>(void *dataPointer, int length, Allocator allocator) where T : struct
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0");
            }

            NativeArray <T> .IsUnmanagedAndThrow();

            var totalSize = UnsafeUtility.SizeOf <T>() * (long)length;

            // Make sure we cannot allocate more than int.MaxValue (2,147,483,647 bytes)
            // because the underlying UnsafeUtility.Malloc is expecting a int.
            // TODO: change UnsafeUtility.Malloc to accept a UIntPtr length instead to match C++ API
            if (totalSize > int.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(length), $"Length * sizeof(T) cannot exceed {int.MaxValue} bytes");
            }

            var newArray = new NativeArray <T>
            {
                m_Buffer         = dataPointer,
                m_Length         = length,
                m_AllocatorLabel = allocator,

                m_MinIndex = 0,
                m_MaxIndex = length - 1,
            };

            return(newArray);
        }
Example #15
0
 public ChunkedMemoryStream(Allocator allocator)
     : this(DefaultChunkSize, allocator)
 {
 }
Example #16
0
 public ByteBlockPool(Allocator allocator, bool trackAllocations)
 {
     InitBlock();
     this.allocator = allocator;
     this.trackAllocations = trackAllocations;
 }
Example #17
0
 /// <summary>
 /// Copies stream data into NativeArray.
 /// </summary>
 /// <param name="allocator">A member of the
 /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
 /// <returns>A new NativeArray, allocated with the given strategy and wrapping the stream data.</returns>
 /// <remarks>The array is a copy of stream data.</remarks>
 public NativeArray <T> ToNativeArray <T>(Allocator allocator) where T : struct
 {
     CheckReadAccess();
     return(m_Stream.ToNativeArray <T>(allocator));
 }
Example #18
0
 /// <summary>
 /// Creates a new <seealso cref="IntBlockPool"/> with the given <seealso cref="Allocator"/>. </summary>
 /// <seealso cref= IntBlockPool#nextBuffer() </seealso>
 public IntBlockPool(Allocator allocator)
 {
     this.allocator = allocator;
 }
Example #19
0
 /// <summary>
 /// Constructs a new NativeStream using the specified type of memory allocation.
 /// </summary>
 /// <param name="dependency">All jobs spawned will depend on this JobHandle.</param>
 /// <param name="allocator">A member of the
 /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
 public NativeStream(int foreachCount, Allocator allocator)
 {
     AllocateBlock(out this, allocator);
     m_Stream.AllocateForEach(foreachCount);
 }
 public NativeArray <ArchetypeChunk> CreateArchetypeChunkArray(Allocator allocator)
 {
     throw new NotImplementedException();
 }
Example #21
0
        /// <summary>
        /// Schedule job to construct a new NativeStream using the specified type of memory allocation.
        /// </summary>
        /// <param name="dependency">All jobs spawned will depend on this JobHandle.</param>
        /// <param name="allocator">A member of the
        /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
        public static JobHandle ScheduleConstruct <T>(out NativeStream stream, NativeList <T> forEachCountFromList, JobHandle dependency, Allocator allocator)
            where T : struct
        {
            AllocateBlock(out stream, allocator);
            var jobData = new ConstructJobList <T> {
                List = forEachCountFromList, Container = stream
            };

            return(jobData.Schedule(dependency));
        }
 public NativeArray <Entity> ToEntityArray(Allocator allocator)
 {
     throw new NotImplementedException();
 }
Example #23
0
        /// <summary>
        /// Schedule job to construct a new NativeStream using the specified type of memory allocation.
        /// </summary>
        /// <param name="allocator">A member of the
        /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
        public static JobHandle ScheduleConstruct(out NativeStream stream, NativeArray <int> lengthFromIndex0, JobHandle dependency, Allocator allocator)
        {
            AllocateBlock(out stream, allocator);
            var jobData = new ConstructJob {
                Length = lengthFromIndex0, Container = stream
            };

            return(jobData.Schedule(dependency));
        }
Example #24
0
        /// <summary>
        /// Completes construction of the blob asset and returns a reference to the asset in unmanaged memory.
        /// </summary>
        /// <remarks>Use the <see cref="BlobAssetReference{T}"/> to access the blob asset. When the asset is no longer
        /// needed, call<see cref="BlobAssetReference{T}.Dispose()"/> to destroy the blob asset and free its allocated
        /// memory.</remarks>
        /// <param name="allocator">The type of memory to allocate. Unless the asset has a very short life span, use
        /// <see cref="Allocator.Persistent"/>.</param>
        /// <typeparam name="T">The data type of the struct used to construct the asset's root. Use the same struct type
        /// that you used when calling <see cref="ConstructRoot{T}"/>.</typeparam>
        /// <returns></returns>
        public BlobAssetReference <T> CreateBlobAssetReference <T>(Allocator allocator) where T : struct
        {
            var offsets      = new NativeArray <int>(m_allocations.Length + 1, Allocator.Temp);
            var sortedAllocs = new NativeArray <SortedIndex>(m_allocations.Length, Allocator.Temp);

            offsets[0] = 0;
            for (int i = 0; i < m_allocations.Length; ++i)
            {
                offsets[i + 1]  = offsets[i] + m_allocations[i].size;
                sortedAllocs[i] = new SortedIndex {
                    p = m_allocations[i].p, index = i
                };
            }
            int dataSize = offsets[m_allocations.Length];

            sortedAllocs.Sort();
            var sortedPatches = new NativeArray <SortedIndex>(m_patches.Length, Allocator.Temp);

            for (int i = 0; i < m_patches.Length; ++i)
            {
                sortedPatches[i] = new SortedIndex {
                    p = (byte *)m_patches[i].offsetPtr, index = i
                }
            }
            ;
            sortedPatches.Sort();

            byte *buffer = (byte *)UnsafeUtility.Malloc(sizeof(BlobAssetHeader) + dataSize, 16, allocator);
            byte *data   = buffer + sizeof(BlobAssetHeader);

            for (int i = 0; i < m_allocations.Length; ++i)
            {
                UnsafeUtility.MemCpy(data + offsets[i], m_allocations[i].p, m_allocations[i].size);
            }

            int iAlloc     = 0;
            var allocStart = m_allocations[sortedAllocs[0].index].p;
            var allocEnd   = allocStart + m_allocations[sortedAllocs[0].index].size;

            for (int i = 0; i < m_patches.Length; ++i)
            {
                int  patchIndex = sortedPatches[i].index;
                int *offsetPtr  = (int *)sortedPatches[i].p;

                while (offsetPtr > allocEnd)
                {
                    ++iAlloc;
                    allocStart = m_allocations[sortedAllocs[iAlloc].index].p;
                    allocEnd   = allocStart + m_allocations[sortedAllocs[iAlloc].index].size;
                }

                var patch = m_patches[patchIndex];

                int offsetPtrInData = offsets[sortedAllocs[iAlloc].index] + (int)((byte *)offsetPtr - allocStart);
                int targetPtrInData = offsets[patch.target.allocIndex] + patch.target.offset;

                *(int *)(data + offsetPtrInData) = targetPtrInData - offsetPtrInData;
                if (patch.length != 0)
                {
                    *(int *)(data + offsetPtrInData + 4) = patch.length;
                }
            }

            sortedPatches.Dispose();
            sortedAllocs.Dispose();
            offsets.Dispose();

            BlobAssetHeader *header = (BlobAssetHeader *)buffer;

            *header = new BlobAssetHeader();
            header->Length    = (int)dataSize;
            header->Allocator = allocator;

            // @TODO use 64bit hash
            header->Hash = math.hash(buffer + sizeof(BlobAssetHeader), dataSize);

            BlobAssetReference <T> blobAssetReference;

            blobAssetReference.m_data.m_Align8Union = 0;
            header->ValidationPtr = blobAssetReference.m_data.m_Ptr = buffer + sizeof(BlobAssetHeader);

            return(blobAssetReference);
        }

        void *AllocationToPointer(BlobDataRef blobDataRef)
        {
            return(m_allocations[blobDataRef.allocIndex].p + blobDataRef.offset);
        }

        BlobAllocation EnsureEnoughRoomInChunk(int size, int alignment)
        {
            if (m_currentChunkIndex == -1)
            {
                return(AllocateNewChunk());
            }

            var alloc       = m_allocations[m_currentChunkIndex];
            int startOffset = CollectionHelper.Align(alloc.size, alignment);

            if (startOffset + size > m_chunkSize)
            {
                return(AllocateNewChunk());
            }

            UnsafeUtility.MemClear(alloc.p + alloc.size, startOffset - alloc.size);

            alloc.size = startOffset;
            return(alloc);
        }

        BlobDataRef Allocate(int size, int alignment)
        {
            if (size > m_chunkSize)
            {
                size = CollectionHelper.Align(size, 16);
                var allocIndex = m_allocations.Length;
                var mem        = (byte *)UnsafeUtility.Malloc(size, alignment, m_allocator);
                UnsafeUtility.MemClear(mem, size);
                m_allocations.Add(new BlobAllocation {
                    p = mem, size = size
                });
                return(new BlobDataRef {
                    allocIndex = allocIndex, offset = 0
                });
            }

            BlobAllocation alloc = EnsureEnoughRoomInChunk(size, alignment);

            var offset = alloc.size;

            UnsafeUtility.MemClear(alloc.p + alloc.size, size);
            alloc.size += size;
            m_allocations[m_currentChunkIndex] = alloc;
            return(new BlobDataRef {
                allocIndex = m_currentChunkIndex, offset = offset
            });
        }

        BlobAllocation AllocateNewChunk()
        {
            // align size of last chunk to 16 bytes so chunks can be concatenated without breaking alignment
            if (m_currentChunkIndex != -1)
            {
                var currentAlloc = m_allocations[m_currentChunkIndex];
                currentAlloc.size = CollectionHelper.Align(currentAlloc.size, 16);
                m_allocations[m_currentChunkIndex] = currentAlloc;
            }

            m_currentChunkIndex = m_allocations.Length;
            var alloc = new BlobAllocation {
                p = (byte *)UnsafeUtility.Malloc(m_chunkSize, 16, m_allocator), size = 0
            };

            m_allocations.Add(alloc);
            return(alloc);
        }
Example #25
0
        public EventBatch(EntityManager em, EventDefinition definition, Allocator allocator = Allocator.Persistent) : this()
        {
            var componentType  = ComponentType.FromTypeIndex(definition.ComponentTypeInfo.TypeIndex);
            var bufferType     = ComponentType.FromTypeIndex(definition.BufferTypeInfo.TypeIndex);
            var bufferLinkType = ComponentType.ReadWrite <BufferLink>();

            HasBuffer    = definition.BufferTypeInfo.TypeIndex != 0;
            HasComponent = definition.ComponentTypeInfo.TypeIndex != 0;

            var components = new List <ComponentType>()
            {
                definition.MetaType,
            };

            if (HasComponent)
            {
                components.AddRange(new[] {
                    componentType,
                });
            }

            if (HasBuffer)
            {
                components.AddRange(new[] {
                    bufferType,
                    bufferLinkType,
                });
            }

            Archetype = em.CreateArchetype(components.ToArray());

            var inactiveComponents = new List <ComponentType>(components)
            {
                ComponentType.ReadWrite <Disabled>()
            };

            InactiveArchetype = em.CreateArchetype(inactiveComponents.ToArray());


            Allocator          = allocator;
            ComponentType      = componentType;
            ComponentTypeIndex = definition.ComponentTypeInfo.TypeIndex;
            ComponentTypeSize  = definition.ComponentTypeInfo.SizeInChunk;

            BufferType             = bufferType;
            BufferTypeIndex        = definition.BufferTypeInfo.TypeIndex;
            BufferElementSize      = definition.BufferTypeInfo.ElementSize;
            BufferSizeInChunk      = definition.BufferTypeInfo.SizeInChunk;
            BufferAlignmentInBytes = definition.BufferTypeInfo.AlignmentInBytes;
            BufferLinkTypeIndex    = TypeManager.GetTypeIndex <BufferLink>();

            StartingPoolSize = definition.StartingPoolSize;

            ComponentQueue = new EventQueue(ComponentTypeIndex, ComponentTypeSize, BufferTypeIndex, BufferElementSize, allocator);
            Offsets        = GetChunkOffsets(em, Archetype, definition.MetaType, componentType, bufferType, bufferLinkType);

            ActiveChunks   = new ArchetypeView(Archetype);
            InactiveChunks = new ArchetypeView(InactiveArchetype);

            ActiveArchetypeChunks         = new UnsafeList(Allocator.Persistent);
            ActiveFullArchetypeChunks     = new UnsafeList(Allocator.Persistent);
            ActivePartialArchetypeChunk   = new UnsafeList(Allocator.Persistent);
            InactiveFullArchetypeChunks   = new UnsafeList(Allocator.Persistent);
            InactivePartialArchetypeChunk = new UnsafeList(Allocator.Persistent);

            if (definition.StartingPoolSize > 0)
            {
                CreateInactiveEntities(em, definition.StartingPoolSize);
                UpdateChunkCollections();
            }
        }
Example #26
0
        public void Add <T>(ref T copySource, out ListLinkedListNode *page, out int index, Allocator allocator) where T : unmanaged
        {
            ListLinkedListNode *tryNode;

            if (LastFull == null)
            {
                tryNode = First;
            }
            else
            {
                tryNode = LastFull->Next;
            }
            for (; tryNode != null; tryNode = tryNode->Next)
            {
                if (tryNode->TryAdd(ref copySource, out index))
                {
                    if (tryNode->IsFull)
                    {
                        LastFull = tryNode;
                    }
                    page = tryNode;
                    return;
                }
                UnityEngine.Debug.Log("LAST FULL RENEW");
                LastFull = tryNode;
            }
            page  = ListLinkedListNode.Create <T>(NodeCapacity, allocator);
            index = 0;
            page->GetRef <T>(0) = copySource;
            page->Length        = 1;
            for (tryNode = LastFull; IntPtr.Zero != Interlocked.CompareExchange(ref tryNode->NextNodePtr, new IntPtr(page), IntPtr.Zero); tryNode = tryNode->Next)
            {
                ;
            }
        }
Example #27
0
 public static EventBatch CreateComponentAndBufferBatch <T1, T2>(EntityManager em, ComponentType metaComponent, int startingPoolSize = 0, Allocator allocator = Allocator.Persistent)
     where T1 : struct, IComponentData
     where T2 : struct, IBufferElementData
 {
     return(new EventBatch(em, new EventDefinition
     {
         MetaType = metaComponent,
         StartingPoolSize = startingPoolSize,
         ComponentTypeInfo = TypeManager.GetTypeInfo <T1>(),
         BufferTypeInfo = TypeManager.GetTypeInfo <T2>(),
     }, allocator));
 }
Example #28
0
        public void AddRange <T>(T *copySource, int length, out ListLinkedListNode *page, out int start, Allocator allocator) where T : unmanaged
        {
            ListLinkedListNode *tryNode;

            if (LastFull == null)
            {
                tryNode = First;
            }
            else if (LastFull->NextNodePtr == IntPtr.Zero)
            {
                tryNode = LastFull;
                goto ADDNEWPAGE;
            }
            else
            {
                tryNode = LastFull->Next;
            }
            if (length > NodeCapacity)
            {
                NodeCapacity = length;
                goto ADDNEWPAGE;
            }
            while (true)
            {
                if (tryNode->TryAdd(copySource, length, out start))
                {
                    if (tryNode->IsFull && LastFull->Next == tryNode)
                    {
                        LastFull = tryNode;
                    }
                    page = tryNode;
                    return;
                }
                if (tryNode->NextNodePtr == IntPtr.Zero)
                {
                    goto ADDNEWPAGE;
                }
                tryNode = tryNode->Next;
            }
ADDNEWPAGE:
            page  = ListLinkedListNode.Create <T>(NodeCapacity, allocator);
            start = 0;
            UnsafeUtility.MemCpy(page->Values, copySource, sizeof(T) * length);
            while (IntPtr.Zero != Interlocked.CompareExchange(ref tryNode->NextNodePtr, new IntPtr(page), IntPtr.Zero))
            {
                tryNode = tryNode->Next;
            }
        }
Example #29
0
 /// <summary>
 /// Create a copy of the given native array
 /// </summary>
 ///
 /// <param name="array">
 /// Native array to copy
 /// </param>
 ///
 /// <param name="allocator">
 /// Allocator to allocate native memory with. Must be valid as defined
 /// by <see cref="UnsafeUtility.IsValidAllocator"/>.
 /// </param>
 public NativeArray2D(NativeArray2D <T> array, Allocator allocator)
 {
     Allocate(array.Length0, array.Length1, allocator, out this);
     Copy(array, this);
 }
Example #30
0
            public ChunkChain(int chunkSize, Allocator allocator)
            {
                this.chunkSize = chunkSize;
                this.allocator = allocator;
                this.firstChunk = allocator(chunkSize);

                this.currentChunk = firstChunk;

                currentChunkOffset = 0;
                currentChunkRemainder = chunkSize;
            }
        /// <summary>
        /// Get the face classifications for the given mesh ID.
        /// </summary>
        /// <param name="subsystem">The meshing subsystem.</param>
        /// <param name="meshId">The trackable ID representing the mesh.</param>
        /// <param name="allocator">The memory allocator type to use in allocating the native array memory.</param>
        /// <returns>
        /// An array of mesh classifications, one for each face in the mesh.
        /// </returns>
        public static unsafe NativeArray <ARMeshClassification> GetFaceClassifications(this XRMeshSubsystem subsystem, TrackableId meshId, Allocator allocator)
        {
            void *classifications = NativeApi.UnityARKit_MeshProvider_AcquireClassifications(meshId, out int numClassifications);

            try
            {
                if (classifications == null)
                {
                    numClassifications = 0;
                }

                var meshClassifications = new NativeArray <ARMeshClassification>(numClassifications, allocator);
                if (classifications != null)
                {
                    NativeArray <ARMeshClassification> tmp = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <ARMeshClassification>(classifications, numClassifications, Allocator.None);
                    meshClassifications.CopyFrom(tmp);
                }

                return(meshClassifications);
            }
            finally
            {
                NativeApi.UnityARKit_MeshProvider_ReleaseClassifications(classifications);
            }
        }
Example #32
0
        public static WorkingTexture ToWorkingTexture(this Texture2D texture, Allocator allocator)
        {
            var wt = new WorkingTexture(allocator, texture);

            return(wt);
        }
Example #33
0
 public PriorityQueue(int intialCapacity, Allocator allocator = Allocator.Persistent)
 {
     Assert.IsTrue(intialCapacity > 1, "capacity must be larger than 1");
     _data = new List <T>(intialCapacity, allocator);
     Clear();
 }
Example #34
0
 public static Allocator __CreateInstance(Allocator.__Internal native, bool skipVTables = false)
 {
     return new Allocator(native, skipVTables);
 }
Example #35
0
        /// <summary>
        /// Creates a NativeArray with all the chunks in a given archetype filtered by the provided EntityQueryFilter.
        /// This function will not sync the needed types in the EntityQueryFilter so they have to be synced manually before calling this function.
        /// </summary>
        /// <param name="matchingArchetypes">List of matching archetypes.</param>
        /// <param name="allocator">Allocator to use for the array.</param>
        /// <param name="jobHandle">Handle to the GatherChunks job used to fill the output array.</param>
        /// <param name="filter">Filter used to filter the resulting chunks</param>
        /// <param name="dependsOn">All jobs spawned will depend on this JobHandle</param>
        /// <returns>NativeArray of all the chunks in the matchingArchetypes list.</returns>
        public static NativeArray <ArchetypeChunk> CreateArchetypeChunkArrayWithoutSync(UnsafeMatchingArchetypePtrList matchingArchetypes,
                                                                                        Allocator allocator, out JobHandle jobHandle, ref EntityQueryFilter filter,
                                                                                        JobHandle dependsOn = default(JobHandle))
        {
            var archetypeCount = matchingArchetypes.Length;

            var offsets =
                new NativeArray <int>(archetypeCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            var chunkCount = 0;

            {
                for (int i = 0; i < matchingArchetypes.Length; ++i)
                {
                    var archetype = matchingArchetypes.Ptr[i]->Archetype;
                    offsets[i]  = chunkCount;
                    chunkCount += archetype->Chunks.Count;
                }
            }

            if (!filter.RequiresMatchesFilter)
            {
                var chunks          = new NativeArray <ArchetypeChunk>(chunkCount, allocator, NativeArrayOptions.UninitializedMemory);
                var gatherChunksJob = new GatherChunks
                {
                    MatchingArchetypes   = matchingArchetypes.Ptr,
                    entityComponentStore = matchingArchetypes.entityComponentStore,
                    Offsets = offsets,
                    Chunks  = chunks
                };
                jobHandle = gatherChunksJob.Schedule(archetypeCount, 1, dependsOn);

                return(chunks);
            }
            else
            {
                var filteredCounts  = new NativeArray <int>(archetypeCount + 1, Allocator.TempJob);
                var sparseChunks    = new NativeArray <ArchetypeChunk>(chunkCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
                var gatherChunksJob = new GatherChunksWithFiltering
                {
                    MatchingArchetypes   = matchingArchetypes.Ptr,
                    Filter               = filter,
                    Offsets              = offsets,
                    FilteredCounts       = filteredCounts,
                    SparseChunks         = sparseChunks,
                    entityComponentStore = matchingArchetypes.entityComponentStore
                };
                gatherChunksJob.Schedule(archetypeCount, 1, dependsOn).Complete();

                // accumulated filtered counts: filteredCounts[i] becomes the destination offset
                int totalChunks = 0;
                for (int i = 0; i < archetypeCount; ++i)
                {
                    int currentCount = filteredCounts[i];
                    filteredCounts[i] = totalChunks;
                    totalChunks      += currentCount;
                }
                filteredCounts[archetypeCount] = totalChunks;

                var joinedChunks = new NativeArray <ArchetypeChunk>(totalChunks, allocator, NativeArrayOptions.UninitializedMemory);

                jobHandle = new JoinChunksJob
                {
                    DestinationOffsets = filteredCounts,
                    SparseChunks       = sparseChunks,
                    Offsets            = offsets,
                    JoinedChunks       = joinedChunks
                }.Schedule(archetypeCount, 1);

                return(joinedChunks);
            }
        }
Example #36
0
 private Allocator(Allocator.__Internal native, bool skipVTables = false)
     : this(__CopyValue(native), skipVTables)
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
 public NativeArray <ArchetypeChunk> CreateArchetypeChunkArray(Allocator allocator, out JobHandle jobhandle)
 {
     throw new NotImplementedException();
 }
Example #38
0
 public ByteBlockPool(Allocator allocator)
 {
     this.allocator = allocator;
 }
 public ComponentDataStream(Allocator label)
 {
     m_ComponentDataChanges           = new NativeList <PackedComponentDataChange>(1, label);
     m_DeferredSharedComponentChanges = new NativeList <DeferredPackedSharedComponentDataChange>(1, label);
     m_Payload = new NativeList <byte>(1, label);
 }