Ejemplo n.º 1
0
        /// <summary>
        /// Entityをランダムな位置に生成
        /// </summary>
        /// <param name="onCreateEntity">Entity生成毎に呼ばれるコールバック</param>
        protected void CreateEntitiesFromRandomPosition(UnityAction <Entity, float3> onCreateEntity)
        {
            var look     = Utility.CreateMeshInstanceRenderer(this._dokabenRenderData);
            var halfX    = this._boundSize.x / 2;
            var halfY    = this._boundSize.y / 2;
            var halfZ    = this._boundSize.z / 2;
            var manager  = World.Active.GetExistingManager <EntityManager>();
            var entities = new NativeArray <Entity>(_maxObjectNum, Allocator.Temp, NativeArrayOptions.UninitializedMemory);

            try
            {
                entities[0] = manager.CreateEntity(Archetype);
                manager.SetSharedComponentData(entities[0], look);
                unsafe
                {
                    var ptr  = (Entity *)NativeArrayUnsafeUtility.GetUnsafePtr(entities);
                    var rest = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <Entity>(ptr + 1, entities.Length - 1, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref rest, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
                    manager.Instantiate(entities[0], rest);
                }
                for (int i = 0; i < entities.Length; ++i)
                {
                    onCreateEntity(entities[i], new float3(UnityEngine.Random.Range(-halfX, halfX), UnityEngine.Random.Range(-halfY, halfY), UnityEngine.Random.Range(-halfZ, halfZ)));
                }
            }
            finally
            {
                entities.Dispose();
            }
        }
Ejemplo n.º 2
0
            public NetworkEvent.Type PopEvent(out DataStreamReader bs)
            {
                bs = default;
                if (m_IncomingEvents->Length == 0)
                {
                    return(NetworkEvent.Type.Empty);
                }

                var ev = UnsafeUtility.ReadArrayElement <DriverEvent>(m_IncomingEvents->Ptr, 0);

                if (m_IncomingEvents->Length > 0)
                {
                    //m_IncomingEvents->RemoveAtSwapBack<DriverEvent>(0);
                    m_IncomingEvents->Length--;
                    UnsafeUtility.MemMove(m_IncomingEvents->Ptr, (byte *)m_IncomingEvents->Ptr + sizeof(DriverEvent), sizeof(DriverEvent) * m_IncomingEvents->Length);
                }

                if (ev.Type == NetworkEvent.Type.Data)
                {
                    var slice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <byte>((byte *)m_DataStream->Ptr + ev.StreamOffset, sizeof(byte), ev.Length);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref slice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif

                    bs = new DataStreamReader(slice);
                }

                return(ev.Type);
            }
Ejemplo n.º 3
0
        internal NativeArray <T> ToNativeArray()
        {
            var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <T>(_pointer, Length, Allocator.Invalid);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
            return(array);
        }
Ejemplo n.º 4
0
        public unsafe ElementPool(void *userBuffer, int capacity)
        {
            m_Elements = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <T>(userBuffer, capacity, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref m_Elements, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
            m_DisposeArray   = false;
            m_FirstFreeIndex = -1;
            PeakCount        = 0;
        }
Ejemplo n.º 5
0
        public ElementEnumerable <T> GetElements <T>() where T : unmanaged, IPoolElement
        {
            NativeArray <T> slice = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <T>(m_Elements, PeakCount, Allocator.None);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref slice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
            return(new ElementEnumerable <T> {
                Slice = slice
            });
        }
Ejemplo n.º 6
0
    //-----------------------------------------------------------------------------
    public unsafe static void CopyMatrices(ComponentDataArray <TransformMatrix> transforms, int beginIndex, int length, Matrix4x4[] outMatrices)
    {
        fixed(Matrix4x4 *matricesPtr = outMatrices)
        {
            Assert.AreEqual(sizeof(Matrix4x4), sizeof(TransformMatrix));
            var matricesSlice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <TransformMatrix>(matricesPtr, sizeof(Matrix4x4), length);

                #if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref matricesSlice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
                #endif
            transforms.CopyTo(matricesSlice, beginIndex);
        }
    }
Ejemplo n.º 7
0
    public unsafe static void CopyMatrices(NativeArray <LocalToWorld> transforms, int beginIndex, int length, Matrix4x4[] outMatrices)
    {
        fixed(Matrix4x4 *matricesPtr = outMatrices)
        {
            Assert.AreEqual(sizeof(Matrix4x4), sizeof(LocalToWorld));

            var matricesSlice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <LocalToWorld>(matricesPtr, sizeof(Matrix4x4), length);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref matricesSlice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif

            matricesSlice.CopyFrom(transforms.Slice(beginIndex, length));
        }
    }
Ejemplo n.º 8
0
        // This is the ugly bit, necessary until Graphics.DrawMeshInstanced supports NativeArrays pulling the data in from a job.
        public unsafe static Vector4[] CopyToArray(this NativeSlice <Vector4> src, Vector4[] dst) // where T:struct
        {
            fixed(Vector4 *p = dst)
            {
                UnityEngine.Assertions.Assert.IsTrue(UnsafeUtility.IsBlittable <Vector4>());
                var s = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <Vector4>(p, UnsafeUtility.SizeOf <Vector4>(), src.Length);

                    #if ENABLE_UNITY_COLLECTIONS_CHECKS
                NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref s, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
                    #endif
                s.CopyFrom(src);
            }

            return(dst);
        }
Ejemplo n.º 9
0
        protected NativeArray <T> GetNativeArray <T>(Chunk *chunk) where T : struct, IComponentData
        {
            var hash           = typeof(T).GetHashCode();
            int componentIndex = ArcheType->GetIndex(hash);

            Assert.IsTrue(componentIndex >= 0);
            var buf   = Block.GetComponentDataArray(chunk, componentIndex);
            var len   = Block.GetComponentDataCount(chunk, componentIndex);
            var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <T>(buf, len, Allocator.Persistent);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
            return(array);
        }
Ejemplo n.º 10
0
        // This is the ugly bit, necessary until Graphics.DrawMeshInstanced supports NativeArrays pulling the data in from a job.
        public unsafe static void CopyMatrices(ComponentDataArray <TransformMatrix> transforms, int beginIndex, int length, Matrix4x4[] outMatrices)
        {
            // @TODO: This is using unsafe code because the Unity DrawInstances API takes a Matrix4x4[] instead of NativeArray.
            // We want to use the ComponentDataArray.CopyTo method
            // because internally it uses memcpy to copy the data,
            // if the nativeslice layout matches the layout of the component data. It's very fast...
            fixed(Matrix4x4 *matricesPtr = outMatrices)
            {
                Assert.AreEqual(sizeof(Matrix4x4), sizeof(TransformMatrix));
                var matricesSlice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <TransformMatrix>(matricesPtr, sizeof(Matrix4x4), length);

                    #if ENABLE_UNITY_COLLECTIONS_CHECKS
                NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref matricesSlice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
                    #endif
                transforms.CopyTo(matricesSlice, beginIndex);
            }
        }
        public static unsafe void FromString(this DynamicBuffer <char> buffer, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                buffer.Clear();
                return;
            }

            fixed(char *ptr = name)
            {
                var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <char>(ptr, name.Length, Allocator.None);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
                NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
                buffer.CopyFrom(array);
            }
        }
Ejemplo n.º 12
0
    GetNativeArray <T>(this ReadOnlySpan <T> span) where T : unmanaged
    {
        unsafe
        {
            fixed(void *ptr = &span.GetPinnableReference())
            {
                var array = NativeArrayUnsafeUtility.
                            ConvertExistingDataToNativeArray <T>
                                (ptr, span.Length, Allocator.None);

                #if ENABLE_UNITY_COLLECTIONS_CHECKS
                var handle = AtomicSafetyHandle.GetTempUnsafePtrSliceHandle();
                NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, handle);
                #endif

                return(array);
            }
        }
    }
Ejemplo n.º 13
0
    GetNativeSlice <T>(this ReadOnlySpan <T> span, int offset, int stride)
        where T : unmanaged
    {
        fixed(void *ptr = &span.GetPinnableReference())
        {
            var headPtr      = (T *)ptr + offset;
            var strideInByte = sizeof(T) * stride;
            var elementCount = span.Length / stride - offset / stride;

            var slice =
                NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <T>
                    (headPtr, strideInByte, elementCount);

          #if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeSliceUnsafeUtility.SetAtomicSafetyHandle
                (ref slice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
          #endif

            return(slice);
        }
    }
Ejemplo n.º 14
0
    public static unsafe void CopyIntegers(NativeList <int> src, List <int> dst)
    {
        if (dst.Capacity < src.Length)
        {
            dst.Capacity = src.Length;
        }

        var array = NoAllocHelpers.ExtractArrayFromListT(dst);

        fixed(int *arrayPtr = array)
        {
            var dstSlice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <int>(arrayPtr, sizeof(int), src.Length);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref dstSlice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
            dstSlice.CopyFrom((NativeArray <int>)src);
        }

        NoAllocHelpers.ResizeList(dst, src.Length);
    }
Ejemplo n.º 15
0
        static unsafe int CopyMatrices()
        {
            int length = native_sprite_data_list_.Length;

            if (length == 0)
            {
                return(0);

                fixed(Matrix4x4 *ptr = managed_matrix_list_)
                {
                    Assert.IsTrue(native_sprite_data_list_.Length <= BULK_NUM);
                    Assert.AreEqual(sizeof(Matrix4x4), sizeof(SpriteData));
                    var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <SpriteData>(ptr, length, Allocator.Persistent);

            #if ENABLE_UNITY_COLLECTIONS_CHECKS
                    NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
            #endif
                    native_sprite_data_list_.CopyTo(array);
                }

                return(length);
        }
Ejemplo n.º 16
0
        public unsafe void SetComponentData <T>(Entity entity, T componentData) where T : struct, IComponentData
        {
            var data = _dataManager.Get(entity.Index);

            if (data->ArcheType == null)
            {
                return;
            }
            var block          = _componentBlockManager.GetOrCreateBlock(data->ArcheType);
            var hash           = typeof(T).GetHashCode();
            int componentIndex = data->ArcheType->GetIndex(hash);

            Assert.IsTrue(componentIndex >= 0);
            var buf   = block.GetComponentDataArray(data->Chunk, componentIndex);
            var len   = block.GetComponentDataCount(data->Chunk, componentIndex);
            var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <T>(buf, len, Allocator.Persistent);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
            array[data->IndexInChunk] = componentData;
        }
            public void Execute()
            {
                UnityEngine.Assertions.Assert.AreEqual(sizeof(Matrix4x4), sizeof(EntityInstanceRendererTransform));
                var matricesSlice = Unity.Collections.LowLevel.Unsafe.NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <EntityInstanceRendererTransform>(matricesPtr, sizeof(Matrix4x4), length);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
                Unity.Collections.LowLevel.Unsafe.NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref matricesSlice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
                transforms.CopyTo(matricesSlice, beginIndex);
            }
        public unsafe static void CopyMatrices(ComponentDataArray <EntityInstanceRendererTransform> transforms, int beginIndex, int length, Matrix4x4[] outMatrices)
        {
            // @TODO: This is only unsafe because the Unity DrawInstances API takes a Matrix4x4[] instead of NativeArray.
            ///       And we also want the code to be really fast.
            fixed(Matrix4x4 *matricesPtr = outMatrices)
            {
                UnityEngine.Assertions.Assert.AreEqual(sizeof(Matrix4x4), sizeof(EntityInstanceRendererTransform));
                var matricesSlice = Unity.Collections.LowLevel.Unsafe.NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice <EntityInstanceRendererTransform>(matricesPtr, sizeof(Matrix4x4), length);

                    #if ENABLE_UNITY_COLLECTIONS_CHECKS
                Unity.Collections.LowLevel.Unsafe.NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref matricesSlice, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
                    #endif
                transforms.CopyTo(matricesSlice, beginIndex);
            }
        }
Ejemplo n.º 19
0
#pragma warning restore 0649
        #endregion // Private Fields(Editable)


        // ----------------------------------------------------
        #region // Unity Events

        /// <summary>
        /// MonoBehaviour.Start
        /// </summary>
        void Start()
        {
            // Worldの作成
            World.Active = new World("Sample World");
            EntityManager entityManager = World.Active.CreateManager <EntityManager>();

            World.Active.CreateManager(typeof(EndFrameTransformSystem));
            World.Active.CreateManager(typeof(RenderingSystemBootstrap));
            World.Active.CreateManager(typeof(PlayerMove), Camera.main.transform, this.Range);
            World.Active.CreateManager(typeof(ColliderUpdate));

            if (this._isSplitSpace)
            {
                // 衝突判定(空間分割)
                World.Active.CreateManager(typeof(SplitSpaceCollisionSystem));
            }
            else
            {
                // 衝突判定(総当たり)
                World.Active.CreateManager(typeof(CollisionSystem));
            }
            var destroyBarrier = World.Active.CreateManager <DestroyBarrier>();

            World.Active.CreateManager(typeof(DestroySystem), destroyBarrier);

            ScriptBehaviourUpdateOrder.UpdatePlayerLoop(World.Active);

            // create player entity.
            var playerArchetype = entityManager.CreateArchetype(
                ComponentType.Create <Position>(), ComponentType.Create <Rotation>(), ComponentType.Create <Scale>(),
                ComponentType.Create <Player>(), ComponentType.Create <SphereCollider>(),
                ComponentType.Create <MeshInstanceRenderer>());
            var playerEntity = entityManager.CreateEntity(playerArchetype);

            entityManager.SetSharedComponentData(playerEntity, this._playerLook);
            entityManager.SetComponentData(playerEntity, new Position {
                Value = new float3(0)
            });
            entityManager.SetComponentData(playerEntity, new Scale {
                Value = new float3(PlayerScale)
            });
            entityManager.SetComponentData(playerEntity, new SphereCollider {
                Radius = SphereColliderRadius * PlayerScale
            });

            // create check hit entities.
            var checkHitArchetype = entityManager.CreateArchetype(
                ComponentType.Create <Position>(), ComponentType.Create <Rotation>(),
                ComponentType.Create <CheckHit>(), ComponentType.Create <SphereCollider>(),
                ComponentType.Create <Destroyable>(),
                ComponentType.Create <MeshInstanceRenderer>());

            // Entityの生成(各種ComponentData/SharedComponentDataの初期化)
            // やっている事としては以下のリンクを参照。
            // - https://qiita.com/pCYSl5EDgo/items/18f1827a5b323a7712d7
            var entities = new NativeArray <Entity>(MaxObjectNum, Allocator.Temp, NativeArrayOptions.UninitializedMemory);

            try
            {
                entities[0] = entityManager.CreateEntity(checkHitArchetype);

                // MeshInstanceRendererに対するデータの設定
                entityManager.SetSharedComponentData(entities[0], this._checkHitLook);
                unsafe
                {
                    var ptr  = (Entity *)NativeArrayUnsafeUtility.GetUnsafePtr(entities);
                    var rest = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <Entity>(ptr + 1, entities.Length - 1, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref rest, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
                    entityManager.Instantiate(entities[0], rest);
                }

                // 各種ComponentDataの設定
                for (int i = 0; i < MaxObjectNum; ++i)
                {
#if ENABLE_DEBUG
                    // テスト用. 横一列に配置
                    entityManager.SetComponentData(entities[i], new Position {
                        Value = new float3(5 + (i * 10), 0, 0)
                    });
#else
                    // ランダムに配置
                    entityManager.SetComponentData(entities[i], new Position {
                        Value = this.GetRandomPosition()
                    });
#endif

                    entityManager.SetComponentData(entities[i], new SphereCollider {
                        Radius = SphereColliderRadius * CheckHitScale
                    });
                }
            }
            finally
            {
                entities.Dispose();
            }
        }